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.

chore(replay): remove the last session summarization remnants (#83019)

Tue Haulund2a03f1115992
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.yml
index 65e4f13544cf..5c76c29ac978 100644
--- a/.github/workflows/container-images-cd.yml
+++ b/.github/workflows/container-images-cd.yml
@@ -505,7 +505,7 @@ jobs:
- name: Check for changes that affect video export temporal worker
id: check_changes_video_export_temporal_worker
run: |
- if git diff --name-only HEAD^ HEAD | grep -qE '^posthog/temporal/exports_video|^posthog/tasks/exports/video_exporter.py|^products/signals/backend/|^products/signals/skills/|^products/review_hog/backend/|^products/business_knowledge/backend/|^products/warehouse_sources/backend/temporal/data_imports/workflow_activities/emit_signals|^products/signals/backend/emission/|^nodejs/src/scripts/record-replay|^ee/hogai/session_summaries|^posthog/temporal/common|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then
+ if git diff --name-only HEAD^ HEAD | grep -qE '^posthog/temporal/exports_video|^posthog/tasks/exports/video_exporter.py|^products/signals/backend/|^products/signals/skills/|^products/review_hog/backend/|^products/business_knowledge/backend/|^products/warehouse_sources/backend/temporal/data_imports/workflow_activities/emit_signals|^products/signals/backend/emission/|^nodejs/src/scripts/record-replay|^posthog/temporal/common|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then
echo "changed=true" >> $GITHUB_OUTPUT
else
echo "changed=false" >> $GITHUB_OUTPUT
@@ -514,7 +514,7 @@ jobs:
- name: Check for changes that affect session replay temporal worker
id: check_changes_session_replay_temporal_worker
run: |
- if git diff --name-only HEAD^ HEAD | grep -qE '^posthog/temporal/session_replay/|^ee/hogai/session_summaries|^posthog/temporal/common|^products/signals/backend/|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then
+ if git diff --name-only HEAD^ HEAD | grep -qE '^posthog/temporal/session_replay/|^posthog/temporal/common|^products/signals/backend/|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then
echo "changed=true" >> $GITHUB_OUTPUT
else
echo "changed=false" >> $GITHUB_OUTPUT
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 0836afdbb51f..3a821da6fe35 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6117,7 +6117,7 @@ snapshots:
scenes-app-experiments--experiment-with-mean-metric--light:
hash: v1.k794b7964.653360b3d5a6ccefeddbac9bf7743def00cc3d15ff2676d6f54b0999453ebad1.3Hczx7-pcdwGchm84XBbwOf3d5eDSGXXriZRkKvek9Q
scenes-app-experiments--experiment-with-multi-step-funnel-metric--dark:
- hash: v1.k794b7964.6c73e20e6bcfbd467e8e9dea7f6cbcd9d05ba8f99b99879a366d5fc14ae1d296.6QHCgNYcXclmThjruFfmFpJsfM5oode4JC1elbpZ-rE
+ hash: v1.k794b7964.b59d17fc7aa41c9d54d50ebcad07ee995472e82d0509a99a3534f689402d8014.SWRehUneMfgPHvrdCTfEc6TWMR2LSyxma5jGOhO-iSA
scenes-app-experiments--experiment-with-multi-step-funnel-metric--light:
hash: v1.k794b7964.0f81873b7b3e44139ef64b33d35aaa9c9857943789e7f88fe0dd8eb9d84b6125.0yFYuT8reEOckBG0v7K4CTlrcHgCWGlaDbiVhp7Euck
scenes-app-experiments--experiment-with-multiple-metrics--dark:
@@ -6441,21 +6441,21 @@ snapshots:
scenes-app-inbox-pullrequestdiffview--truncated--light:
hash: v1.k794b7964.58a507666519d2ad2f2a5247605b2c903180639eae9e43580992de250bc8f258._lKwsnOWccjuN6S_pd8IgOfKLzqnIvVqmTh1uETW-TY
scenes-app-inbox-scene--empty--dark:
- hash: v1.k794b7964.3342b9e88244f5f5e59b9a98df7d51ee9acd70aa27881c276ee843eca23e5528.DA1w6v4HKI-i7mwEaUSUJLrrkANbxtZbPvlKifpaqys
+ hash: v1.k794b7964.37705b8ab767e1c52a18fa3759cdde234d8dedd7a57bb03c7ad0396c7531f602.D2jNHc3iW6nIAvhAO5XuVCNAgCpk-URO2YKfROisz3Q
scenes-app-inbox-scene--empty--light:
- hash: v1.k794b7964.9843212b09fb91920cda765af021e0e1d3a44e4ad9443f7918fb9065149d1c3f.7R3Gqufkumc-BQrIXQor3MZgqL6IT1PLSj4ZNqKOQP4
+ hash: v1.k794b7964.f7edb21a2afcad5f2af8e440b0dbe23ac55be93c4d5166f1f225c1e6f41e365c.5r4NDhjB9-Np5FEplm9lHFLUTAnF6dgZFDaANsKPfzs
scenes-app-inbox-scene--empty-control--dark:
hash: v1.k794b7964.99ffca71975a423bd8ef679c361fd0bf4b9a1f6be6d4f4dfe82b69a9637184af.NwEat2sZEU9_PcNSbsxCt1SZBzTzyQJbewP-ZpJZOM4
scenes-app-inbox-scene--empty-control--light:
hash: v1.k794b7964.0bd8154cc24c9f19aef821da27d873001473634e8c8e4868d414d9204b35c58f.ATQvLBhDOPKTDa3bKkfGKcPytCuMGpk_mBtOdv-f3WQ
scenes-app-inbox-scene--empty-with-many-scouts--dark:
- hash: v1.k794b7964.6f8bb823b1f76abd54fcedbf1a2bc02abaaea0ad940850ffc2d7f553a667a0c3.JO8Wwe3Wtz2B309Qv67RkEn_SXeiUUZSHqlP9wW9Dew
+ hash: v1.k794b7964.32ea8aa91e71baa9a72b403c44731aa97bff8282b6bd9d5041b4537a50825060.G9RYZ-ZdAGxc4hcvryNgiAmH5xsqtHIj8mjKeXCZpJI
scenes-app-inbox-scene--empty-with-many-scouts--light:
- hash: v1.k794b7964.4757fdc3e6603cc7752cffdf45421aa24d8551754e9b5cca04569ed5c9577a26.k0mDZb6DY2eTMFjNrG2mi_0Dbhcrho9A4MhjjH5KlCM
+ hash: v1.k794b7964.57cc628441b89eaebc408c9c0103615965dcfd9ba4c8b8e62b6de53763f3343c.3OXdEJ2GFbqX23EOaks1SZLNZJzdXhhysDckPTnKqF4
scenes-app-inbox-scene--inbox--dark:
- hash: v1.k794b7964.6938f54b10a00b66cd90158043512d6b056ac3bf97e291fa5961529af56ba084.noXScllvtHLNl8e7c7bKckMTjf-O9lC0OuvKdUKVT7o
+ hash: v1.k794b7964.98816a7cdb21dd76c051dfcaf72207419c2808d5f8416a5d4179a9887b773951.LqtL3huPg1dw9HUbUfuVmtbkFBiY7heyiWdio3IfBCg
scenes-app-inbox-scene--inbox--light:
- hash: v1.k794b7964.21ae4235f9bc3c8f39fc33259edc39f53e06baaeb37f679f3badd771b986b86a.AoPLxHhT6028ylYpVRlXQUVgqm6ckEBiLWWwCovU7DQ
+ hash: v1.k794b7964.c649a0e2c22cc7b0ad4061ee1b0f1174c0dfd02c54de0ea3318264e1cb92fd05.tuklmIWKUczz3ewHyxwiKq9p2et0W-ZSxocgEFBCEw0
scenes-app-inbox-scene--installing-self-driving--dark:
hash: v1.k794b7964.d2c648fd6ea8079c6746f4b5e979cac53dbd928dd06990c3bac2031eeaba12be.rCs94UBn0krUWBSp28BM_f7Jo4Smc85JTXR_iWzDjoY
scenes-app-inbox-scene--installing-self-driving--light:
@@ -6485,33 +6485,33 @@ snapshots:
scenes-app-inbox-scoutmcpserverspicker--scout-settings-variant--light:
hash: v1.k794b7964.2f1013abc412adb4544bca6a00209d3051c46969db69d4242ab201ecf5d189f3.YVfbrzpaRzPwuCbeFXmaVOLla0fvhHmAm1CkuaKWCLI
scenes-app-inbox-signalsourcespanel--armed-but-tools-off--dark:
- hash: v1.k794b7964.dad07e3272e433a69b81e55d5fac37d75d3f743154490c1ff3c5ef57d657be16.4cTh_S35TMTgXe_HQWzOP8HRN-aUWN9DNUKLTgmMoj4
+ hash: v1.k794b7964.6747f0e7e69605654f1d01460a103c36935d8f6b03cc46d5ccb553d5537451e8.0RmRYEmcbsdEoazRnDeW87aVR0xoagYioC-rco63co4
scenes-app-inbox-signalsourcespanel--armed-but-tools-off--light:
- hash: v1.k794b7964.1dc995875cf262796b527a1e889516ac2b7a8514eb19d4f1b4137fb8eabca975.i_K2jMotSMF-ykCtoZTBzMyA08PV9wDLJEX094kIBD0
+ hash: v1.k794b7964.09478dcd17ef5eca59d8ca0fd2f743cc6567f7a1bf0a0b1696c8af470c455765.PWv_h7qQqQncL_sclGpghIsiUSrBZH2qF-heJBPFsak
scenes-app-inbox-signalsourcespanel--arming-blocked--dark:
- hash: v1.k794b7964.71ac42fd1e7056933699992aef59540c49eedbce96c3c3ca368e5e538826b960.tWa3l92wgH6yKpa_aYVatJxPnr2wbjTmD89LtEb4K80
+ hash: v1.k794b7964.77eec4902b872f0a9e099844c9d546fca76269183de75bb2f81dedbea8231692.HzFIcX0ZhPWVf6Ilrt9Uwii07Ir1PYLpagaBIvwTpXc
scenes-app-inbox-signalsourcespanel--arming-blocked--light:
- hash: v1.k794b7964.9ad76d414d11155032f260e4c4b69ba1986e3b4163c1f2e469c32592d6ac0443.aLsMiwnupJOQHp3IwrdT9Qq7pAkg2vPWZ-Bh7p7d0rA
+ hash: v1.k794b7964.55f973b3d21ebf7e25e20a8b95bd70648abd5890fa472e381cf9b41bdd05ebe0.-VvwSfM-FXhabZd47zV7E11f0C9FMt0zrW6wuOKVkiM
scenes-app-inbox-signalsourcespanel--event-definitions-unavailable--dark:
- hash: v1.k794b7964.beeb4d600d3133a633bee704a0c3d791aac5439ad4f946155106890e0a4405f6.u9204AKTy8nWE2WDB2FU61BrNvuRTVlLpJCvT3BaC-Y
+ hash: v1.k794b7964.49d77d5da449f14d7d5ac3dedd952f1db0027138a3cb1f1ebbcb740e290cdad9.a6y-0D3q4ixuUQr4jlqaFDdnUA3Z0sGzJzv46wmbPNg
scenes-app-inbox-signalsourcespanel--event-definitions-unavailable--light:
- hash: v1.k794b7964.081a1fad69c387c67c550c79755130e9dfaa61d7fad58175369f614bf27d7728.CbM3vQfjDPLXTNpGz15hJ77Jyi_dIM5Dd3vT5B-bGL4
+ hash: v1.k794b7964.a34bc31c56796ca2ad8883ebdc34df811f475def77e2855015d96d3ecbc86a84.aiy32uolR6W1o915BKzGg1vxFQgX2QYAsj1HLtlBSME
scenes-app-inbox-signalsourcespanel--everything-healthy--dark:
- hash: v1.k794b7964.b2e233f272369c041fef33328ee9683c2a30adfb34879ed984f9991169cf4b37.oZfVzcukSDS6iHVPB-r5SP1SA6159eg7eTyloqIZiUs
+ hash: v1.k794b7964.44df353cdbb0659a024d5a8ac22101d508bddedb029ee6abd66b5fef85dec1d4.kbUJrXu5MzaCudWv5B5N0lyJQ8Pj7mpwCX7zwlm7U4k
scenes-app-inbox-signalsourcespanel--everything-healthy--light:
- hash: v1.k794b7964.4a7d5460e801fb9c14851b428f597f53b69ac1506477ab425435acc0f35f586b.-WgldiC8BrGdolvo-S2sZtbqEwZDI6RKV5erZt1OG9w
+ hash: v1.k794b7964.da01cfb8b29b94c98e473e5a1c9b0cd23a894133a49e06b0f58a309efe61249e.m7YYe9eopd42q0soUqtbxpEafkikgrw23-6TxA1TyDQ
scenes-app-inbox-signalsourcespanel--playground--dark:
- hash: v1.k794b7964.732341765db75db485563342ff39953106c2809ade1b19af0b15916f0646c861.JqgudGUmBZ8yStkJGvGciMbhZUa19nVI4Xw8tuUFJSw
+ hash: v1.k794b7964.e625ebc1278bfb5b0a632eceee8af8ecfb9a3291b59113ae83e4cd6dc7e058ec.5hpxYodVx0pNTY4vVAGgXxDBstLhSX1inisoXXTbSO0
scenes-app-inbox-signalsourcespanel--playground--light:
- hash: v1.k794b7964.5f876c8877cf09dd4599907541d5ab1a39cb18c60dd310bbd058f0a374fedbf7.GdDUQqucO1cCIO9HAn_RtLEDpLrsX-42lqsR7jweyGY
+ hash: v1.k794b7964.22974fb177402f5d8a0f4932f4fa1bccf3bf9b6599fc3509a9e1aef016da050d.olKbQ6bu27HnLBU5pYoNzLNLRfPRw2PGcsU0hTNNj8g
scenes-app-inbox-signalsourcespanel--server-side-exceptions-only--dark:
- hash: v1.k794b7964.732341765db75db485563342ff39953106c2809ade1b19af0b15916f0646c861.EthjU6-rAzHWPSErj2I4YXi8idPhAtwQHiFjb1g6K4k
+ hash: v1.k794b7964.e625ebc1278bfb5b0a632eceee8af8ecfb9a3291b59113ae83e4cd6dc7e058ec.3lmRhERqp25v4IsVCtNTVZr6Cw1OE9fxNpEEegGXFcc
scenes-app-inbox-signalsourcespanel--server-side-exceptions-only--light:
- hash: v1.k794b7964.5f876c8877cf09dd4599907541d5ab1a39cb18c60dd310bbd058f0a374fedbf7.pItXtECs25b0CNhjmEOvmQwTwhP6maPVMzODmQaewPE
+ hash: v1.k794b7964.22974fb177402f5d8a0f4932f4fa1bccf3bf9b6599fc3509a9e1aef016da050d.-sF41j5D471cLEZ2XTWH5vPxeeL0Ncb-j_4RUVa0FFI
scenes-app-inbox-signalsourcespanel--tools-on-no-recent-data--dark:
- hash: v1.k794b7964.ede380c1b6b227061209acd70a462e7742b56a16dd71f57c3f9cc7fb776432c2.Vizn91fzHqZGfZShQPQtrGi2mpaSScoYuuEUxjJ3sdw
+ hash: v1.k794b7964.6520781eb2e2bf411a83cd78a25b13b7e222e31d52584d6fa8427a6905117757.Zdlz_WiWEU2EjHNjO27QzC8yd168RuPToMNSiIq1VrA
scenes-app-inbox-signalsourcespanel--tools-on-no-recent-data--light:
- hash: v1.k794b7964.0912985d46e913d5e8760dbd1c2e66c60ac291e4445527acd2442a28319582b9.-SPPzUlkJMTWDPCpGJNtVE-T22zWyDhEhxjesNCcx98
+ hash: v1.k794b7964.5945b2460886f8db3e09a08c6edf74faeda0730487f2bef9ccf9825f5faae281.su94KwLO8C9OBu4Jdwl9HMaRG4pI78QWeDwWlFcWkzU
scenes-app-inbox-tabs--pull-requests--dark:
hash: v1.k794b7964.474d8e744637e08afd4bb7540f0f5dafd6a79342c2f547188cb436b55f9ef8e7.PiyD1Zkhkot-_DKLU3W0T5uA7rvpTUTn5bKChCa3AV4
scenes-app-inbox-tabs--pull-requests--light:
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index b9493a70b0d1..c691c14b4c07 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -5157,9 +5157,6 @@ const api = {
}): Promise<CountedPaginatedResponse<SignalReport>> {
return await new ApiRequest().signalReports().withQueryString(params).get()
},
- async analyzeSessions(): Promise<Record<string, any>> {
- return await new ApiRequest().signalReports().withAction('analyze_sessions').create()
- },
async get(id: SignalReport['id']): Promise<SignalReport> {
return await new ApiRequest().signalReport(id).get()
},
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 81925cf27637..de4431c9ba7b 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -48367,9 +48367,6 @@
},
"type": "array"
},
- "has_summary": {
- "type": "boolean"
- },
"id": {
"type": "string"
},
diff --git a/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx b/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx
index fc16a1faa693..e645775a282d 100644
--- a/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx
+++ b/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx
@@ -44,9 +44,7 @@ export function LangGraphActivity({
const uiPayloadBody =
toolCall && uiPayload && isRenderableUIPayloadTool(toolCall.name, uiPayload)
? Object.entries(uiPayload)
- .filter(
- ([toolName]) => toolName !== 'summarize_sessions' && toolName !== 'summarize_website_interactions'
- )
+ .filter(([toolName]) => toolName !== 'summarize_website_interactions')
.map(([toolName, toolPayload]) => (
<UIPayloadAnswer
key={`${result?.tool_call_id}-${toolName}`}
diff --git a/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx b/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx
index d3f74934adda..5a196318eda5 100644
--- a/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx
+++ b/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx
@@ -18,7 +18,6 @@ import { AnnotatedScreenshotView, parseAnnotatedScreenshot } from './AnnotatedSc
export const RENDERABLE_UI_PAYLOAD_TOOLS: AssistantTool[] = [
'search_session_recordings',
'search_error_tracking_issues',
- 'summarize_sessions',
'create_form',
]
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 102c6ffe7c17..afe1502956c3 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2088,7 +2088,6 @@ export interface SessionRecordingType {
expiry_time?: string
/** Number of whole days left until the recording expires. */
recording_ttl?: number
- has_summary?: boolean
/** External references to third party issues. */
external_references?: SessionRecordingExternalReference[]
/** False when the recording was included in list results via a direct link despite not matching the filters. */
diff --git a/posthog/api/project.py b/posthog/api/project.py
index a73689a6e9f4..114b57382d63 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -120,7 +120,6 @@ from products.notifications.backend.facade.api import (
TargetType,
create_notification,
)
-from products.signals.backend.models import SignalSourceConfig
from ee.api.rbac.access_control import AccessControlViewSetMixin
from ee.api.rbac.access_control_settings import AccessControlSettingsViewSetMixin
@@ -1248,21 +1247,6 @@ class ProjectBackwardCompatSerializer(
team.refresh_from_db()
set_team_in_cache(team.api_token, team)
- if "proactive_tasks_enabled" in validated_data:
- if validated_data["proactive_tasks_enabled"]:
- SignalSourceConfig.objects.get_or_create(
- team=team,
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- defaults={"enabled": True, "config": {}, "created_by": self.context["request"].user},
- )
- else:
- SignalSourceConfig.objects.filter(
- team=team,
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- ).delete()
-
project_after_update = instance.__dict__.copy()
team_changes = dict_changes_between("Team", team_before_update, team_after_update, use_field_exclusions=True)
project_changes = dict_changes_between(
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 1e0cc05e0875..22f59242a304 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -110,7 +110,6 @@ from posthog.utils import (
from products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfig
from products.feature_flags.backend.models.evaluation_context import EvaluationContext, normalize_context_name
from products.logs.backend.models import TeamLogsConfig
-from products.signals.backend.models import SignalSourceConfig
from products.workflows.backend.models.team_workflows_config import EmailTrackingConsentMode, TeamWorkflowsConfig
tracer = trace.get_tracer(__name__)
@@ -1912,22 +1911,6 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
set_team_in_cache(instance.api_token, instance)
updated_team = instance
- if "proactive_tasks_enabled" in validated_data:
- # Backward compat for old proactive tasks enabled field, remove after February 2026
- if validated_data["proactive_tasks_enabled"]:
- SignalSourceConfig.objects.get_or_create(
- team=instance,
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- defaults={"enabled": True, "config": {}, "created_by": self.context["request"].user},
- )
- else:
- SignalSourceConfig.objects.filter(
- team=instance,
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- ).delete()
-
changes = dict_changes_between("Team", before_update, after_update, use_field_exclusions=True)
log_activity(
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 3b16421a1e77..e3649cb4c7c5 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -1945,69 +1945,6 @@ def team_api_test_factory():
self.assertEqual(self.team.session_recording_opt_in, True)
self.assertEqual(self.team.surveys_opt_in, True)
- @override_settings(DEBUG=True)
- def test_update_proactive_tasks_enabled_true_creates_signal_source_config(self):
- from products.signals.backend.models import SignalSourceConfig
-
- response = self.client.patch("/api/environments/@current/", {"proactive_tasks_enabled": True})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- self.assertTrue(
- SignalSourceConfig.objects.filter(
- team=self.team,
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- enabled=True,
- ).exists()
- )
-
- @override_settings(DEBUG=True)
- def test_update_proactive_tasks_enabled_false_deletes_signal_source_config(self):
- from products.signals.backend.models import SignalSourceConfig
-
- SignalSourceConfig.objects.create(
- team=self.team,
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- enabled=True,
- config={},
- )
-
- response = self.client.patch("/api/environments/@current/", {"proactive_tasks_enabled": False})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- self.assertFalse(
- SignalSourceConfig.objects.filter(
- team=self.team,
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- ).exists()
- )
-
- @override_settings(DEBUG=True)
- def test_update_proactive_tasks_enabled_true_is_idempotent(self):
- from products.signals.backend.models import SignalSourceConfig
-
- SignalSourceConfig.objects.create(
- team=self.team,
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- enabled=True,
- config={},
- )
-
- response = self.client.patch("/api/environments/@current/", {"proactive_tasks_enabled": True})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- self.assertEqual(
- SignalSourceConfig.objects.filter(
- team=self.team,
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- ).count(),
- 1,
- )
-
def test_can_set_session_recording_trigger_groups(self):
"""Test that we can create and update session_recording_trigger_groups field"""
trigger_groups = {
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 654ac59ca115..9a75d1360c13 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -113,10 +113,6 @@ from posthog.temporal.session_replay.enforce_max_replay_retention import (
ENFORCE_MAX_REPLAY_RETENTION_ACTIVITIES,
ENFORCE_MAX_REPLAY_RETENTION_WORKFLOWS,
)
-from posthog.temporal.session_replay.gemini_cleanup_sweep import (
- GEMINI_CLEANUP_SWEEP_ACTIVITIES,
- GEMINI_CLEANUP_SWEEP_WORKFLOWS,
-)
from posthog.temporal.session_replay.rasterize_recording import (
RASTERIZE_RECORDING_ACTIVITIES,
RASTERIZE_RECORDING_WORKFLOWS,
@@ -421,16 +417,14 @@ _task_queue_specs = [
),
(
settings.SESSION_REPLAY_TASK_QUEUE,
- GEMINI_CLEANUP_SWEEP_WORKFLOWS
- + COUNT_PLAYLIST_ITEMS_WORKFLOWS
+ COUNT_PLAYLIST_ITEMS_WORKFLOWS
+ DELETE_RECORDINGS_WORKFLOWS
+ ENFORCE_MAX_REPLAY_RETENTION_WORKFLOWS
+ RASTERIZE_RECORDING_WORKFLOWS
+ REPLAY_COUNT_METRICS_WORKFLOWS
+ SURFACING_SCORE_EXPORT_SWEEP_WORKFLOWS
+ SURFACING_SCORING_SWEEP_WORKFLOWS,
- GEMINI_CLEANUP_SWEEP_ACTIVITIES
- + COUNT_PLAYLIST_ITEMS_ACTIVITIES
+ COUNT_PLAYLIST_ITEMS_ACTIVITIES
+ DELETE_RECORDINGS_ACTIVITIES
+ ENFORCE_MAX_REPLAY_RETENTION_ACTIVITIES
+ RASTERIZE_RECORDING_ACTIVITIES
diff --git a/posthog/schema.py b/posthog/schema.py
index 983f83789e5e..f528a571994a 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -6805,7 +6805,6 @@ class SessionRecordingType(BaseModel):
external_references: list[SessionRecordingExternalReference] | None = Field(
default=None, description="External references to third party issues."
)
- has_summary: bool | None = None
id: str
inactive_seconds: float | None = None
keypress_count: float | None = None
diff --git a/posthog/session_recordings/ai_summary_cap.py b/posthog/session_recordings/ai_summary_cap.py
deleted file mode 100644
index 4af6adaba667..000000000000
--- a/posthog/session_recordings/ai_summary_cap.py
+++ /dev/null
@@ -1,204 +0,0 @@
-"""Per-team monthly hard cap for Replay Vision summaries.
-
-Backstop against runaway LLM cost. One Redis counter per team per calendar
-month; auto-resets on the 1st. A team can use up to 2x the cap across a month
-boundary — fine for a backstop, not for billing.
-
-Cap value: `DEFAULT_MAX_SUMMARIES_PER_PERIOD`, optionally lowered (never
-raised) by `SignalSourceConfig.config["max_summaries_per_period"]`.
-
-Importable from both DRF and Temporal activities — keep this module
-dependency-light.
-"""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from datetime import UTC, datetime
-
-import structlog
-from redis.exceptions import ResponseError
-
-from posthog.redis import get_client
-
-logger = structlog.get_logger(__name__)
-
-# Bump in a deploy. Per-team lowering is allowed via SignalSourceConfig.
-DEFAULT_MAX_SUMMARIES_PER_PERIOD = 2500
-
-# JSON key on SignalSourceConfig.config.
-CONFIG_KEY = "max_summaries_per_period"
-
-_REDIS_KEY_PREFIX = "posthog/replay-summary-cap"
-
-# 32 days — slightly longer than any month so the bucket outlives its read
-# window. Redis GCs the key on its own.
-_KEY_TTL_SECONDS = 32 * 24 * 60 * 60
-
-
-@dataclass(frozen=True)
-class CapDecision:
- allowed: bool
- used: int
- cap: int
-
-
-def coerce_max_summaries_per_period(value: object) -> int:
- """Validate a raw cap override value. Anything malformed falls back to
- the default — admin JSON should never take down the summarize path.
-
- Bools are rejected explicitly because they inherit from int and would
- otherwise coerce to 0/1.
- """
- if value is None or isinstance(value, bool):
- return DEFAULT_MAX_SUMMARIES_PER_PERIOD
- if not isinstance(value, (int, float, str, bytes, bytearray)):
- return DEFAULT_MAX_SUMMARIES_PER_PERIOD
- try:
- cap = int(value)
- except (ValueError, OverflowError):
- return DEFAULT_MAX_SUMMARIES_PER_PERIOD
- if cap <= 0:
- return DEFAULT_MAX_SUMMARIES_PER_PERIOD
- return cap
-
-
-def get_cap_for_team(team_id: int) -> int:
- """Return the effective per-team monthly cap.
-
- The override on `SignalSourceConfig.config` can only LOWER the default —
- never raise it. Project members can edit that config row via API, so
- treating it as a raise vector would be a privilege escalation around the
- backstop.
- """
- # Lazy import: this module is imported by Temporal activities that load
- # before Django apps.
- from products.signals.backend.models import SignalSourceConfig
-
- row = (
- SignalSourceConfig.objects.filter(
- team_id=team_id,
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- )
- .only("config")
- .first()
- )
- if row is None or not isinstance(row.config, dict):
- return DEFAULT_MAX_SUMMARIES_PER_PERIOD
- override = coerce_max_summaries_per_period(row.config.get(CONFIG_KEY))
- return min(override, DEFAULT_MAX_SUMMARIES_PER_PERIOD)
-
-
-def _redis_key(team_id: int, *, now: datetime | None = None) -> str:
- bucket = (now or datetime.now(UTC)).strftime("%Y-%m")
- return f"{_REDIS_KEY_PREFIX}:{team_id}:{bucket}"
-
-
-def current_usage(team_id: int, *, now: datetime | None = None) -> int:
- raw = get_client().get(_redis_key(team_id, now=now))
- if raw is None:
- return 0
- try:
- return int(raw)
- except (TypeError, ValueError):
- # Corrupt key — log and treat as zero so summaries don't break.
- logger.warning("replay_summary_cap.corrupt_counter", team_id=team_id, raw=raw)
- return 0
-
-
-def headroom(team_id: int, *, now: datetime | None = None) -> int:
- """Remaining quota for the team this month. Never negative.
-
- Used by the autonomous sweep to slice its dispatch list before starting
- children, otherwise a runaway sweep could starve interactive DRF users.
- """
- return max(0, get_cap_for_team(team_id) - current_usage(team_id, now=now))
-
-
-def _incrby(client, key: str, n: int) -> int:
- """INCRBY with WRONGTYPE recovery. Returns the new counter value.
-
- Recovery: if somebody SET the key to a non-integer string, reset it and
- retry. Losing the (uncountable) prior usage is fine for a backstop.
- """
- try:
- return int(client.incrby(key, n))
- except ResponseError:
- logger.warning("replay_summary_cap.corrupt_counter_on_write", key=key)
- client.delete(key)
- return int(client.incrby(key, n))
-
-
-def consume_summary_quota(team_id: int, n: int = 1, *, now: datetime | None = None) -> int:
- """Increment the counter by `n`. Sets TTL on first write. Returns the new
- value. No bound check — caller is responsible for that."""
- if n <= 0:
- return current_usage(team_id, now=now)
- key = _redis_key(team_id, now=now)
- client = get_client()
- new_value = _incrby(client, key, n)
- # First write of the month: set the TTL so abandoned keys GC themselves.
- if new_value == n:
- client.expire(key, _KEY_TTL_SECONDS)
- return new_value
-
-
-def atomic_check_and_consume(team_id: int, *, requested: int = 1, now: datetime | None = None) -> CapDecision:
- """Reserve `requested` slots in one Redis round-trip. Returns the decision.
-
- If the new counter exceeds the cap, the reservation is rolled back and
- `allowed=False` is returned. This closes the TOCTOU window between a
- naive read-then-write check, so concurrent requests can't all pass and
- then collectively overshoot.
-
- Callers MUST `refund(team_id, n)` if they later decide not to do the
- work (e.g. `start_workflow` failed). The split between reservation and
- commit lives in the caller.
- """
- if requested < 0:
- raise ValueError(f"requested must be >= 0, got {requested}")
- if requested == 0:
- return CapDecision(allowed=True, used=current_usage(team_id, now=now), cap=get_cap_for_team(team_id))
-
- cap = get_cap_for_team(team_id)
- key = _redis_key(team_id, now=now)
- client = get_client()
- new_value = _incrby(client, key, requested)
- if new_value == requested:
- client.expire(key, _KEY_TTL_SECONDS)
- if new_value > cap:
- # Roll back: keep the counter at-or-below cap so a steady-state team
- # doesn't permanently look over.
- client.decrby(key, requested)
- return CapDecision(allowed=False, used=new_value - requested, cap=cap)
- return CapDecision(allowed=True, used=new_value, cap=cap)
-
-
-def refund(team_id: int, n: int = 1, *, now: datetime | None = None) -> None:
- """Roll back a previous `atomic_check_and_consume(...n)` reservation.
-
- Best-effort: failures are logged, not raised. We don't want a Redis blip
- to fail a request that already succeeded (or failed) on its main path.
- """
- if n <= 0:
- return
- try:
- get_client().decrby(_redis_key(team_id, now=now), n)
- except Exception as e:
- logger.warning("replay_summary_cap.refund_failed", team_id=team_id, n=n, error=str(e))
-
-
-def check_only(team_id: int, *, requested: int = 1, now: datetime | None = None) -> CapDecision:
- """Read-only: decide whether `requested` slots fit, without reserving.
-
- Use this when you can't tolerate the boundary effect of a reserve-then-
- refund cycle (e.g. health checks). For request-handling paths that may
- commit to LLM work, prefer `atomic_check_and_consume`.
- """
- if requested < 0:
- raise ValueError(f"requested must be >= 0, got {requested}")
- now = now or datetime.now(UTC)
- cap = get_cap_for_team(team_id)
- used = current_usage(team_id, now=now)
- return CapDecision(allowed=used + requested <= cap, used=used, cap=cap)
diff --git a/posthog/session_recordings/models/session_recording.py b/posthog/session_recordings/models/session_recording.py
index 889caeabddcd..a45787f0364e 100644
--- a/posthog/session_recordings/models/session_recording.py
+++ b/posthog/session_recordings/models/session_recording.py
@@ -85,8 +85,6 @@ class SessionRecording(UUIDTModel):
matching_events: Optional[RecordingMatchingEvents] = None
ongoing: Optional[bool] = None
activity_score: Optional[float] = None
- has_summary: Optional[bool] = None
- summary_outcome: Optional[dict] = None
expiry_time: Optional[datetime] = None
recording_ttl: Optional[int] = None
# False when this recording was included in listing results via session_recording_id
diff --git a/posthog/session_recordings/test/test_ai_summary_cap.py b/posthog/session_recordings/test/test_ai_summary_cap.py
deleted file mode 100644
index f28edbe98dd2..000000000000
--- a/posthog/session_recordings/test/test_ai_summary_cap.py
+++ /dev/null
@@ -1,411 +0,0 @@
-import re
-import threading
-from datetime import UTC, datetime
-
-import pytest
-from posthog.test.base import BaseTest
-from unittest.mock import patch
-
-from parameterized import parameterized
-from redis.exceptions import ResponseError
-
-from posthog.models.team import Team
-from posthog.redis import get_client
-from posthog.session_recordings.ai_summary_cap import (
- DEFAULT_MAX_SUMMARIES_PER_PERIOD,
- CapDecision,
- _redis_key,
- atomic_check_and_consume,
- check_only,
- coerce_max_summaries_per_period,
- consume_summary_quota,
- current_usage,
- get_cap_for_team,
- headroom,
- refund,
-)
-
-from products.signals.backend.models import SignalSourceConfig
-
-
-def _create_cluster_config(team: Team, *, enabled: bool = True, **config_overrides) -> SignalSourceConfig:
- """Most tests need the same boilerplate row — keep it here."""
- return SignalSourceConfig.objects.create(
- team=team,
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- enabled=enabled,
- config=config_overrides,
- )
-
-
-class TestCoerceMaxSummariesPerPeriod(BaseTest):
- @parameterized.expand(
- [
- # Falls back to default
- ("none", None, DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- ("zero", 0, DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- ("negative_int", -10, DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- ("negative_float_truncates_to_negative", -3.5, DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- ("non_numeric_string", "abc", DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- ("empty_string", "", DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- ("hex_string", "0x10", DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- ("bool_true", True, DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- ("bool_false", False, DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- ("nan_value", float("nan"), DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- # `int(float("inf"))` raises OverflowError, not ValueError — must be caught.
- ("inf", float("inf"), DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- ("negative_inf", float("-inf"), DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- ("list", [5], DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- ("dict", {"x": 5}, DEFAULT_MAX_SUMMARIES_PER_PERIOD),
- # Accepted (matches lenient `coerce_sample_rate` semantics)
- ("numeric_string", "100", 100),
- # int() strips ASCII whitespace; documented behavior we lean on.
- ("padded_numeric_string", " 50 ", 50),
- ("leading_zero_string", "007", 7),
- ("float_truncates", 3.7, 3),
- ("valid_one", 1, 1),
- ("valid_large", 99999, 99999),
- ("very_large_int", 10**12, 10**12),
- ]
- )
- def test_coerce(self, _name, value, expected):
- assert coerce_max_summaries_per_period(value) == expected
-
-
-class TestGetCapForTeam(BaseTest):
- def test_default_when_no_config_row(self):
- assert not SignalSourceConfig.objects.filter(team_id=self.team.pk).exists()
- assert get_cap_for_team(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD
-
- def test_default_when_row_has_no_cap_key(self):
- _create_cluster_config(self.team, sample_rate=0.5)
- assert get_cap_for_team(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD
-
- def test_override_can_only_lower(self):
- # Overrides ≤ default are honored.
- _create_cluster_config(self.team, max_summaries_per_period=7)
- assert get_cap_for_team(self.team.pk) == 7
-
- def test_override_above_default_is_clamped(self):
- # Cap-the-cap: project members can edit SignalSourceConfig, so an
- # override is allowed to lower the backstop but never raise it.
- _create_cluster_config(self.team, max_summaries_per_period=DEFAULT_MAX_SUMMARIES_PER_PERIOD * 1000)
- assert get_cap_for_team(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD
-
- def test_disabled_row_still_supplies_cap(self):
- # Sweep gating uses `enabled=True`, but the cap should apply even when the
- # autonomous sweep is off — DRF summarize is what we're protecting.
- _create_cluster_config(self.team, enabled=False, max_summaries_per_period=3)
- assert get_cap_for_team(self.team.pk) == 3
-
- def test_default_when_config_value_uncoerceable(self):
- _create_cluster_config(self.team, max_summaries_per_period="abc")
- assert get_cap_for_team(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD
-
- def test_default_when_config_is_list(self):
- # Pathological but valid JSON — `.config.get(...)` would AttributeError without the guard.
- SignalSourceConfig.objects.create(
- team=self.team,
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- config=[],
- )
- assert get_cap_for_team(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD
-
- def test_cross_team_isolation(self):
- other_team = Team.objects.create(organization=self.organization, name="other")
- _create_cluster_config(other_team, max_summaries_per_period=99)
- assert get_cap_for_team(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD
- assert get_cap_for_team(other_team.pk) == 99
-
-
-class TestRedisKey(BaseTest):
- def test_format(self):
- key = _redis_key(42, now=datetime(2026, 5, 5, tzinfo=UTC))
- assert key == "posthog/replay-summary-cap:42:2026-05"
- assert re.fullmatch(r"posthog/replay-summary-cap:\d+:\d{4}-\d{2}", key)
-
- def test_zero_padded_month(self):
- # Catch a future drift to %Y-%-m or similar — ops scripts will rely on
- # lexicographic sort, and "2026-1" sorts after "2026-10".
- assert _redis_key(1, now=datetime(2026, 1, 31, tzinfo=UTC)).endswith(":2026-01")
- assert _redis_key(1, now=datetime(2026, 12, 1, tzinfo=UTC)).endswith(":2026-12")
-
- def test_uses_utc_when_now_omitted(self):
- # We never want a worker's local TZ to determine the bucket — pin it to UTC.
- with patch("posthog.session_recordings.ai_summary_cap.datetime") as mock_dt:
- mock_dt.now.return_value = datetime(2026, 5, 5, 12, 0, 0, tzinfo=UTC)
- key = _redis_key(1)
- mock_dt.now.assert_called_once_with(UTC)
- assert key.endswith(":2026-05")
-
-
-class TestCounter(BaseTest):
- def test_current_usage_zero_for_unseen_team(self):
- assert current_usage(self.team.pk) == 0
-
- def test_consume_increments_and_returns_new_value(self):
- assert consume_summary_quota(self.team.pk, 1) == 1
- assert current_usage(self.team.pk) == 1
- assert consume_summary_quota(self.team.pk, 4) == 5
- assert current_usage(self.team.pk) == 5
-
- def test_consume_zero_is_noop(self):
- consume_summary_quota(self.team.pk, 1)
- assert consume_summary_quota(self.team.pk, 0) == 1
- assert consume_summary_quota(self.team.pk, -3) == 1
- assert current_usage(self.team.pk) == 1
-
- def test_ttl_set_on_first_write_only(self):
- client = get_client()
- consume_summary_quota(self.team.pk, 1)
- first_ttl = client.ttl(_redis_key(self.team.pk))
- assert first_ttl > 0 # an EXPIRE was issued
-
- # Force the key's TTL to a sentinel; a second consume must NOT re-issue EXPIRE.
- client.expire(_redis_key(self.team.pk), 999)
- consume_summary_quota(self.team.pk, 1)
- second_ttl = client.ttl(_redis_key(self.team.pk))
- assert second_ttl <= 999
-
- def test_corrupt_counter_treated_as_zero(self):
- get_client().set(_redis_key(self.team.pk), "not-a-number")
- assert current_usage(self.team.pk) == 0
-
- def test_consume_recovers_from_corrupt_key(self):
- # Real bug if unhandled: Redis INCRBY on a non-integer string raises
- # WRONGTYPE → we'd crash the summarize path. Reset + retry instead.
- client = get_client()
- client.set(_redis_key(self.team.pk), "not-a-number")
- # Sanity: raw INCRBY would explode.
- with pytest.raises(ResponseError):
- client.incrby(_redis_key(self.team.pk), 1)
- # consume_summary_quota must absorb it and re-establish the counter.
- assert consume_summary_quota(self.team.pk, 2) == 2
- assert current_usage(self.team.pk) == 2
-
- def test_consume_returns_int_even_when_redis_returns_bytes_via_round_trip(self):
- # Belt-and-braces: INCRBY returns int already, but `current_usage` reads
- # via GET which can return bytes depending on client config. Make sure we
- # still cast cleanly.
- consume_summary_quota(self.team.pk, 7)
- raw = get_client().get(_redis_key(self.team.pk))
- assert raw is not None
- assert int(raw) == 7 # what current_usage does internally
- assert current_usage(self.team.pk) == 7
-
-
-class TestCheckOnly(BaseTest):
- """`check_only` is the entrypoint primitive used at the cost-backstop
- check. The defining invariant: it MUST NEVER advance the counter, no
- matter the decision. Pair with a later `consume_summary_quota` once the
- caller commits to actual LLM work.
- """
-
- def setUp(self):
- super().setUp()
- _create_cluster_config(self.team, max_summaries_per_period=3)
-
- def test_allows_under_cap_without_incrementing(self):
- # Repeated check_only must not move the counter — that's the whole point.
- for _ in range(5):
- decision = check_only(self.team.pk)
- assert decision == CapDecision(allowed=True, used=0, cap=3)
- assert current_usage(self.team.pk) == 0
-
- def test_blocks_at_cap_without_incrementing(self):
- consume_summary_quota(self.team.pk, 3)
- decision = check_only(self.team.pk)
- assert decision == CapDecision(allowed=False, used=3, cap=3)
- assert current_usage(self.team.pk) == 3
-
- def test_reflects_existing_usage(self):
- consume_summary_quota(self.team.pk, 2)
- assert check_only(self.team.pk) == CapDecision(allowed=True, used=2, cap=3)
- assert current_usage(self.team.pk) == 2 # unchanged
-
- def test_requested_more_than_headroom_blocks(self):
- consume_summary_quota(self.team.pk, 2)
- assert check_only(self.team.pk, requested=2) == CapDecision(allowed=False, used=2, cap=3)
- assert current_usage(self.team.pk) == 2
-
- def test_requested_equal_to_headroom_allowed(self):
- consume_summary_quota(self.team.pk, 1)
- assert check_only(self.team.pk, requested=2) == CapDecision(allowed=True, used=1, cap=3)
- assert current_usage(self.team.pk) == 1 # NOT advanced — we only checked
-
- def test_exactly_at_cap_then_blocks(self):
- # Boundary regression: off-by-one in the `<=` comparator would flip these.
- consume_summary_quota(self.team.pk, 2)
- assert check_only(self.team.pk).allowed is True
- consume_summary_quota(self.team.pk, 1) # caller commits to the work
- assert check_only(self.team.pk).allowed is False
-
- def test_requested_zero_is_allowed_noop(self):
- decision = check_only(self.team.pk, requested=0)
- assert decision.allowed is True
- assert current_usage(self.team.pk) == 0
-
- def test_requested_negative_raises(self):
- with pytest.raises(ValueError, match="requested must be >= 0"):
- check_only(self.team.pk, requested=-1)
-
- def test_check_only_then_consume_advances_counter_only_when_committed(self):
- # The split (check_only + consume) must advance the counter exactly
- # once per committed work item, never on the check itself.
- for _ in range(3):
- decision = check_only(self.team.pk)
- if decision.allowed:
- consume_summary_quota(self.team.pk, 1)
- assert current_usage(self.team.pk) == 3
- assert check_only(self.team.pk).allowed is False
-
- def test_no_consume_on_short_circuit(self):
- # The motivating case for the split: a caller that bails out of LLM work
- # after `check_only` (cache hit, in-flight workflow dedup) must NOT have
- # burned quota.
- for _ in range(10):
- decision = check_only(self.team.pk)
- assert decision.allowed is True
- # Caller short-circuits — no consume call.
- assert current_usage(self.team.pk) == 0
-
-
-class TestHeadroom(BaseTest):
- def test_headroom_default_when_unseen(self):
- assert headroom(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD
-
- def test_headroom_decreases_with_usage(self):
- _create_cluster_config(self.team, max_summaries_per_period=10)
- assert headroom(self.team.pk) == 10
- consume_summary_quota(self.team.pk, 4)
- assert headroom(self.team.pk) == 6
-
- def test_headroom_clamped_to_zero_when_overconsumed(self):
- _create_cluster_config(self.team, max_summaries_per_period=5)
- consume_summary_quota(self.team.pk, 12)
- assert headroom(self.team.pk) == 0
-
-
-class TestAtomicCheckAndConsume(BaseTest):
- """`atomic_check_and_consume` is the request-handling primitive: reserves a
- slot in one Redis round-trip and reverts if the new value exceeds the cap.
- """
-
- def setUp(self):
- super().setUp()
- _create_cluster_config(self.team, max_summaries_per_period=3)
-
- def test_first_n_calls_allowed_then_blocks(self):
- # Within the cap: each call advances the counter by 1.
- for i in range(1, 4):
- decision = atomic_check_and_consume(self.team.pk)
- assert decision == CapDecision(allowed=True, used=i, cap=3)
- assert current_usage(self.team.pk) == i
- # Cap reached: next call is blocked and reverted.
- decision = atomic_check_and_consume(self.team.pk)
- assert decision == CapDecision(allowed=False, used=3, cap=3)
- assert current_usage(self.team.pk) == 3
-
- def test_block_reverts_so_steady_state_stays_at_cap(self):
- # The blocked branch must DECRBY back to the cap, otherwise repeated
- # blocked calls would inflate the counter unboundedly.
- consume_summary_quota(self.team.pk, 3)
- for _ in range(20):
- assert atomic_check_and_consume(self.team.pk).allowed is False
- assert current_usage(self.team.pk) == 3
-
- def test_requested_more_than_headroom_blocks_and_reverts(self):
- consume_summary_quota(self.team.pk, 2)
- decision = atomic_check_and_consume(self.team.pk, requested=2)
- # Cap=3, used=2, requested=2 → would be 4 → block + revert.
- assert decision == CapDecision(allowed=False, used=2, cap=3)
- assert current_usage(self.team.pk) == 2
-
- def test_requested_zero_is_allowed_noop(self):
- decision = atomic_check_and_consume(self.team.pk, requested=0)
- assert decision.allowed is True
- assert current_usage(self.team.pk) == 0
-
- def test_requested_negative_raises(self):
- with pytest.raises(ValueError, match="requested must be >= 0"):
- atomic_check_and_consume(self.team.pk, requested=-1)
-
- def test_atomic_check_and_consume_is_overshoot_free(self):
- # The defining invariant of the atomic API: concurrent callers can
- # never collectively pass more than `cap`. The split check_only +
- # consume pattern can; the atomic one cannot.
- #
- # Mock the cap lookup so we don't hit Django's connection-per-thread
- # transaction isolation (test row written in the main thread isn't
- # visible to worker threads with fresh connections).
- n_threads = 20
- barrier = threading.Barrier(n_threads)
- results: list[CapDecision] = []
- results_lock = threading.Lock()
-
- def worker():
- barrier.wait()
- decision = atomic_check_and_consume(self.team.pk)
- with results_lock:
- results.append(decision)
-
- with patch("posthog.session_recordings.ai_summary_cap.get_cap_for_team", return_value=3):
- threads = [threading.Thread(target=worker) for _ in range(n_threads)]
- for t in threads:
- t.start()
- for t in threads:
- t.join()
-
- allowed_count = sum(1 for r in results if r.allowed)
- # Cap is 3 — no concurrency can break that.
- assert allowed_count == 3
- # Counter equals exactly cap. All blocked attempts reverted.
- assert current_usage(self.team.pk) == 3
-
-
-class TestRefund(BaseTest):
- def setUp(self):
- super().setUp()
- _create_cluster_config(self.team, max_summaries_per_period=3)
-
- def test_refund_undoes_a_prior_atomic_reservation(self):
- atomic_check_and_consume(self.team.pk)
- assert current_usage(self.team.pk) == 1
- refund(self.team.pk, 1)
- assert current_usage(self.team.pk) == 0
-
- def test_refund_zero_or_negative_is_noop(self):
- consume_summary_quota(self.team.pk, 2)
- refund(self.team.pk, 0)
- refund(self.team.pk, -5)
- assert current_usage(self.team.pk) == 2
-
- def test_refund_swallows_redis_errors(self):
- # A flaky DECR must not raise — refund is best-effort.
- with patch("posthog.session_recordings.ai_summary_cap.get_client") as mock_client:
- mock_client.return_value.decrby.side_effect = ConnectionError("redis down")
- refund(self.team.pk, 1)
-
-
-class TestMonthBoundary(BaseTest):
- def test_independent_buckets_across_months(self):
- jan = datetime(2026, 1, 31, 23, 59, 59, tzinfo=UTC)
- feb = datetime(2026, 2, 1, 0, 0, 1, tzinfo=UTC)
-
- consume_summary_quota(self.team.pk, 5, now=jan)
- assert current_usage(self.team.pk, now=jan) == 5
- assert current_usage(self.team.pk, now=feb) == 0
-
- consume_summary_quota(self.team.pk, 2, now=feb)
- assert current_usage(self.team.pk, now=feb) == 2
- assert current_usage(self.team.pk, now=jan) == 5
-
- def test_check_only_uses_now_for_bucket(self):
- feb = datetime(2026, 2, 15, 12, 0, 0, tzinfo=UTC)
- consume_summary_quota(self.team.pk, 5, now=feb)
-
- with patch("posthog.session_recordings.ai_summary_cap.datetime") as mock_dt:
- mock_dt.now.return_value = feb
- assert check_only(self.team.pk) == CapDecision(allowed=True, used=5, cap=DEFAULT_MAX_SUMMARIES_PER_PERIOD)
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index b23130aef0f9..ba1739c36283 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -64,7 +64,6 @@ from posthog.temporal.salesforce_enrichment.usage_workflow import UsageEnrichmen
from posthog.temporal.salesforce_enrichment.workflow import SalesforceEnrichmentInputs
from posthog.temporal.session_replay.delete_recordings.types import PurgeDeletedMetadataInput
from posthog.temporal.session_replay.enforce_max_replay_retention.types import EnforceMaxReplayRetentionInput
-from posthog.temporal.session_replay.gemini_cleanup_sweep import create_gemini_cleanup_sweep_schedule
from posthog.temporal.session_replay.replay_count_metrics.types import ReplayCountMetricsInput
from posthog.temporal.session_replay.surfacing_score_export_sweep.schedule import (
create_surfacing_score_export_sweep_schedule,
@@ -637,6 +636,8 @@ async def cleanup_legacy_session_summarization_schedules(client: Client):
"video-segment-clustering-coordinator-schedule",
"session-summarization-sweep-schedule",
"session-summarization-sweep-reconciler-schedule",
+ # Swept Gemini files uploaded by the session-summary workflow; nothing uploads them now.
+ "session-summary-cleanup-sweep-schedule",
]
for schedule_id in legacy_schedule_ids:
if await a_schedule_exists(client, schedule_id):
@@ -901,7 +902,6 @@ schedules = [
if settings.CLOUD_DEPLOYMENT:
# Gemini uploads only happen in cloud; each sweep reaps only the files tracked in this
# deployment's own Redis index, so per-deployment scoping is inherent.
- schedules.append(create_gemini_cleanup_sweep_schedule)
schedules.append(create_replay_vision_gemini_cleanup_sweep_schedule)
schedules.append(create_run_usage_reports_schedule)
schedules.append(create_finalize_usage_reports_schedule)
diff --git a/posthog/temporal/session_replay/gemini_cleanup_sweep/__init__.py b/posthog/temporal/session_replay/gemini_cleanup_sweep/__init__.py
deleted file mode 100644
index 69ef67420f4b..000000000000
--- a/posthog/temporal/session_replay/gemini_cleanup_sweep/__init__.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from posthog.temporal.session_replay.gemini_cleanup_sweep.activities import sweep_gemini_files_activity
-from posthog.temporal.session_replay.gemini_cleanup_sweep.schedule import create_gemini_cleanup_sweep_schedule
-from posthog.temporal.session_replay.gemini_cleanup_sweep.workflow import GeminiFileCleanupSweepWorkflow
-
-GEMINI_CLEANUP_SWEEP_WORKFLOWS = [GeminiFileCleanupSweepWorkflow]
-GEMINI_CLEANUP_SWEEP_ACTIVITIES = [sweep_gemini_files_activity]
-
-__all__ = [
- "GEMINI_CLEANUP_SWEEP_ACTIVITIES",
- "GEMINI_CLEANUP_SWEEP_WORKFLOWS",
- "create_gemini_cleanup_sweep_schedule",
-]
diff --git a/posthog/temporal/session_replay/gemini_cleanup_sweep/activities.py b/posthog/temporal/session_replay/gemini_cleanup_sweep/activities.py
deleted file mode 100644
index f893ea3dfb02..000000000000
--- a/posthog/temporal/session_replay/gemini_cleanup_sweep/activities.py
+++ /dev/null
@@ -1,154 +0,0 @@
-import asyncio
-from dataclasses import replace
-from datetime import UTC, datetime
-
-from django.conf import settings
-
-import structlog
-from asgiref.sync import sync_to_async
-from google.genai import Client as RawGenAIClient
-from temporalio import activity
-from temporalio.client import Client, WorkflowExecutionStatus
-from temporalio.service import RPCError, RPCStatusCode
-
-from posthog.temporal.common.client import async_connect
-from posthog.temporal.session_replay.gemini_cleanup_sweep.constants import (
- DELETE_CONCURRENCY,
- DESCRIBE_CONCURRENCY,
- MAX_FILES_PER_SWEEP,
- SWEEP_MIN_AGE,
-)
-from posthog.temporal.session_replay.gemini_cleanup_sweep.tracking import (
- index_size,
- is_gemini_file_gone,
- iter_tracked_files,
- untrack_uploaded_file,
-)
-from posthog.temporal.session_replay.gemini_cleanup_sweep.types import (
- CleanupSweepInputs,
- CleanupSweepResult,
- TrackedFile,
-)
-
-logger = structlog.get_logger(__name__)
-
-_TERMINAL_STATUSES = frozenset(
- {
- WorkflowExecutionStatus.COMPLETED,
- WorkflowExecutionStatus.FAILED,
- WorkflowExecutionStatus.CANCELED,
- WorkflowExecutionStatus.TERMINATED,
- WorkflowExecutionStatus.TIMED_OUT,
- }
-)
-
-
-async def _classify_workflow(temporal: Client, workflow_id: str) -> str:
- """Returns ``"delete"``, ``"running"``, or ``"error"``."""
- try:
- desc = await temporal.get_workflow_handle(workflow_id).describe()
- except RPCError as e:
- if e.status == RPCStatusCode.NOT_FOUND:
- return "delete"
- return "error"
- except Exception:
- return "error"
-
- if desc.status in _TERMINAL_STATUSES:
- return "delete"
- return "running"
-
-
-async def sweep_gemini_files_activity(inputs: CleanupSweepInputs) -> CleanupSweepResult:
- """Reclaims orphaned Gemini files. Failures counted, never raised."""
- raw_client = RawGenAIClient(api_key=settings.GEMINI_API_KEY)
- temporal = await async_connect()
- cutoff = datetime.now(UTC) - SWEEP_MIN_AGE
-
- total_tracked = await index_size()
- hit_max_files_cap = total_tracked > MAX_FILES_PER_SWEEP
-
- scanned = 0
- skipped_too_young = 0
- skipped_invalid_value = 0
- candidates: list[TrackedFile] = []
- async for tracked in iter_tracked_files(limit=MAX_FILES_PER_SWEEP):
- scanned += 1
- if tracked is None:
- skipped_invalid_value += 1
- continue
- if tracked.uploaded_at > cutoff:
- skipped_too_young += 1
- continue
- candidates.append(tracked)
- activity.heartbeat({"phase": "scanned", "scanned": scanned, "candidates": len(candidates)})
-
- describe_sem = asyncio.Semaphore(DESCRIBE_CONCURRENCY)
-
- async def _classify(tracked: TrackedFile) -> tuple[TrackedFile, str]:
- async with describe_sem:
- outcome = await _classify_workflow(temporal, tracked.workflow_id)
- return tracked, outcome
-
- classifications = await asyncio.gather(*(_classify(t) for t in candidates))
- activity.heartbeat({"phase": "classified", "classified": len(classifications)})
-
- to_delete = [t for t, outcome in classifications if outcome == "delete"]
- skipped_running = sum(1 for _, outcome in classifications if outcome == "running")
- skipped_temporal_error = sum(1 for _, outcome in classifications if outcome == "error")
-
- base_result = CleanupSweepResult(
- scanned=scanned,
- skipped_too_young=skipped_too_young,
- skipped_invalid_value=skipped_invalid_value,
- skipped_running=skipped_running,
- skipped_temporal_error=skipped_temporal_error,
- hit_max_files_cap=hit_max_files_cap,
- )
-
- delete_sem = asyncio.Semaphore(DELETE_CONCURRENCY)
-
- async def _delete(tracked: TrackedFile) -> bool:
- async with delete_sem:
- try:
- await sync_to_async(raw_client.files.delete, thread_sensitive=False)(name=tracked.gemini_file_name)
- except Exception as e:
- if not is_gemini_file_gone(e):
- # Key kept for next-cycle retry; 48h TTL backstops.
- logger.exception(
- "cleanup_sweep.delete_failed",
- gemini_file_name=tracked.gemini_file_name,
- workflow_id=tracked.workflow_id,
- signals_type="cleanup-sweep",
- )
- return False
- # File already gone (e.g., a previous untrack failed). Drop the key so we
- # don't keep retrying a doomed delete.
- logger.info(
- "cleanup_sweep.delete_already_gone",
- gemini_file_name=tracked.gemini_file_name,
- workflow_id=tracked.workflow_id,
- signals_type="cleanup-sweep",
- )
- await untrack_uploaded_file(tracked.gemini_file_name)
- return True
-
- delete_results = await asyncio.gather(*(_delete(t) for t in to_delete))
- deleted = sum(1 for r in delete_results if r)
- delete_failed = sum(1 for r in delete_results if not r)
-
- result = replace(base_result, deleted=deleted, delete_failed=delete_failed)
- logger.info(
- "cleanup_sweep.cycle_complete",
- scanned=result.scanned,
- deleted=result.deleted,
- skipped_running=result.skipped_running,
- skipped_too_young=result.skipped_too_young,
- skipped_invalid_value=result.skipped_invalid_value,
- skipped_temporal_error=result.skipped_temporal_error,
- delete_failed=result.delete_failed,
- hit_max_files_cap=result.hit_max_files_cap,
- signals_type="cleanup-sweep",
- )
- return result
diff --git a/posthog/temporal/session_replay/gemini_cleanup_sweep/constants.py b/posthog/temporal/session_replay/gemini_cleanup_sweep/constants.py
deleted file mode 100644
index 7d8c1ede9df3..000000000000
--- a/posthog/temporal/session_replay/gemini_cleanup_sweep/constants.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from datetime import timedelta
-
-SCHEDULE_ID = "session-summary-cleanup-sweep-schedule"
-WORKFLOW_ID = "session-summary-cleanup-sweep"
-WORKFLOW_NAME = "session-summary-cleanup-sweep"
-SCHEDULE_TYPE = "session-summary-cleanup-sweep"
-
-SCHEDULE_INTERVAL = timedelta(minutes=5)
-
-REDIS_KEY_PREFIX = "session-summary:gemini-file:"
-REDIS_INDEX_KEY = "session-summary:gemini-files-index"
-
-# Matches Gemini's ~48h retention.
-REDIS_KEY_TTL = timedelta(hours=48)
-
-# Skips describing very-recently-started workflows that may not yet be visible to Temporal.
-SWEEP_MIN_AGE = timedelta(seconds=60)
-
-MAX_FILES_PER_SWEEP = 1500
-MGET_BATCH_SIZE = 200
-
-DESCRIBE_CONCURRENCY = 20
-DELETE_CONCURRENCY = 10
-
-WORKFLOW_EXECUTION_TIMEOUT = timedelta(minutes=20)
-SWEEP_ACTIVITY_TIMEOUT = timedelta(minutes=15)
-SWEEP_ACTIVITY_HEARTBEAT_TIMEOUT = timedelta(minutes=2)
diff --git a/posthog/temporal/session_replay/gemini_cleanup_sweep/schedule.py b/posthog/temporal/session_replay/gemini_cleanup_sweep/schedule.py
deleted file mode 100644
index 5c9441f18bcb..000000000000
--- a/posthog/temporal/session_replay/gemini_cleanup_sweep/schedule.py
+++ /dev/null
@@ -1,56 +0,0 @@
-from django.conf import settings
-
-from temporalio import common
-from temporalio.client import (
- Client,
- Schedule,
- ScheduleActionStartWorkflow,
- ScheduleIntervalSpec,
- ScheduleOverlapPolicy,
- SchedulePolicy,
- ScheduleSpec,
-)
-from temporalio.common import SearchAttributePair, TypedSearchAttributes
-
-from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
-from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY
-from posthog.temporal.session_replay.gemini_cleanup_sweep.constants import (
- SCHEDULE_ID,
- SCHEDULE_INTERVAL,
- SCHEDULE_TYPE,
- WORKFLOW_EXECUTION_TIMEOUT,
- WORKFLOW_ID,
- WORKFLOW_NAME,
-)
-from posthog.temporal.session_replay.gemini_cleanup_sweep.types import CleanupSweepInputs
-
-
-async def create_gemini_cleanup_sweep_schedule(client: Client) -> None:
- schedule = Schedule(
- action=ScheduleActionStartWorkflow(
- WORKFLOW_NAME,
- CleanupSweepInputs(),
- id=WORKFLOW_ID,
- task_queue=settings.SESSION_REPLAY_TASK_QUEUE,
- execution_timeout=WORKFLOW_EXECUTION_TIMEOUT,
- retry_policy=common.RetryPolicy(maximum_attempts=1),
- ),
- spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=SCHEDULE_INTERVAL)]),
- policy=SchedulePolicy(
- overlap=ScheduleOverlapPolicy.SKIP,
- catchup_window=SCHEDULE_INTERVAL,
- ),
- )
- search_attributes = TypedSearchAttributes(
- search_attributes=[SearchAttributePair(key=POSTHOG_SCHEDULE_TYPE_KEY, value=SCHEDULE_TYPE)]
- )
- if await a_schedule_exists(client, SCHEDULE_ID):
- await a_update_schedule(client, SCHEDULE_ID, schedule, search_attributes=search_attributes)
- else:
- await a_create_schedule(
- client,
- SCHEDULE_ID,
- schedule,
- trigger_immediately=True,
- search_attributes=search_attributes,
- )
diff --git a/posthog/temporal/session_replay/gemini_cleanup_sweep/tracking.py b/posthog/temporal/session_replay/gemini_cleanup_sweep/tracking.py
deleted file mode 100644
index ef8924a76cb8..000000000000
--- a/posthog/temporal/session_replay/gemini_cleanup_sweep/tracking.py
+++ /dev/null
@@ -1,110 +0,0 @@
-"""Redis tracking for Gemini files uploaded by the session-summary workflow."""
-
-import json
-from collections.abc import AsyncIterator
-from datetime import datetime
-
-import structlog
-from google.genai.errors import APIError
-
-from posthog.redis import get_async_client
-from posthog.temporal.session_replay.gemini_cleanup_sweep.constants import (
- MGET_BATCH_SIZE,
- REDIS_INDEX_KEY,
- REDIS_KEY_PREFIX,
- REDIS_KEY_TTL,
-)
-from posthog.temporal.session_replay.gemini_cleanup_sweep.types import TrackedFile
-
-logger = structlog.get_logger(__name__)
-
-
-def is_gemini_file_gone(error: Exception) -> bool:
- """Whether a Gemini delete failure means the file no longer exists. Gemini reports missing
- files as 403 PERMISSION_DENIED ("...or it may not exist"), not just 404 — callers should
- untrack on either instead of retrying a doomed delete."""
- return isinstance(error, APIError) and error.code in (403, 404)
-
-
-def _redis_key_for(gemini_file_name: str) -> str:
- return f"{REDIS_KEY_PREFIX}{gemini_file_name}"
-
-
-def _to_str(raw: str | bytes) -> str:
- return raw.decode() if isinstance(raw, bytes) else raw
-
-
-def _to_str_optional(raw: str | bytes | None) -> str | None:
- return None if raw is None else _to_str(raw)
-
-
-async def track_uploaded_file(gemini_file_name: str, workflow_id: str, uploaded_at: datetime) -> None:
- """Raises on Redis failure so the caller can roll back the upload."""
- redis = get_async_client()
- payload = json.dumps({"workflow_id": workflow_id, "uploaded_at": uploaded_at.isoformat()})
- async with redis.pipeline(transaction=True) as pipe:
- pipe.set(_redis_key_for(gemini_file_name), payload, ex=int(REDIS_KEY_TTL.total_seconds()))
- pipe.zadd(REDIS_INDEX_KEY, {gemini_file_name: uploaded_at.timestamp()})
- await pipe.execute()
-
-
-async def untrack_uploaded_file(gemini_file_name: str) -> None:
- """Best-effort: TTL or sweep stale-cleanup handle leftover state on failure."""
- redis = get_async_client()
- try:
- async with redis.pipeline(transaction=True) as pipe:
- pipe.delete(_redis_key_for(gemini_file_name))
- pipe.zrem(REDIS_INDEX_KEY, gemini_file_name)
- await pipe.execute()
- except Exception:
- logger.exception(
- "gemini_cleanup_sweep.untrack_failed",
- gemini_file_name=gemini_file_name,
- signals_type="cleanup-sweep",
- )
-
-
-async def iter_tracked_files(limit: int) -> AsyncIterator[TrackedFile | None]:
- """Yield up to ``limit`` tracked files, oldest-uploaded first. Bounded server-side via
- ZRANGE LIMIT so the fetch cost is independent of total backlog. Yields ``None`` for
- undecodable payloads. Drops stale index entries (per-file key TTL'd out) as it goes."""
- redis = get_async_client()
- raw_members = await redis.zrange(REDIS_INDEX_KEY, 0, limit - 1)
- file_names: list[str] = [_to_str(m) for m in raw_members]
- if not file_names:
- return
-
- for batch_start in range(0, len(file_names), MGET_BATCH_SIZE):
- batch = file_names[batch_start : batch_start + MGET_BATCH_SIZE]
- keys = [_redis_key_for(fn) for fn in batch]
- raw_values = await redis.mget(*keys)
- stale: list[str] = []
- for fn, raw in zip(batch, raw_values):
- value = _to_str_optional(raw)
- if value is None:
- stale.append(fn)
- continue
- try:
- payload = json.loads(value)
- workflow_id = payload["workflow_id"]
- uploaded_at = datetime.fromisoformat(payload["uploaded_at"])
- except (json.JSONDecodeError, KeyError, TypeError, ValueError):
- logger.exception(
- "gemini_cleanup_sweep.invalid_value",
- gemini_file_name=fn,
- signals_type="cleanup-sweep",
- )
- yield None
- continue
- yield TrackedFile(
- gemini_file_name=fn,
- workflow_id=workflow_id,
- uploaded_at=uploaded_at,
- )
- if stale:
- await redis.zrem(REDIS_INDEX_KEY, *stale)
-
-
-async def index_size() -> int:
- redis = get_async_client()
- return await redis.zcard(REDIS_INDEX_KEY)
diff --git a/posthog/temporal/session_replay/gemini_cleanup_sweep/types.py b/posthog/temporal/session_replay/gemini_cleanup_sweep/types.py
deleted file mode 100644
index 8ae178d830f0..000000000000
--- a/posthog/temporal/session_replay/gemini_cleanup_sweep/types.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from dataclasses import dataclass
-from datetime import datetime
-
-
-@dataclass
-class CleanupSweepInputs:
- pass
-
-
-@dataclass
-class CleanupSweepResult:
- scanned: int = 0
- deleted: int = 0
- skipped_running: int = 0
- skipped_too_young: int = 0
- skipped_temporal_error: int = 0
- skipped_invalid_value: int = 0
- delete_failed: int = 0
- hit_max_files_cap: bool = False
-
-
-@dataclass(frozen=True)
-class TrackedFile:
- gemini_file_name: str
- workflow_id: str
- uploaded_at: datetime
diff --git a/posthog/temporal/session_replay/gemini_cleanup_sweep/workflow.py b/posthog/temporal/session_replay/gemini_cleanup_sweep/workflow.py
deleted file mode 100644
index 40d15dcea9d3..000000000000
--- a/posthog/temporal/session_replay/gemini_cleanup_sweep/workflow.py
+++ /dev/null
@@ -1,41 +0,0 @@
-from typing import Any
-
-from temporalio import workflow
-from temporalio.common import RetryPolicy
-
-from posthog.temporal.common.base import PostHogWorkflow
-from posthog.temporal.session_replay.gemini_cleanup_sweep.constants import (
- SWEEP_ACTIVITY_HEARTBEAT_TIMEOUT,
- SWEEP_ACTIVITY_TIMEOUT,
- WORKFLOW_NAME,
-)
-from posthog.temporal.session_replay.gemini_cleanup_sweep.types import CleanupSweepInputs
-
-with workflow.unsafe.imports_passed_through():
- from posthog.temporal.session_replay.gemini_cleanup_sweep.activities import sweep_gemini_files_activity
-
-
[email protected](name=WORKFLOW_NAME)
-class GeminiFileCleanupSweepWorkflow(PostHogWorkflow):
- inputs_cls = CleanupSweepInputs
- inputs_optional = True
-
- @workflow.run
- async def run(self, inputs: CleanupSweepInputs) -> dict[str, Any]:
- result = await workflow.execute_activity(
- sweep_gemini_files_activity,
- inputs,
- start_to_close_timeout=SWEEP_ACTIVITY_TIMEOUT,
- heartbeat_timeout=SWEEP_ACTIVITY_HEARTBEAT_TIMEOUT,
- retry_policy=RetryPolicy(maximum_attempts=1),
- )
- return {
- "scanned": result.scanned,
- "deleted": result.deleted,
- "skipped_running": result.skipped_running,
- "skipped_too_young": result.skipped_too_young,
- "skipped_temporal_error": result.skipped_temporal_error,
- "skipped_invalid_value": result.skipped_invalid_value,
- "delete_failed": result.delete_failed,
- "hit_max_files_cap": result.hit_max_files_cap,
- }
diff --git a/posthog/temporal/tests/session_replay/conftest.py b/posthog/temporal/tests/session_replay/conftest.py
deleted file mode 100644
index 9de2b619024f..000000000000
--- a/posthog/temporal/tests/session_replay/conftest.py
+++ /dev/null
@@ -1,22 +0,0 @@
-"""Shared fixtures for session_replay temporal tests."""
-
-import pytest_asyncio
-
-from posthog.redis import get_async_client
-from posthog.temporal.session_replay.gemini_cleanup_sweep.constants import REDIS_INDEX_KEY, REDIS_KEY_PREFIX
-
-
-async def _drop_gemini_tracking_keys(client) -> None:
- keys = [k async for k in client.scan_iter(match=f"{REDIS_KEY_PREFIX}*")]
- if keys:
- await client.delete(*keys)
- await client.delete(REDIS_INDEX_KEY)
-
-
-@pytest_asyncio.fixture
-async def gemini_redis():
- """Async Redis client with the gemini_cleanup_sweep namespace wiped before/after each test."""
- client = get_async_client()
- await _drop_gemini_tracking_keys(client)
- yield client
- await _drop_gemini_tracking_keys(client)
diff --git a/posthog/temporal/tests/session_replay/gemini_cleanup_sweep/__init__.py b/posthog/temporal/tests/session_replay/gemini_cleanup_sweep/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/temporal/tests/session_replay/gemini_cleanup_sweep/test_activities.py b/posthog/temporal/tests/session_replay/gemini_cleanup_sweep/test_activities.py
deleted file mode 100644
index 035042ce00ec..000000000000
--- a/posthog/temporal/tests/session_replay/gemini_cleanup_sweep/test_activities.py
+++ /dev/null
@@ -1,335 +0,0 @@
-import json
-import datetime as dt
-from dataclasses import dataclass
-
-import pytest
-from unittest.mock import AsyncMock, patch
-
-from google.genai.errors import APIError
-from temporalio.client import WorkflowExecutionStatus
-from temporalio.service import RPCError, RPCStatusCode
-
-from posthog.temporal.session_replay.gemini_cleanup_sweep.activities import sweep_gemini_files_activity
-from posthog.temporal.session_replay.gemini_cleanup_sweep.constants import (
- MAX_FILES_PER_SWEEP,
- REDIS_INDEX_KEY,
- REDIS_KEY_PREFIX,
- REDIS_KEY_TTL,
- SWEEP_MIN_AGE,
-)
-from posthog.temporal.session_replay.gemini_cleanup_sweep.types import CleanupSweepInputs, CleanupSweepResult
-
-_NOW = dt.datetime(2026, 4, 24, 12, 0, 0, tzinfo=dt.UTC)
-
-
-@dataclass
-class _Outcome:
- status: WorkflowExecutionStatus | None = None
- raise_not_found: bool = False
- raise_rpc_error: bool = False
-
-
-class _StubHandle:
- def __init__(self, outcome: _Outcome) -> None:
- self._outcome = outcome
-
- async def describe(self):
- if self._outcome.raise_not_found:
- raise RPCError("not found", RPCStatusCode.NOT_FOUND, b"")
- if self._outcome.raise_rpc_error:
- raise RPCError("boom", RPCStatusCode.INTERNAL, b"")
-
- class _Desc:
- status = self._outcome.status
-
- return _Desc()
-
-
-class _StubTemporal:
- def __init__(self, outcomes: dict[str, _Outcome]) -> None:
- self._outcomes = outcomes
-
- def get_workflow_handle(self, workflow_id: str) -> _StubHandle:
- return _StubHandle(self._outcomes.get(workflow_id, _Outcome(status=WorkflowExecutionStatus.RUNNING)))
-
-
-class _StubFiles:
- def __init__(self) -> None:
- self.deleted: list[str] = []
- self.delete_raises_for: dict[str, BaseException] = {}
-
- def delete(self, *, name: str) -> None:
- if name in self.delete_raises_for:
- raise self.delete_raises_for[name]
- self.deleted.append(name)
-
-
-class _StubRawClient:
- def __init__(self) -> None:
- self.files = _StubFiles()
-
-
-def fixed_now():
- class _FixedDatetime(dt.datetime):
- @classmethod
- def now(cls, tz=None):
- return _NOW if tz is None else _NOW.astimezone(tz)
-
- with patch(
- "posthog.temporal.session_replay.gemini_cleanup_sweep.activities.datetime",
- _FixedDatetime,
- ):
- yield
-
-
-async def _track(client, *, file_name: str, workflow_id: str, age: dt.timedelta) -> None:
- uploaded_at = _NOW - age
- payload = json.dumps({"workflow_id": workflow_id, "uploaded_at": uploaded_at.isoformat()})
- await client.set(f"{REDIS_KEY_PREFIX}{file_name}", payload, ex=int(REDIS_KEY_TTL.total_seconds()))
- await client.zadd(REDIS_INDEX_KEY, {file_name: uploaded_at.timestamp()})
-
-
-def _patch_clients(raw_client: _StubRawClient, temporal: _StubTemporal):
- return (
- patch(
- "posthog.temporal.session_replay.gemini_cleanup_sweep.activities.RawGenAIClient",
- return_value=raw_client,
- ),
- patch(
- "posthog.temporal.session_replay.gemini_cleanup_sweep.activities.async_connect",
- new=AsyncMock(return_value=temporal),
- ),
- )
-
-
-async def _key_exists(client, file_name: str) -> bool:
- return bool(await client.exists(f"{REDIS_KEY_PREFIX}{file_name}"))
-
-
-async def _index_has(client, file_name: str) -> bool:
- return await client.zscore(REDIS_INDEX_KEY, file_name) is not None
-
-
-async def test_no_keys_returns_zeros(activity_environment, fixed_now, gemini_redis):
- raw, tmp = _StubRawClient(), _StubTemporal({})
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result == CleanupSweepResult()
- assert raw.files.deleted == []
-
-
-async def test_skips_keys_younger_than_min_age(activity_environment, fixed_now, gemini_redis):
- await _track(gemini_redis, file_name="files/young", workflow_id="wf-1", age=SWEEP_MIN_AGE / 2)
- raw, tmp = _StubRawClient(), _StubTemporal({"wf-1": _Outcome(status=WorkflowExecutionStatus.COMPLETED)})
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result.scanned == 1
- assert result.skipped_too_young == 1
- assert result.deleted == 0
- assert raw.files.deleted == []
- assert await _key_exists(gemini_redis, "files/young")
- assert await _index_has(gemini_redis, "files/young")
-
-
- "status",
- [
- WorkflowExecutionStatus.COMPLETED,
- WorkflowExecutionStatus.FAILED,
- WorkflowExecutionStatus.CANCELED,
- WorkflowExecutionStatus.TERMINATED,
- WorkflowExecutionStatus.TIMED_OUT,
- ],
-)
-async def test_deletes_files_for_terminal_workflows(activity_environment, fixed_now, gemini_redis, status):
- await _track(gemini_redis, file_name="files/old", workflow_id="wf-1", age=SWEEP_MIN_AGE * 10)
- raw, tmp = _StubRawClient(), _StubTemporal({"wf-1": _Outcome(status=status)})
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result.deleted == 1
- assert raw.files.deleted == ["files/old"]
- assert not await _key_exists(gemini_redis, "files/old")
- assert not await _index_has(gemini_redis, "files/old")
-
-
- "status",
- [WorkflowExecutionStatus.RUNNING, WorkflowExecutionStatus.CONTINUED_AS_NEW],
-)
-async def test_skips_files_for_active_workflows(activity_environment, fixed_now, gemini_redis, status):
- await _track(gemini_redis, file_name="files/in-use", workflow_id="wf-1", age=SWEEP_MIN_AGE * 10)
- raw, tmp = _StubRawClient(), _StubTemporal({"wf-1": _Outcome(status=status)})
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result.skipped_running == 1
- assert result.deleted == 0
- assert raw.files.deleted == []
- assert await _key_exists(gemini_redis, "files/in-use")
- assert await _index_has(gemini_redis, "files/in-use")
-
-
-async def test_status_none_is_treated_as_running(activity_environment, fixed_now, gemini_redis):
- await _track(gemini_redis, file_name="files/maybe-running", workflow_id="wf-1", age=SWEEP_MIN_AGE * 10)
- raw, tmp = _StubRawClient(), _StubTemporal({"wf-1": _Outcome(status=None)})
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result.skipped_running == 1
- assert result.deleted == 0
-
-
-async def test_deletes_when_workflow_not_found(activity_environment, fixed_now, gemini_redis):
- await _track(gemini_redis, file_name="files/orphan", workflow_id="wf-1", age=SWEEP_MIN_AGE * 10)
- raw, tmp = _StubRawClient(), _StubTemporal({"wf-1": _Outcome(raise_not_found=True)})
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result.deleted == 1
- assert raw.files.deleted == ["files/orphan"]
- assert not await _key_exists(gemini_redis, "files/orphan")
- assert not await _index_has(gemini_redis, "files/orphan")
-
-
-async def test_skips_on_temporal_rpc_error(activity_environment, fixed_now, gemini_redis):
- await _track(gemini_redis, file_name="files/unknown", workflow_id="wf-1", age=SWEEP_MIN_AGE * 10)
- raw, tmp = _StubRawClient(), _StubTemporal({"wf-1": _Outcome(raise_rpc_error=True)})
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result.skipped_temporal_error == 1
- assert result.deleted == 0
- assert await _key_exists(gemini_redis, "files/unknown")
- assert await _index_has(gemini_redis, "files/unknown")
-
-
-async def test_delete_failure_keeps_redis_state_for_retry(activity_environment, fixed_now, gemini_redis):
- await _track(gemini_redis, file_name="files/ok", workflow_id="wf-1", age=SWEEP_MIN_AGE * 10)
- await _track(gemini_redis, file_name="files/bad", workflow_id="wf-2", age=SWEEP_MIN_AGE * 10)
- raw = _StubRawClient()
- raw.files.delete_raises_for = {"files/bad": RuntimeError("simulated")}
- tmp = _StubTemporal(
- {
- "wf-1": _Outcome(status=WorkflowExecutionStatus.COMPLETED),
- "wf-2": _Outcome(status=WorkflowExecutionStatus.COMPLETED),
- }
- )
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result.deleted == 1
- assert result.delete_failed == 1
- assert raw.files.deleted == ["files/ok"]
- assert not await _key_exists(gemini_redis, "files/ok")
- assert not await _index_has(gemini_redis, "files/ok")
- assert await _key_exists(gemini_redis, "files/bad")
- assert await _index_has(gemini_redis, "files/bad")
-
-
[email protected]("code", [403, 404])
-async def test_treats_gemini_already_gone_as_success(activity_environment, fixed_now, gemini_redis, code):
- # If a previous untrack failed and left an orphan key, the actual file may already be gone
- # from Gemini. Missing files surface as 403 PERMISSION_DENIED ("...or it may not exist")
- # or 404. Don't keep retrying — drop the key and move on.
- await _track(gemini_redis, file_name="files/already-gone", workflow_id="wf-1", age=SWEEP_MIN_AGE * 10)
- raw = _StubRawClient()
- raw.files.delete_raises_for = {"files/already-gone": APIError(code=code, response_json={})}
- tmp = _StubTemporal({"wf-1": _Outcome(status=WorkflowExecutionStatus.COMPLETED)})
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result.deleted == 1
- assert result.delete_failed == 0
- assert not await _key_exists(gemini_redis, "files/already-gone")
- assert not await _index_has(gemini_redis, "files/already-gone")
-
-
-async def test_invalid_value_counted_separately(activity_environment, fixed_now, gemini_redis):
- await gemini_redis.set(f"{REDIS_KEY_PREFIX}files/garbage", "not-json")
- await gemini_redis.zadd(REDIS_INDEX_KEY, {"files/garbage": _NOW.timestamp()})
- raw, tmp = _StubRawClient(), _StubTemporal({})
-
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result.skipped_invalid_value == 1
- assert result.deleted == 0
-
-
-async def test_stale_index_entries_are_cleaned_up(activity_environment, fixed_now, gemini_redis):
- await gemini_redis.zadd(REDIS_INDEX_KEY, {"files/stale": _NOW.timestamp()})
- raw, tmp = _StubRawClient(), _StubTemporal({})
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result.scanned == 0
- assert result.deleted == 0
- assert not await _index_has(gemini_redis, "files/stale")
-
-
-async def test_hit_max_files_cap_set_when_index_exceeds_limit(activity_environment, fixed_now, gemini_redis):
- extras = MAX_FILES_PER_SWEEP + 1
- uploaded_at = _NOW - SWEEP_MIN_AGE * 10
- pipe = gemini_redis.pipeline()
- for i in range(extras):
- fn = f"files/n{i}"
- pipe.set(
- f"{REDIS_KEY_PREFIX}{fn}",
- json.dumps({"workflow_id": "wf-x", "uploaded_at": uploaded_at.isoformat()}),
- ex=int(REDIS_KEY_TTL.total_seconds()),
- )
- pipe.zadd(REDIS_INDEX_KEY, {fn: uploaded_at.timestamp()})
- await pipe.execute()
- raw, tmp = _StubRawClient(), _StubTemporal({"wf-x": _Outcome(raise_not_found=True)})
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result.hit_max_files_cap is True
- assert result.scanned == MAX_FILES_PER_SWEEP
- assert result.deleted == MAX_FILES_PER_SWEEP
-
-
-async def test_mixed_cycle_aggregates_correctly(activity_environment, fixed_now, gemini_redis):
- await _track(gemini_redis, file_name="files/young", workflow_id="wf-young", age=SWEEP_MIN_AGE / 2)
- await _track(gemini_redis, file_name="files/done", workflow_id="wf-done", age=SWEEP_MIN_AGE * 10)
- await _track(gemini_redis, file_name="files/running", workflow_id="wf-run", age=SWEEP_MIN_AGE * 10)
- await _track(gemini_redis, file_name="files/orphan", workflow_id="wf-orphan", age=SWEEP_MIN_AGE * 10)
- await _track(gemini_redis, file_name="files/error", workflow_id="wf-err", age=SWEEP_MIN_AGE * 10)
- await gemini_redis.set(f"{REDIS_KEY_PREFIX}files/garbage", "not-json")
- await gemini_redis.zadd(REDIS_INDEX_KEY, {"files/garbage": _NOW.timestamp()})
- raw = _StubRawClient()
- tmp = _StubTemporal(
- {
- "wf-done": _Outcome(status=WorkflowExecutionStatus.COMPLETED),
- "wf-run": _Outcome(status=WorkflowExecutionStatus.RUNNING),
- "wf-orphan": _Outcome(raise_not_found=True),
- "wf-err": _Outcome(raise_rpc_error=True),
- }
- )
- p1, p2 = _patch_clients(raw, tmp)
- with p1, p2:
- result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result.scanned == 6
- assert result.skipped_too_young == 1
- assert result.skipped_running == 1
- assert result.skipped_temporal_error == 1
- assert result.skipped_invalid_value == 1
- assert result.deleted == 2
- assert sorted(raw.files.deleted) == ["files/done", "files/orphan"]
diff --git a/posthog/temporal/tests/session_replay/gemini_cleanup_sweep/test_tracking.py b/posthog/temporal/tests/session_replay/gemini_cleanup_sweep/test_tracking.py
deleted file mode 100644
index b0f4c8d59b18..000000000000
--- a/posthog/temporal/tests/session_replay/gemini_cleanup_sweep/test_tracking.py
+++ /dev/null
@@ -1,156 +0,0 @@
-import json
-import datetime as dt
-
-import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
-
-from posthog.temporal.session_replay.gemini_cleanup_sweep.constants import (
- REDIS_INDEX_KEY,
- REDIS_KEY_PREFIX,
- REDIS_KEY_TTL,
-)
-from posthog.temporal.session_replay.gemini_cleanup_sweep.tracking import (
- index_size,
- iter_tracked_files,
- track_uploaded_file,
- untrack_uploaded_file,
-)
-from posthog.temporal.session_replay.gemini_cleanup_sweep.types import TrackedFile
-
-_NOW = dt.datetime(2026, 4, 24, 12, 0, 0, tzinfo=dt.UTC)
-
-
-async def _collect(it) -> list[TrackedFile | None]:
- return [item async for item in it]
-
-
-async def test_track_writes_per_file_key_and_index_entry(gemini_redis):
- await track_uploaded_file("files/abc", "wf-1", _NOW)
- raw = await gemini_redis.get(f"{REDIS_KEY_PREFIX}files/abc")
- assert raw is not None
- payload = json.loads(raw.decode() if isinstance(raw, bytes) else raw)
- assert payload == {"workflow_id": "wf-1", "uploaded_at": _NOW.isoformat()}
- assert await gemini_redis.zscore(REDIS_INDEX_KEY, "files/abc") == _NOW.timestamp()
- ttl = await gemini_redis.ttl(f"{REDIS_KEY_PREFIX}files/abc")
- assert 0 < ttl <= int(REDIS_KEY_TTL.total_seconds())
-
-
-async def test_track_raises_when_redis_pipeline_fails(gemini_redis):
- failing_pipe = MagicMock()
- failing_pipe.set = MagicMock()
- failing_pipe.zadd = MagicMock()
- failing_pipe.execute = AsyncMock(side_effect=RuntimeError("redis down"))
- failing_pipe.__aenter__ = AsyncMock(return_value=failing_pipe)
- failing_pipe.__aexit__ = AsyncMock(return_value=None)
-
- fake_redis = MagicMock()
- fake_redis.pipeline = MagicMock(return_value=failing_pipe)
- with patch(
- "posthog.temporal.session_replay.gemini_cleanup_sweep.tracking.get_async_client",
- return_value=fake_redis,
- ):
- with pytest.raises(RuntimeError, match="redis down"):
- await track_uploaded_file("files/abc", "wf-1", _NOW)
-
-
-async def test_untrack_clears_per_file_key_and_index_entry(gemini_redis):
- await track_uploaded_file("files/abc", "wf-1", _NOW)
- await untrack_uploaded_file("files/abc")
- assert await gemini_redis.exists(f"{REDIS_KEY_PREFIX}files/abc") == 0
- assert await gemini_redis.zscore(REDIS_INDEX_KEY, "files/abc") is None
-
-
-async def test_untrack_swallows_redis_errors(gemini_redis):
- failing_pipe = MagicMock()
- failing_pipe.delete = MagicMock()
- failing_pipe.zrem = MagicMock()
- failing_pipe.execute = AsyncMock(side_effect=RuntimeError("redis down"))
- failing_pipe.__aenter__ = AsyncMock(return_value=failing_pipe)
- failing_pipe.__aexit__ = AsyncMock(return_value=None)
-
- fake_redis = MagicMock()
- fake_redis.pipeline = MagicMock(return_value=failing_pipe)
- with patch(
- "posthog.temporal.session_replay.gemini_cleanup_sweep.tracking.get_async_client",
- return_value=fake_redis,
- ):
- await untrack_uploaded_file("files/abc")
-
-
-async def test_iter_yields_tracked_files(gemini_redis):
- await track_uploaded_file("files/a", "wf-a", _NOW)
- await track_uploaded_file("files/b", "wf-b", _NOW - dt.timedelta(seconds=10))
-
- items = await _collect(iter_tracked_files(limit=10))
- by_name = {t.gemini_file_name: t for t in items if t is not None}
- assert set(by_name) == {"files/a", "files/b"}
- assert by_name["files/a"].workflow_id == "wf-a"
- assert by_name["files/a"].uploaded_at == _NOW
- assert by_name["files/b"].workflow_id == "wf-b"
-
-
-async def test_iter_yields_oldest_first(gemini_redis):
- await track_uploaded_file("files/new", "wf-new", _NOW)
- await track_uploaded_file("files/old", "wf-old", _NOW - dt.timedelta(hours=2))
- await track_uploaded_file("files/middle", "wf-middle", _NOW - dt.timedelta(minutes=30))
-
- items = await _collect(iter_tracked_files(limit=10))
- names = [t.gemini_file_name for t in items if t is not None]
- assert names == ["files/old", "files/middle", "files/new"]
-
-
- "value",
- [
- "not-json", # JSONDecodeError
- '{"workflow_id": "wf-1"}', # KeyError on uploaded_at
- '{"workflow_id": "wf-1", "uploaded_at": "garbage"}', # ValueError from fromisoformat
- ],
-)
-async def test_iter_yields_none_for_invalid_payload(gemini_redis, value):
- await gemini_redis.set(f"{REDIS_KEY_PREFIX}files/garbage", value)
- await gemini_redis.zadd(REDIS_INDEX_KEY, {"files/garbage": _NOW.timestamp()})
- items = await _collect(iter_tracked_files(limit=10))
- assert items == [None]
-
-
-async def test_iter_cleans_up_stale_index_entries(gemini_redis):
- await gemini_redis.zadd(REDIS_INDEX_KEY, {"files/stale": _NOW.timestamp()})
- items = await _collect(iter_tracked_files(limit=10))
- assert items == []
- assert await gemini_redis.zscore(REDIS_INDEX_KEY, "files/stale") is None
-
-
-async def test_iter_respects_limit(gemini_redis):
- for i in range(20):
- await track_uploaded_file(f"files/n{i}", "wf-x", _NOW + dt.timedelta(seconds=i))
- items = await _collect(iter_tracked_files(limit=5))
- assert len(items) == 5
-
-
-async def test_iter_batches_across_mget_boundary(gemini_redis):
- n = 250 # > MGET_BATCH_SIZE (200)
- for i in range(n):
- await track_uploaded_file(f"files/n{i:04d}", "wf-x", _NOW + dt.timedelta(seconds=i))
- items = await _collect(iter_tracked_files(limit=n))
- assert len({t.gemini_file_name for t in items if t is not None}) == n
-
-
-async def test_index_size_returns_index_cardinality(gemini_redis):
- assert await index_size() == 0
- await track_uploaded_file("files/a", "wf-a", _NOW)
- await track_uploaded_file("files/b", "wf-b", _NOW)
- assert await index_size() == 2
- await untrack_uploaded_file("files/a")
- assert await index_size() == 1
diff --git a/posthog/temporal/tests/session_replay/gemini_cleanup_sweep/test_workflow.py b/posthog/temporal/tests/session_replay/gemini_cleanup_sweep/test_workflow.py
deleted file mode 100644
index dda3488dae6e..000000000000
--- a/posthog/temporal/tests/session_replay/gemini_cleanup_sweep/test_workflow.py
+++ /dev/null
@@ -1,55 +0,0 @@
-import uuid
-
-import pytest
-
-import temporalio.worker
-from temporalio import activity
-from temporalio.testing import WorkflowEnvironment
-from temporalio.worker import Worker
-
-from posthog.temporal.session_replay.gemini_cleanup_sweep.constants import WORKFLOW_NAME
-from posthog.temporal.session_replay.gemini_cleanup_sweep.types import CleanupSweepInputs, CleanupSweepResult
-from posthog.temporal.session_replay.gemini_cleanup_sweep.workflow import GeminiFileCleanupSweepWorkflow
-
-
-async def test_workflow_returns_activity_result_as_dict():
- @activity.defn(name="sweep_gemini_files_activity")
- async def sweep_mocked(inputs: CleanupSweepInputs) -> CleanupSweepResult:
- return CleanupSweepResult(
- scanned=42,
- deleted=10,
- skipped_running=5,
- skipped_too_young=20,
- skipped_temporal_error=1,
- skipped_invalid_value=2,
- delete_failed=1,
- hit_max_files_cap=True,
- )
-
- task_queue = str(uuid.uuid4())
- async with await WorkflowEnvironment.start_time_skipping() as env:
- async with Worker(
- env.client,
- task_queue=task_queue,
- workflows=[GeminiFileCleanupSweepWorkflow],
- activities=[sweep_mocked],
- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
- ):
- result = await env.client.execute_workflow(
- WORKFLOW_NAME,
- CleanupSweepInputs(),
- id=str(uuid.uuid4()),
- task_queue=task_queue,
- )
-
- assert result == {
- "scanned": 42,
- "deleted": 10,
- "skipped_running": 5,
- "skipped_too_young": 20,
- "skipped_temporal_error": 1,
- "skipped_invalid_value": 2,
- "delete_failed": 1,
- "hit_max_files_cap": True,
- }
diff --git a/posthog/test/dataclass_frozen_baseline.txt b/posthog/test/dataclass_frozen_baseline.txt
index e92b684f8a01..b5a6abd6450c 100644
--- a/posthog/test/dataclass_frozen_baseline.txt
+++ b/posthog/test/dataclass_frozen_baseline.txt
@@ -87,7 +87,6 @@
1 posthog/temporal/session_replay/session_summary/activities/capture_timing.py
1 posthog/temporal/tests/common/test_logger.py
1 posthog/temporal/tests/data_modeling/test_log_routing.py
-1 posthog/temporal/tests/session_replay/gemini_cleanup_sweep/test_activities.py
1 posthog/test/test_journeys.py
1 posthog/views.py
1 products/actions/backend/models/action.py
@@ -1430,7 +1429,6 @@
2 posthog/temporal/proxy_service/cloudflare.py
2 posthog/temporal/proxy_service/delete.py
2 posthog/temporal/salesforce_enrichment/workflow.py
-2 posthog/temporal/session_replay/gemini_cleanup_sweep/types.py
2 posthog/temporal/sync_person_distinct_ids/workflow.py
2 posthog/temporal/tests/common/test_error_tracking.py
2 posthog/temporal/tests/common/test_posthog_client_team_id.py
diff --git a/products/growth/backend/enrichment/labels.py b/products/growth/backend/enrichment/labels.py
index 95385967d382..6a231b4ad90f 100644
--- a/products/growth/backend/enrichment/labels.py
+++ b/products/growth/backend/enrichment/labels.py
@@ -476,7 +476,7 @@ def ai_processing_approved(organization_id: Any) -> bool:
A full-archive run spans hours, so an admin revoking consent partway through must be honored
for every org still queued, not just the ones enumerated after the change. Only an explicit
True approves: the column is nullable, and the rest of the codebase treats unset as unapproved
- (posthog/temporal/ai/sync_vectors.py, session_replay/summarization_sweep/activities.py).
+ (posthog/temporal/ai/sync_vectors.py).
"""
return Organization.objects.filter(pk=organization_id, is_ai_data_processing_approved=True).exists()
diff --git a/products/replay/mcp/apps/SessionRecordingView.tsx b/products/replay/mcp/apps/SessionRecordingView.tsx
index 475206162e96..62a0e31f0de5 100644
--- a/products/replay/mcp/apps/SessionRecordingView.tsx
+++ b/products/replay/mcp/apps/SessionRecordingView.tsx
@@ -22,7 +22,6 @@ export interface SessionRecordingData {
snapshot_source?: string | null
ongoing?: boolean
activity_score?: number | null
- has_summary?: boolean
person?: {
id?: number | string | null
distinct_ids?: string[]
diff --git a/products/replay_vision/backend/management/commands/provision_summarizer_scanners.py b/products/replay_vision/backend/management/commands/provision_summarizer_scanners.py
deleted file mode 100644
index 67c72ec72d69..000000000000
--- a/products/replay_vision/backend/management/commands/provision_summarizer_scanners.py
+++ /dev/null
@@ -1,157 +0,0 @@
-"""Give teams losing the legacy session summarization a Replay Vision summarizer in its place.
-
-Those teams had `session_replay`/`session_analysis_cluster` emitting signals into the inbox. Removing
-the old feature silences that source, so this mints one summarizer scanner per team to keep it fed.
-
-Deliberately a command rather than a migration: it creates billable resources for real customers, so
-it must be run in batches by a person watching credit burn, not fired at every team during a deploy.
-"""
-
-from typing import Any
-
-from django.core.management.base import BaseCommand, CommandError
-from django.db import transaction
-
-import structlog
-
-from posthog.models.team import Team
-
-from products.replay_vision.backend.api.scanners import _refresh_estimate_fail_soft
-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
-from products.replay_vision.backend.queries import MIN_SAMPLING_RATE
-from products.signals.backend.models import SignalSourceConfig
-
-logger = structlog.get_logger(__name__)
-
-SCANNER_NAME = "Session summary"
-SCANNER_DESCRIPTION = "A short narrative summary of the session."
-
-# Kept in step by hand with the `session_summary` scanner template the picker offers, so a provisioned
-# scanner and a hand-created one produce the same shape of summary.
-SCANNER_PROMPT = (
- "Summarize what the user did in this session: which pages they visited, what they tried to "
- "accomplish, and any notable moments like errors, confusion, or successful completions. "
- "Be concrete and don't speculate."
-)
-
-
-class Command(BaseCommand):
- help = "Provision a summarizer scanner for teams that had the legacy session summarization signal source."
-
- def add_arguments(self, parser: Any) -> None:
- parser.add_argument(
- "--credit-limit",
- type=int,
- required=True,
- help="Per-scanner credit cap per billing period. Required: without it a provisioned scanner "
- "spends against the org's whole allowance, including purchased credits.",
- )
- parser.add_argument(
- "--sampling-rate",
- type=float,
- default=0.1,
- help="Fraction of matching recordings to scan (default 0.1).",
- )
- parser.add_argument(
- "--model",
- default=ScannerModel.GEMINI_3_5_FLASH_LITE,
- choices=[m.value for m in ScannerModel],
- help="Model to scan with; the cheapest is the default.",
- )
- parser.add_argument("--limit", type=int, help="Provision at most this many teams, for staged rollout.")
- parser.add_argument("--team-ids", help="Comma-separated team ids to restrict to.")
- parser.add_argument(
- "--apply",
- action="store_true",
- help="Actually create scanners. Without it the command only reports what it would do.",
- )
-
- def handle(self, *args: Any, **options: Any) -> None:
- # The cap is the whole safety story, so refuse to run on a build that cannot enforce one rather
- # than silently creating scanners that spend against the org's full balance.
- if not any(f.name == "credit_limit" for f in ReplayScanner._meta.get_fields()):
- raise CommandError(
- "ReplayScanner has no `credit_limit` field, so a per-scanner cap cannot be set. "
- "This command needs the per-scanner credit limit work deployed first."
- )
- if options["credit_limit"] < 1:
- raise CommandError("--credit-limit must be at least 1.")
- # Same floor the serializer enforces: below it a scanner samples so little it scans nothing.
- if not MIN_SAMPLING_RATE <= options["sampling_rate"] <= 1.0:
- raise CommandError(f"--sampling-rate must be between {MIN_SAMPLING_RATE} and 1.")
-
- team_ids = self._target_team_ids(options.get("team_ids"))
-
- created = skipped_no_consent = 0
- for team in Team.objects.filter(id__in=team_ids).select_related("organization").order_by("id"):
- # Scanner creation through the API refuses without org approval; a command must not be a way around it.
- if not team.organization.is_ai_data_processing_approved:
- skipped_no_consent += 1
- self.stdout.write(f" skip team {team.id}: org has not approved AI data processing")
- continue
-
- # Counted after the consent skip so `--limit 10` provisions ten teams rather than considering ten.
- if options.get("limit") and created >= options["limit"]:
- break
-
- if not options["apply"]:
- self.stdout.write(f" would provision team {team.id}")
- created += 1
- continue
-
- with transaction.atomic():
- scanner = self._create_scanner(team, options)
- # Without this the scanner spends credits while missing from the org's spend forecast.
- _refresh_estimate_fail_soft(scanner)
- logger.info(
- "replay_vision.provisioned_summarizer",
- team_id=team.id,
- scanner_id=str(scanner.id),
- credit_limit=options["credit_limit"],
- )
- self.stdout.write(f" provisioned team {team.id} -> scanner {scanner.id}")
- created += 1
-
- verb = "provisioned" if options["apply"] else "would provision"
- self.stdout.write(
- self.style.SUCCESS(f"{verb} {created} team(s); skipped {skipped_no_consent} without AI consent")
- )
- if not options["apply"]:
- self.stdout.write("Dry run. Re-run with --apply to create these scanners.")
-
- def _target_team_ids(self, restrict_to: str | None) -> list[int]:
- """Teams still on the legacy source that have no scanner of their own to replace it."""
- enabled = SignalSourceConfig.objects.filter(
- source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,
- source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
- enabled=True,
- )
- team_ids = set(enabled.values_list("team_id", flat=True))
- if restrict_to:
- try:
- team_ids &= {int(t) for t in restrict_to.split(",") if t.strip()}
- except ValueError:
- raise CommandError("--team-ids must be a comma-separated list of integers.")
- # `objects` is configured-only, so an inline scan from a summarize click never counts as one.
- already = set(ReplayScanner.objects.filter(team_id__in=team_ids).values_list("team_id", flat=True))
- return sorted(team_ids - already)
-
- def _create_scanner(self, team: Team, options: dict[str, Any]) -> ReplayScanner:
- fields: dict[str, Any] = {
- "team": team,
- # No creator: nobody asked for this scanner, so crediting a user would misattribute it.
- "created_by": None,
- "name": SCANNER_NAME,
- "description": SCANNER_DESCRIPTION,
- "scanner_type": ScannerType.SUMMARIZER,
- "scanner_config": {"prompt": SCANNER_PROMPT, "length": "medium"},
- "model": options["model"],
- "sampling_rate": options["sampling_rate"],
- "emits_signals": True,
- "enabled": True,
- # Set dynamically because the field ships with the per-scanner credit limit work, which this
- # command predates. `handle` refuses to run until it exists, so this is never silently dropped.
- "credit_limit": options["credit_limit"],
- }
- # No built-in digest: it is a second scheduled LLM run per day, and nobody asked for this scanner.
- return ReplayScanner.objects.create(**fields)
diff --git a/products/replay_vision/backend/tests/test_signals_onboarding.py b/products/replay_vision/backend/tests/test_signals_onboarding.py
index 05adb2e3742a..18eec05a108e 100644
--- a/products/replay_vision/backend/tests/test_signals_onboarding.py
+++ b/products/replay_vision/backend/tests/test_signals_onboarding.py
@@ -46,5 +46,5 @@ class TestOnboardingSources(BaseTest):
# It has no config row to write, and submitting the checkbox snapshot without it must not
# read as "untick Replay Vision".
self._emitting_scanner()
- assert set_sources(self.team.id, None, ["error_tracking"]) == []
+ set_sources(self.team.id, None, ["error_tracking"])
assert self._source("replay_vision").enabled is True
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index a1e76ce7d1dc..46d6ca1299d9 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -533,7 +533,6 @@ Per-team configuration for which signal sources are enabled.
- `llm_analytics` signals go through the standard enabled-row check like every other source. `evaluation_report` is the only type AI observability emits, gated by its own `(llm_analytics, evaluation_report)` row (the inbox "AI observability" toggle). The per-result workflow and activity remain registered only so existing Temporal histories can finish replaying.
- For session replay configs, serializer validation enforces that `config.recording_filters` is a JSON object when present.
- The serializer exposes a computed `status` field:
- - `session_analysis_cluster` derives status from the Temporal clustering workflow
- data-import-backed sources (`github`, `linear`, `zendesk`) derive status from `ExternalDataSchema`
- The `signals_scout` source variant pairs with `source_type=cross_source_issue` and is the emission channel used by the headless Signals agent's `emit_signal_*` tools. It is the only `(source_product, source_type)` pair the agent emits today.
@@ -806,10 +805,8 @@ Full CRUD for per-team signal source configurations. Uses `IsAuthenticated` + `A
Important side effects:
-- Creating or enabling a `session_analysis_cluster` config starts the clustering workflow
- Creating an enabled `error_tracking / issue_created` config starts the error-tracking backfill workflow
- Enabling data-import-backed sources can trigger external data syncs
-- Disabling a clustering config cancels the clustering workflow
#### `SignalTeamConfigViewSet`
@@ -934,7 +931,7 @@ Generated MCP tool names:
- **`SignalSourceConfigSerializer`**
- Exposes `id`, `source_product`, `source_type`, `enabled`, `config`, `created_at`, `updated_at`, `status`
- Validates that `recording_filters` in config is a JSON object for `session_replay`
- - Computes `status` from the clustering workflow or external data import state depending on the source
+ - Computes `status` from external data import state for data-import-backed sources
- **`SignalTeamConfigSerializer`**
- ModelSerializer for `SignalTeamConfig`
- Exposes `id`, `default_autostart_priority`, `created_at`, `updated_at`
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index 66e6135b999d..492335e04645 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -195,8 +195,6 @@ def set_default_slack_notification_channel(team_id: int, value: str | None) -> N
# One catalog drives the list, the toggles, and the "connected" checks.
# ---------------------------------------------------------------------------
-_DEFAULT_SESSION_ANALYSIS_SAMPLE_RATE = 0.1
-
@dataclasses.dataclass(frozen=True)
class OnboardingSource:
@@ -227,7 +225,6 @@ class _SourceSpec:
# The SignalSourceConfig (source_product, source_type) rows ticking this source enables.
# Empty when the source authorizes itself elsewhere, which is also what makes it untickable.
pairs: tuple[tuple[str, str], ...] = ()
- needs_ai_approval: bool = False
# Reads the on/off state of a source that has no config row to read it from.
enabled_check: Callable[[int], bool] | None = None
@@ -249,29 +246,22 @@ _SOURCE_CATALOG: tuple[_SourceSpec, ...] = (
"bugs and UX problems scanners find in recordings",
enabled_check=_has_emitting_replay_scanner,
),
- _SourceSpec(
- "session_replay",
- "Session replay analysis (legacy)",
- "problems real users hit. Replay vision covers this now",
- (("session_replay", "session_analysis_cluster"),),
- needs_ai_approval=True,
- ),
)
_SOURCE_BY_KEY: dict[str, _SourceSpec] = {spec.key: spec for spec in _SOURCE_CATALOG}
-def _ai_data_processing_approved(team_id: int) -> bool:
- return bool(
- Team.objects.filter(id=team_id).values_list("organization__is_ai_data_processing_approved", flat=True).first()
- )
-
-
def has_enabled_source(team_id: int) -> bool:
"""True once the team has at least one enabled signal source — i.e. there's something to respond to.
Replay Vision is checked separately because it has no config row to find: each scanner's own
`emits_signals` flag authorizes it (see `SignalSourceConfig.is_source_enabled`)."""
- if SignalSourceConfig.objects.filter(team_id=team_id, enabled=True).exists():
+ if (
+ SignalSourceConfig.objects.filter(team_id=team_id, enabled=True)
+ # Retired: rows outlive the feature until the cleanup migration runs, and counting one marks
+ # onboarding complete on a source that emits nothing.
+ .exclude(source_product="session_replay", source_type="session_analysis_cluster")
+ .exists()
+ ):
return True
return _has_emitting_replay_scanner(team_id)
@@ -315,29 +305,19 @@ def onboarding_sources(team_id: int) -> list[OnboardingSource]:
]
-def set_sources(team_id: int, user_id: int | None, selected_keys: list[str]) -> list[str]:
+def set_sources(team_id: int, user_id: int | None, selected_keys: list[str]) -> None:
"""Sync the team's onboarding sources to ``selected_keys`` (tick = enable, untick = disable;
- enabling a source sets up its SignalSourceConfig). Returns the labels of any that couldn't be
- enabled because AI data processing isn't approved (session replay analysis)."""
+ enabling a source sets up its SignalSourceConfig)."""
selected = set(selected_keys)
- ai_approved = _ai_data_processing_approved(team_id)
- blocked: list[str] = []
for spec in _SOURCE_CATALOG:
if not spec.pairs:
# Authorized elsewhere (Replay Vision, per scanner), so onboarding never offered it as a
# checkbox and has nothing to write here.
continue
want_on = spec.key in selected
- if want_on and spec.needs_ai_approval and not ai_approved:
- # Wanted but AI-gated: leave the source as-is. Disabling here would silently turn off a
- # previously-approved source when the full checkbox snapshot is re-submitted.
- blocked.append(spec.label)
- continue
for source_product, source_type in spec.pairs:
if want_on:
defaults: dict = {"enabled": True, "created_by_id": user_id}
- if source_type == "session_analysis_cluster":
- defaults["config"] = {"sample_rate": _DEFAULT_SESSION_ANALYSIS_SAMPLE_RATE}
obj, created = SignalSourceConfig.objects.get_or_create(
team_id=team_id, source_product=source_product, source_type=source_type, defaults=defaults
)
@@ -348,7 +328,6 @@ def set_sources(team_id: int, user_id: int | None, selected_keys: list[str]) ->
SignalSourceConfig.objects.filter(
team_id=team_id, source_product=source_product, source_type=source_type, enabled=True
).update(enabled=False)
- return blocked
# The signal channel's generic `extra` passthrough only forwards top-level *scalar* values,
diff --git a/products/signals/backend/migrations/0094_delete_session_analysis_source_configs.py b/products/signals/backend/migrations/0094_delete_session_analysis_source_configs.py
new file mode 100644
index 000000000000..18a80c01c290
--- /dev/null
+++ b/products/signals/backend/migrations/0094_delete_session_analysis_source_configs.py
@@ -0,0 +1,34 @@
+from django.db import migrations
+
+
+def delete_session_analysis_configs(apps, schema_editor):
+ """Drop the config rows for the retired session summarization signal source.
+
+ Nothing has emitted against them since the feature was removed, and this release takes away the
+ last surface that read them, so a team could neither turn the source off nor get anything from
+ leaving it on. They also made `has_enabled_source` report true, which let onboarding read as
+ finished on the strength of a source that produces nothing.
+
+ Deleted in batches: this is roughly 1,800 rows across both regions, and one unbounded DELETE
+ would hold row locks on the whole set for the length of the statement.
+ """
+ SignalSourceConfig = apps.get_model("signals", "SignalSourceConfig")
+ doomed = SignalSourceConfig.objects.filter(
+ source_product="session_replay",
+ source_type="session_analysis_cluster",
+ )
+ while True:
+ batch = list(doomed.values_list("id", flat=True)[:500])
+ if not batch:
+ break
+ SignalSourceConfig.objects.filter(id__in=batch).delete()
+
+
+class Migration(migrations.Migration):
+ dependencies = [("signals", "0093_delete_per_evaluation_source_configs")]
+
+ # Deleting rows nothing reads is not reversible in any meaningful sense: re-creating them would
+ # invent config a team never asked for.
+ operations = [
+ migrations.RunPython(delete_session_analysis_configs, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index aa08f96aa197..648f9b1bd368 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0093_delete_per_evaluation_source_configs
+0094_delete_session_analysis_source_configs
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 015224fe5c28..73c485c72a52 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -1,19 +1,14 @@
import json
-import logging
from collections.abc import Mapping
from typing import cast
from django.db.models import Q
-from asgiref.sync import async_to_sync
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field
-from opentelemetry import trace
-from opentelemetry.trace import Status, StatusCode
from rest_framework import serializers
from posthog.models import User
-from posthog.temporal.common.client import sync_connect
from products.signals.backend import contracts
from products.signals.backend.billing import REFUND_INELIGIBILITY_REASONS, refund_ineligibility_reason
@@ -32,9 +27,6 @@ from .models import (
from .report_charts import CHART_SIZES, MAX_CHART_CAPTION_LENGTH, MAX_CHART_ID_LENGTH, MAX_CHART_TITLE_LENGTH
from .report_generation.resolve_reviewers import enrich_reviewer_dicts_with_org_members
-logger = logging.getLogger(__name__)
-tracer = trace.get_tracer(__name__)
-
DEFAULT_SESSION_ANALYSIS_SAMPLE_RATE = 0.1
@@ -65,41 +57,12 @@ class SignalSourceConfigSerializer(serializers.ModelSerializer):
read_only_fields = ["id", "created_at", "updated_at", "status"]
def get_status(self, obj: SignalSourceConfig) -> str | None:
- if obj.source_type == SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER:
- return self._get_session_analysis_status(obj.team_id)
-
mapping = _DATA_IMPORT_SOURCE_MAP.get((obj.source_product, obj.source_type))
if mapping is None:
return None
ext_source_type, schema_name = mapping
return self._get_data_import_status(obj.team_id, ext_source_type, schema_name)
- # Per-row Temporal RPC: serializing N source configs issues N of these on inbox load.
- # The span surfaces that cost so the N+1 is visible per request in APM.
- @tracer.start_as_current_span("signals.source_config.session_analysis_status")
- def _get_session_analysis_status(self, team_id: int) -> str | None:
- """ "running" iff any `summarize-session` workflow for this team is currently executing."""
- query = f'PostHogTeamId = {team_id} AND WorkflowType = "summarize-session" AND ExecutionStatus = "Running"'
-
- try:
- temporal = sync_connect()
-
- async def has_running() -> bool:
- async for _ in temporal.list_workflows(query=query, page_size=1):
- return True
- return False
-
- if async_to_sync(has_running)():
- return "running"
- except Exception as e:
- # The except swallows the error, so OTel won't auto-record it on the span — mark it
- # failed explicitly, else an unreachable Temporal looks like a successful no-op in APM.
- span = trace.get_current_span()
- span.record_exception(e)
- span.set_status(Status(StatusCode.ERROR))
- logger.warning("Failed to list session summarization workflows: %s", e)
- return None
-
def _get_data_import_status(self, team_id: int, ext_source_type: str, schema_name: str) -> str | None:
from products.warehouse_sources.backend.facade.models import ExternalDataSchema
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 1b924e462179..e73cc6de45bd 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -353,8 +353,7 @@ class SignalSourceConfigViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
if instance.enabled and not was_enabled:
- if instance.source_type != SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER:
- self._trigger_data_import_sync(instance)
+ self._trigger_data_import_sync(instance)
# Maps source_product to ExternalDataSourceType value for data import sources
_DATA_IMPORT_SOURCE_TYPE_MAP: dict[str, str] = {
diff --git a/products/signals/frontend/inbox/InboxScene.tsx b/products/signals/frontend/inbox/InboxScene.tsx
index ec51ff9d4293..ad6be9ac39c6 100644
--- a/products/signals/frontend/inbox/InboxScene.tsx
+++ b/products/signals/frontend/inbox/InboxScene.tsx
@@ -2,11 +2,10 @@ import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import React, { useEffect, useRef } from 'react'
-import { IconArrowLeft, IconBug } from '@posthog/icons'
-import { LemonButton, Tooltip } from '@posthog/lemon-ui'
+import { IconArrowLeft } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
import { useResizeBreakpoints } from 'lib/hooks/useResizeObserver'
-import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -252,7 +251,6 @@ function InboxPanelView({ onBack, children }: { onBack: () => void; children: JS
export function InboxScene(): JSX.Element {
const {
activeTab,
- isRunningSessionAnalysis,
selectedReportId,
selectedReport,
selectedReportLoading,
@@ -260,9 +258,8 @@ export function InboxScene(): JSX.Element {
isScratchpadOpen,
isFindingsOpen,
} = useValues(inboxSceneLogic)
- const { runSessionAnalysis, setScratchpadOpen, setFindingsOpen } = useActions(inboxSceneLogic)
+ const { setScratchpadOpen, setFindingsOpen } = useActions(inboxSceneLogic)
const { onboardingMode, isWelcomeRedesign } = useValues(inboxOnboardingLogic)
- const { isDev } = useValues(preflightLogic)
const { searchParams } = useValues(router)
// Surfaces that embed inbox cards (e.g. the customer analytics feed) set a `?back=` internal path;
@@ -310,23 +307,7 @@ export function InboxScene(): JSX.Element {
: INBOX_TAB_DESCRIPTION[activeTab]
}
resourceType={{ type: 'inbox' }}
- actions={
- isDev ? (
- <Tooltip title="Analyze the last 7 days of sessions">
- <LemonButton
- type="secondary"
- onClick={() => runSessionAnalysis()}
- loading={isRunningSessionAnalysis}
- size="small"
- data-attr="run-session-analysis-button"
- tooltip="DEBUG-only"
- icon={<IconBug />}
- >
- Run session analysis
- </LemonButton>
- </Tooltip>
- ) : undefined
- }
+ actions={undefined}
/>
<div className="flex flex-col -mx-4 -mt-4 flex-1 min-h-0">
diff --git a/products/signals/frontend/inbox/SessionAnalysisSetup.tsx b/products/signals/frontend/inbox/SessionAnalysisSetup.tsx
deleted file mode 100644
index e70bc0abf751..000000000000
--- a/products/signals/frontend/inbox/SessionAnalysisSetup.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-import { BindLogic, useActions, useValues } from 'kea'
-import { useEffect } from 'react'
-
-import { Logomark } from 'lib/brand'
-import { SidebarQuestionInput } from 'scenes/max/components/SidebarQuestionInput'
-import { ThreadAutoScroller } from 'scenes/max/components/ThreadAutoScroller'
-import { maxLogic } from 'scenes/max/maxLogic'
-import { MaxThreadLogicProps, maxThreadLogic } from 'scenes/max/maxThreadLogic'
-import { Thread } from 'scenes/max/Thread'
-
-import { AgentMode } from '~/queries/schema/schema-assistant-messages'
-
-import { signalSourcesLogic } from './signalSourcesLogic'
-
-const INBOX_TAB_ID = 'inbox-setup'
-
-const SUGGESTIONS = ['Just logged-in sessions', 'Sessions where users used our product']
-
-function SessionAnalysisSetupIntro(): JSX.Element {
- return (
- <div className="flex flex-col items-center text-center">
- <div className="flex p-1">
- <Logomark size="sm" />
- </div>
- <h3 className="text-base font-bold mb-0.5">Configure session filters</h3>
- <p className="text-xs text-secondary max-w-sm mb-0">
- Describe what sessions to analyze. PostHog AI will help you build the right filters.
- </p>
- </div>
- )
-}
-
-function SessionAnalysisSetupSuggestions(): JSX.Element {
- const { askMax } = useActions(maxLogic)
-
- return (
- <div className="flex flex-wrap gap-1.5 justify-center max-w-md">
- {SUGGESTIONS.map((suggestion) => (
- <button
- key={suggestion}
- type="button"
- className="text-xs px-2.5 py-1 rounded-full border bg-surface-primary hover:bg-surface-secondary transition-colors cursor-pointer"
- onClick={() => askMax(suggestion)}
- >
- {suggestion}
- </button>
- ))}
- </div>
- )
-}
-
-function SessionAnalysisSetupChat(): JSX.Element {
- const { threadVisible } = useValues(maxLogic)
- const { setAgentMode } = useActions(maxThreadLogic)
-
- useEffect(() => {
- setAgentMode(AgentMode.SessionReplay)
- }, [setAgentMode])
-
- const hasMessages = threadVisible
-
- return (
- <div className="flex flex-col grow overflow-y-auto h-full" data-attr="max-scrollable">
- <div
- className={`flex flex-col items-center gap-3 transition-all duration-200 ease-out ${
- hasMessages ? 'opacity-0 h-0 overflow-hidden' : 'opacity-100 pb-3'
- }`}
- >
- <SessionAnalysisSetupIntro />
- <SessionAnalysisSetupSuggestions />
- </div>
-
- {hasMessages && (
- <ThreadAutoScroller>
- <Thread className="p-3" />
- </ThreadAutoScroller>
- )}
-
- <div
- className={`w-full max-w-3xl mx-auto px-3 transition-all duration-300 ease-out z-50 ${
- hasMessages ? 'sticky bottom-0 bg-primary py-2 max-w-none' : ''
- }`}
- >
- <SidebarQuestionInput />
- </div>
- </div>
- )
-}
-
-export function SessionAnalysisSetup(): JSX.Element {
- const { saveSessionAnalysisFilters } = useActions(signalSourcesLogic)
- const maxLogicProps = { panelId: INBOX_TAB_ID, onAcceptSessionFilters: saveSessionAnalysisFilters }
- const { threadLogicKey, conversation } = useValues(maxLogic(maxLogicProps))
-
- return (
- <BindLogic logic={maxLogic} props={maxLogicProps}>
- <BindLogic
- logic={maxThreadLogic}
- props={
- {
- panelId: INBOX_TAB_ID,
- conversationId: threadLogicKey,
- conversation,
- } satisfies MaxThreadLogicProps
- }
- >
- <SessionAnalysisSetupChat />
- </BindLogic>
- </BindLogic>
- )
-}
diff --git a/products/signals/frontend/inbox/SourcesList.tsx b/products/signals/frontend/inbox/SourcesList.tsx
index 916217e8147c..72dd8ef22089 100644
--- a/products/signals/frontend/inbox/SourcesList.tsx
+++ b/products/signals/frontend/inbox/SourcesList.tsx
@@ -2,9 +2,8 @@ import { useActions, useValues } from 'kea'
import { useState } from 'react'
import { IconArrowRight, IconBell, IconGithub, IconGraph, IconHeartPlus, IconLinear } from '@posthog/icons'
-import { LemonButton, Spinner } from '@posthog/lemon-ui'
+import { LemonButton } from '@posthog/lemon-ui'
-import { RecordingsUniversalFiltersDisplay } from 'lib/components/Cards/InsightCard/RecordingsUniversalFiltersDisplay'
import { IconSlack } from 'lib/lemon-ui/icons'
import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
@@ -14,7 +13,6 @@ import iconZendesk from 'public/services/zendesk.svg'
import { captureSignalSourceInterest } from './inboxAnalytics'
import { PgAnalyzeIcon as IconPgAnalyze } from './PgAnalyzeIcon'
import { signalSourcesLogic } from './signalSourcesLogic'
-import { SignalSourceConfigStatus } from './types'
type SourceProps =
| {
@@ -123,25 +121,8 @@ function Source(props: SourceProps): JSX.Element {
)
}
-function isNonEmptyFilters(obj: unknown): boolean {
- return obj != null && typeof obj === 'object' && Object.keys(obj as Record<string, unknown>).length > 0
-}
-
-function SessionAnalysisStatusIndicator({ status }: { status: SignalSourceConfigStatus | null }): JSX.Element | null {
- if (status === SignalSourceConfigStatus.RUNNING) {
- return (
- <div className="mt-2 flex items-center gap-2 rounded bg-accent-light text-xs text-accent">
- <Spinner className="size-3.5" />
- <span>Summarizing sessions…</span>
- </div>
- )
- }
- return null
-}
-
export function SourcesList(): JSX.Element {
const {
- sessionAnalysisConfig,
githubIssuesConfig,
linearIssuesConfig,
zendeskTicketsConfig,
@@ -149,7 +130,6 @@ export function SourcesList(): JSX.Element {
errorTrackingIsFullyEnabled,
healthChecksConfig,
anomalyInvestigationConfig,
- isSessionAnalysisToggling,
isGithubIssuesToggling,
isLinearIssuesToggling,
isZendeskTicketsToggling,
@@ -158,48 +138,11 @@ export function SourcesList(): JSX.Element {
isHealthChecksToggling,
isAnomalyInvestigationToggling,
} = useValues(signalSourcesLogic)
- const {
- toggleSessionAnalysis,
- openSessionAnalysisSetup,
- clearSessionAnalysisFilters,
- initiateDataWarehouseSourceToggle,
- toggleErrorTracking,
- toggleHealthChecks,
- toggleAnomalyInvestigation,
- } = useActions(signalSourcesLogic)
-
- const recordingFilters = sessionAnalysisConfig?.config?.recording_filters
- const hasNonEmptyFilters = isNonEmptyFilters(recordingFilters)
+ const { initiateDataWarehouseSourceToggle, toggleErrorTracking, toggleHealthChecks, toggleAnomalyInvestigation } =
+ useActions(signalSourcesLogic)
return (
<div className="divide-y space-y-3">
- <Source
- icon={
- <div className="flex *:text-xl group/colorful-product-icons colorful-product-icons-true">
- {iconForType('session_replay')}
- </div>
- }
- title="PostHog Session replay"
- description="Session recordings + event data → Signals"
- variant="available"
- checked={!!sessionAnalysisConfig?.enabled}
- loading={isSessionAnalysisToggling}
- onToggle={() => toggleSessionAnalysis()}
- config={{
- buttonLabel: recordingFilters ? 'Edit' : 'Configure',
- onClick: openSessionAnalysisSetup,
- display: recordingFilters ? (
- <RecordingsUniversalFiltersDisplay filters={recordingFilters} />
- ) : (
- <div className="px-2 pb-2">
- <span className="text-xs text-secondary">All sessions</span>
- </div>
- ),
- }}
- onClearClick={hasNonEmptyFilters ? clearSessionAnalysisFilters : undefined}
- statusSection={<SessionAnalysisStatusIndicator status={sessionAnalysisConfig?.status ?? null} />}
- />
-
<Source
icon={
<div className="flex *:text-xl group/colorful-product-icons colorful-product-icons-true">
diff --git a/products/signals/frontend/inbox/__mocks__/inboxMocks.ts b/products/signals/frontend/inbox/__mocks__/inboxMocks.ts
index 11da7327b54e..bcc77466d4d0 100644
--- a/products/signals/frontend/inbox/__mocks__/inboxMocks.ts
+++ b/products/signals/frontend/inbox/__mocks__/inboxMocks.ts
@@ -507,16 +507,6 @@ index 9c8b7a6..2f3e4d5 100644
export const mockSourceConfigs = {
results: [
- {
- id: 'sc-1',
- source_product: 'session_replay',
- source_type: 'session_analysis_cluster',
- enabled: true,
- config: {},
- created_at: BASE_DATE,
- updated_at: BASE_DATE,
- status: 'completed',
- },
{
id: 'sc-2',
source_product: 'error_tracking',
diff --git a/products/signals/frontend/inbox/components/config/AgentsRoster.tsx b/products/signals/frontend/inbox/components/config/AgentsRoster.tsx
index 40f3fcd3da62..c5db845ef15e 100644
--- a/products/signals/frontend/inbox/components/config/AgentsRoster.tsx
+++ b/products/signals/frontend/inbox/components/config/AgentsRoster.tsx
@@ -516,7 +516,6 @@ const AgentRow = memo(function AgentRow({
export function AgentsRoster(): JSX.Element {
const {
- sessionAnalysisConfig,
conversationsConfig,
evalReportsConfig,
anomalyInvestigationConfig,
@@ -531,7 +530,6 @@ export function AgentsRoster(): JSX.Element {
errorTrackingTypeStates,
visionScanners,
visionScannersLoading,
- isSessionAnalysisToggling,
isConversationsToggling,
isEvalReportsToggling,
isAnomalyInvestigationToggling,
@@ -546,7 +544,6 @@ export function AgentsRoster(): JSX.Element {
enablingTool,
} = useValues(signalSourcesLogic)
const {
- toggleSessionAnalysis,
toggleConversations,
toggleErrorTracking,
toggleErrorTrackingType,
@@ -557,7 +554,6 @@ export function AgentsRoster(): JSX.Element {
toggleScannerSignals,
initiateDataWarehouseSourceToggle,
enableSourceTool,
- openSessionAnalysisSetup,
loadToolDataEvents,
} = useActions(signalSourcesLogic)
const { featureFlags } = useValues(featureFlagLogic)
@@ -627,14 +623,6 @@ export function AgentsRoster(): JSX.Element {
entities: scannerEntities,
entitiesLoading: visionScanners === null && visionScannersLoading,
}
- case 'session_replay':
- return {
- ...base,
- armed: !!sessionAnalysisConfig?.enabled,
- loading: isSessionAnalysisToggling,
- requiresSetup: false,
- syncStatus: sessionAnalysisConfig?.status,
- }
case 'llm_analytics':
return {
...base,
@@ -687,8 +675,6 @@ export function AgentsRoster(): JSX.Element {
scannerEntities,
visionScanners,
visionScannersLoading,
- sessionAnalysisConfig,
- isSessionAnalysisToggling,
evalReportsConfig,
isEvalReportsToggling,
anomalyInvestigationConfig,
@@ -722,9 +708,6 @@ export function AgentsRoster(): JSX.Element {
case 'conversations':
toggleConversations()
return
- case 'session_replay':
- toggleSessionAnalysis()
- return
case 'llm_analytics':
toggleEvalReports()
return
@@ -748,7 +731,6 @@ export function AgentsRoster(): JSX.Element {
[
toggleErrorTracking,
toggleConversations,
- toggleSessionAnalysis,
toggleEvalReports,
toggleCiSignals,
toggleAnomalyInvestigation,
@@ -804,9 +786,7 @@ export function AgentsRoster(): JSX.Element {
onToggle={handleToggle}
onToggleEntity={handleToggleEntity}
onEnableTool={(tool) => tool.enablement && enableSourceTool(tool.enablement)}
- onConfigureFilters={
- agent.source === 'session_replay' ? openSessionAnalysisSetup : undefined
- }
+ onConfigureFilters={undefined}
onRetryData={loadToolDataEvents}
/>
))}
diff --git a/products/signals/frontend/inbox/components/config/AgentsTab.tsx b/products/signals/frontend/inbox/components/config/AgentsTab.tsx
index 132deff3eba7..7de50a5e7784 100644
--- a/products/signals/frontend/inbox/components/config/AgentsTab.tsx
+++ b/products/signals/frontend/inbox/components/config/AgentsTab.tsx
@@ -7,7 +7,6 @@ import { LemonButton } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { SessionAnalysisSetup } from '../../SessionAnalysisSetup'
import { signalSourcesLogic } from '../../signalSourcesLogic'
import { AgentsRoster } from './AgentsRoster'
import { ConnectionsSection } from './ConnectionsSection'
@@ -52,16 +51,10 @@ function BackLink({ onClick }: { onClick: () => void }): JSX.Element {
* render inline (replacing the roster) when their sub-flow is open.
*/
export function AgentsTab(): JSX.Element {
- const { sessionAnalysisSetupOpen, dataSourceSetupSource } = useValues(signalSourcesLogic)
+ const { dataSourceSetupSource } = useValues(signalSourcesLogic)
const { featureFlags } = useValues(featureFlagLogic)
- const {
- loadSources,
- loadSourceConfigs,
- loadToolDataEvents,
- closeSessionAnalysisSetup,
- closeDataSourceSetup,
- onDataSourceSetupComplete,
- } = useActions(signalSourcesLogic)
+ const { loadSources, loadSourceConfigs, loadToolDataEvents, closeDataSourceSetup, onDataSourceSetupComplete } =
+ useActions(signalSourcesLogic)
useEffect(() => {
loadSources()
@@ -77,13 +70,6 @@ export function AgentsTab(): JSX.Element {
<DataSourceSetup source={dataSourceSetupSource} onComplete={() => onDataSourceSetupComplete()} />
</div>
)
- } else if (sessionAnalysisSetupOpen) {
- agentsBody = (
- <div className="flex flex-col gap-3">
- <BackLink onClick={closeSessionAnalysisSetup} />
- <SessionAnalysisSetup />
- </div>
- )
} else {
agentsBody = <AgentsRoster />
}
diff --git a/products/signals/frontend/inbox/components/config/SignalSourcesPanel.tsx b/products/signals/frontend/inbox/components/config/SignalSourcesPanel.tsx
index aed5c68d6023..70eafafe274a 100644
--- a/products/signals/frontend/inbox/components/config/SignalSourcesPanel.tsx
+++ b/products/signals/frontend/inbox/components/config/SignalSourcesPanel.tsx
@@ -4,7 +4,6 @@ import { useEffect } from 'react'
import { IconArrowLeft } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
-import { SessionAnalysisSetup } from '../../SessionAnalysisSetup'
import { signalSourcesLogic } from '../../signalSourcesLogic'
import { AgentsRoster } from './AgentsRoster'
import { DataSourceSetup } from './DataSourceSetup'
@@ -24,13 +23,12 @@ function BackLink({ onClick }: { onClick: () => void }): JSX.Element {
* the Signal sources setup modal.
*/
export function SignalSourcesPanel(): JSX.Element {
- const { sessionAnalysisSetupOpen, dataSourceSetupSource } = useValues(signalSourcesLogic)
+ const { dataSourceSetupSource } = useValues(signalSourcesLogic)
const {
loadSources,
loadSourceConfigs,
loadVisionScanners,
loadToolDataEvents,
- closeSessionAnalysisSetup,
closeDataSourceSetup,
onDataSourceSetupComplete,
} = useActions(signalSourcesLogic)
@@ -51,14 +49,5 @@ export function SignalSourcesPanel(): JSX.Element {
)
}
- if (sessionAnalysisSetupOpen) {
- return (
- <div className="flex flex-col gap-3">
- <BackLink onClick={closeSessionAnalysisSetup} />
- <SessionAnalysisSetup />
- </div>
- )
- }
-
return <AgentsRoster />
}
diff --git a/products/signals/frontend/inbox/components/config/agentRosterMeta.ts b/products/signals/frontend/inbox/components/config/agentRosterMeta.ts
index 166c04a169bf..4249abc1b51e 100644
--- a/products/signals/frontend/inbox/components/config/agentRosterMeta.ts
+++ b/products/signals/frontend/inbox/components/config/agentRosterMeta.ts
@@ -12,7 +12,6 @@ export type AgentRosterSource =
| 'error_tracking'
| 'conversations'
| 'replay_vision'
- | 'session_replay'
| 'llm_analytics'
| 'analytics'
| 'health_checks'
@@ -128,16 +127,6 @@ export const AGENT_ROSTER_GROUPS: AgentRosterGroup[] = [
docsUrl: urls.health(),
docsLabel: 'Health checks',
},
- {
- source: 'session_replay',
- sourceProduct: SignalSourceProduct.SessionReplay,
- label: 'Session replay',
- watches: 'UX problems in recordings, now covered by Replay Vision',
- detail: 'Runs on a sample of the recordings that match your filters.',
- docsUrl: 'https://posthog.com/docs/session-replay',
- docsLabel: 'Session replay',
- legacy: true,
- },
],
},
{
diff --git a/products/signals/frontend/inbox/components/emptyState/InboxWaitingForWork.tsx b/products/signals/frontend/inbox/components/emptyState/InboxWaitingForWork.tsx
index 82616b5ee192..10bc52b63df9 100644
--- a/products/signals/frontend/inbox/components/emptyState/InboxWaitingForWork.tsx
+++ b/products/signals/frontend/inbox/components/emptyState/InboxWaitingForWork.tsx
@@ -19,6 +19,9 @@ function uniqueEnabledSources(sourceConfigs: SignalSourceConfig[] | null): Signa
!source.enabled ||
(source.source_product === SignalSourceProduct.SignalsScout &&
source.source_type === SignalSourceType.CrossSourceIssue) ||
+ // Retired: the row can outlive the feature until the cleanup migration runs.
+ (source.source_product === SignalSourceProduct.SessionReplay &&
+ source.source_type === SignalSourceType.SessionAnalysisCluster) ||
seenProducts.has(source.source_product)
) {
return false
diff --git a/products/signals/frontend/inbox/components/emptyState/emptyStateCopy.ts b/products/signals/frontend/inbox/components/emptyState/emptyStateCopy.ts
index ff85f51fbee8..f9c82726d637 100644
--- a/products/signals/frontend/inbox/components/emptyState/emptyStateCopy.ts
+++ b/products/signals/frontend/inbox/components/emptyState/emptyStateCopy.ts
@@ -1,7 +1,6 @@
import { SignalSourceType } from '../../types'
const SOURCE_TRIGGER_COPY: Partial<Record<SignalSourceType, string>> = {
- [SignalSourceType.SessionAnalysisCluster]: 'a session shows a repeated problem',
[SignalSourceType.SessionProblem]: 'a session shows a product problem',
[SignalSourceType.Evaluation]: 'an AI evaluation fails',
[SignalSourceType.EvaluationReport]: 'AI evaluation results need attention',
diff --git a/products/signals/frontend/inbox/filterOptions.tsx b/products/signals/frontend/inbox/filterOptions.tsx
index f596e6a8e5c9..ee161e685550 100644
--- a/products/signals/frontend/inbox/filterOptions.tsx
+++ b/products/signals/frontend/inbox/filterOptions.tsx
@@ -14,7 +14,6 @@ import {
IconList,
IconReceipt,
IconRefresh,
- IconRewindPlay,
IconStack,
IconSupport,
} from '@posthog/icons'
@@ -81,7 +80,6 @@ export const INBOX_SORT_OPTIONS: InboxSortOption[] = [
]
export const INBOX_SOURCE_OPTIONS: { value: string; label: string; icon: JSX.Element }[] = [
- { value: 'session_replay', label: 'Session replay', icon: <IconRewindPlay /> },
{ value: 'replay_vision', label: 'Replay vision', icon: <IconEye /> },
{ value: 'error_tracking', label: 'Error tracking', icon: <IconBug /> },
{ value: 'llm_analytics', label: 'AI observability', icon: <IconBrain /> },
diff --git a/products/signals/frontend/inbox/inboxSceneLogic.ts b/products/signals/frontend/inbox/inboxSceneLogic.ts
index dd34e0955abb..ecf05573c68a 100644
--- a/products/signals/frontend/inbox/inboxSceneLogic.ts
+++ b/products/signals/frontend/inbox/inboxSceneLogic.ts
@@ -72,8 +72,6 @@ function consumeScoutTemplateHash(
// How often the Runs tab refetches while it's open, so live runs update in place.
const RUNS_POLL_INTERVAL_MS = 5000
-const SESSION_ANALYSIS_POLL_INTERVAL_MS = 5000
-
// `TaskRunStatus` and `SignalScoutRunStatus` enumerate the same run states. This `Record` keyed on the
// enum makes the relationship exhaustive: a new `TaskRunStatus` value breaks the build here instead of
// silently rendering as 'queued', so the two type vocabularies can't drift unnoticed.
@@ -236,12 +234,10 @@ function flushOpenReport(
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxSceneLogicValues {
- isSessionAnalysisRunning: boolean // signalSourcesLogic
user: UserType | null // userLogic
activeTab: InboxTabKey
breadcrumbs: Breadcrumb[]
isFindingsOpen: boolean
- isRunningSessionAnalysis: boolean
isScratchpadOpen: boolean
isStaff: boolean
scoutTemplateDraft: ScoutCreateInitialValues | null
@@ -300,15 +296,6 @@ export interface inboxSceneLogicActions {
reportDetailScrolled: () => {
value: true
}
- runSessionAnalysis: () => {
- value: true
- }
- runSessionAnalysisFailure: (error: string) => {
- error: string
- }
- runSessionAnalysisSuccess: () => {
- value: true
- }
seedSelectedReport: (report: SignalReport | null) => {
report: SignalReport | null
}
@@ -370,7 +357,7 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
// Mount inboxFiltersLogic with the scene so its URL sync (shareable filter params) applies on
// deep-link load, before the filter bar / list have rendered.
logic: [inboxFiltersLogic],
- values: [signalSourcesLogic, ['isSessionAnalysisRunning'], userLogic, ['user']],
+ values: [userLogic, ['user']],
actions: [signalSourcesLogic, ['loadSourceConfigs']],
})),
@@ -396,9 +383,6 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
// Cross-fleet findings surface: full-width browse/search/filter of every finding the troop
// emitted recently, mutually exclusive with the other full-width views.
setFindingsOpen: (open: boolean) => ({ open }),
- runSessionAnalysis: true,
- runSessionAnalysisSuccess: true,
- runSessionAnalysisFailure: (error: string) => ({ error }),
// The detail pane was scrolled. The logic fires `Inbox report scrolled` once per open; the
// component reports the raw scroll.
reportDetailScrolled: true,
@@ -525,14 +509,6 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
setSelectedScoutSkillName: (_, { findingId }) => findingId,
},
],
- isRunningSessionAnalysis: [
- false,
- {
- runSessionAnalysis: () => true,
- runSessionAnalysisSuccess: () => false,
- runSessionAnalysisFailure: () => false,
- },
- ],
}),
selectors({
@@ -695,24 +671,6 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
}
}
},
- loadSourceConfigsSuccess: () => {
- clearInterval(cache.sessionAnalysisPollInterval)
- if (values.isSessionAnalysisRunning) {
- cache.sessionAnalysisPollInterval = setInterval(() => {
- actions.loadSourceConfigs()
- }, SESSION_ANALYSIS_POLL_INTERVAL_MS)
- }
- },
- runSessionAnalysis: async () => {
- try {
- await api.signalReports.analyzeSessions()
- lemonToast.success('Session analysis completed')
- actions.runSessionAnalysisSuccess()
- } catch (error: any) {
- lemonToast.error(error?.detail || error?.message || 'Failed to run session analysis')
- actions.runSessionAnalysisFailure(error?.detail || error?.message || 'Failed to run session analysis')
- }
- },
})),
events(({ cache }) => ({
@@ -734,7 +692,6 @@ export const inboxSceneLogic = kea<inboxSceneLogicType>([
// The Runs list loads lazily when its tab opens (via the `setActiveTab` listener). There is no
// mount pre-fetch, so an inbox visit that never opens Runs doesn't pay for its two requests.
beforeUnmount: () => {
- clearInterval(cache.sessionAnalysisPollInterval)
// Flush dwell time for a report still open when the scene unmounts (navigated away).
flushOpenReport(cache, 'unmount')
},
diff --git a/products/signals/frontend/inbox/signalSourcesLogic.ts b/products/signals/frontend/inbox/signalSourcesLogic.ts
index fd3d1ff08b38..ba4cec1d4b45 100644
--- a/products/signals/frontend/inbox/signalSourcesLogic.ts
+++ b/products/signals/frontend/inbox/signalSourcesLogic.ts
@@ -13,13 +13,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { productEnablementCreate } from '~/generated/core/api'
import { ExternalDataSourceType } from '~/queries/schema/schema-general'
-import {
- ExternalDataSource,
- ExternalDataSourceSchema,
- RecordingUniversalFilters,
- TeamPublicType,
- TeamType,
-} from '~/types'
+import { ExternalDataSource, ExternalDataSourceSchema, TeamPublicType, TeamType } from '~/types'
import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'
import {
@@ -35,7 +29,7 @@ import { SignalSourceProduct, SignalSourceType } from 'products/signals/frontend
import type { SignalSourceTypeApi } from '../generated/api.schemas'
import type { AgentRosterSource } from './components/config/agentRosterMeta'
import { captureSignalSourceConnected, captureSignalSourceDisabled } from './inboxAnalytics'
-import { SignalSourceConfig, SignalSourceConfigStatus, ToggleSignalSourceParams } from './types'
+import { SignalSourceConfig, ToggleSignalSourceParams } from './types'
/** product_enablement recipe names for tools that back a signal source. */
export type SourceToolEnablement = 'session_replay' | 'error_tracking' | 'conversations'
@@ -237,13 +231,9 @@ export interface signalSourcesLogicValues {
isHealthChecksToggling: boolean
isLinearIssuesToggling: boolean
isPgAnalyzeIssuesToggling: boolean
- isSessionAnalysisRunning: boolean
- isSessionAnalysisToggling: boolean
isZendeskTicketsToggling: boolean
linearIssuesConfig: SignalSourceConfig | null
pgAnalyzeIssuesConfig: SignalSourceConfig | null
- sessionAnalysisConfig: SignalSourceConfig | null
- sessionAnalysisSetupOpen: boolean
sourceConfigs: SignalSourceConfig[] | null
sourceConfigsLoading: boolean
sourcesModalOpen: boolean
@@ -262,15 +252,9 @@ export interface signalSourcesLogicActions {
loadSources: () => {
value: true
} // sourcesDataLogic
- clearSessionAnalysisFilters: () => {
- value: true
- }
closeDataSourceSetup: () => {
value: true
}
- closeSessionAnalysisSetup: () => {
- value: true
- }
closeSourcesModal: () => {
value: true
}
@@ -352,15 +336,9 @@ export interface signalSourcesLogicActions {
openDataSourceSetup: (source: WarehouseBackedSource) => {
source: WarehouseBackedSource
}
- openSessionAnalysisSetup: () => {
- value: true
- }
openSourcesModal: () => {
value: true
}
- saveSessionAnalysisFilters: (filters: RecordingUniversalFilters) => {
- filters: RecordingUniversalFilters
- }
setAllScannerSignals: (enabled: boolean) => {
enabled: boolean
}
@@ -434,9 +412,6 @@ export interface signalSourcesLogicActions {
visionScanners: ReplayScannerApi[]
payload?: any
}
- toggleSessionAnalysis: () => {
- value: true
- }
toggleSignalSource: (params: ToggleSignalSourceParams) => {
params: ToggleSignalSourceParams
}
@@ -455,13 +430,11 @@ export interface signalSourcesLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface signalSourcesLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- sessionAnalysisConfig: (sourceConfigs: SignalSourceConfig[] | null) => SignalSourceConfig | null
githubIssuesConfig: (sourceConfigs: SignalSourceConfig[] | null) => SignalSourceConfig | null
linearIssuesConfig: (sourceConfigs: SignalSourceConfig[] | null) => SignalSourceConfig | null
zendeskTicketsConfig: (sourceConfigs: SignalSourceConfig[] | null) => SignalSourceConfig | null
pgAnalyzeIssuesConfig: (sourceConfigs: SignalSourceConfig[] | null) => SignalSourceConfig | null
conversationsConfig: (sourceConfigs: SignalSourceConfig[] | null) => SignalSourceConfig | null
- isSessionAnalysisToggling: (togglingSourceKeys: Set<string>) => boolean
isConversationsToggling: (togglingSourceKeys: Set<string>) => boolean
isGithubIssuesToggling: (togglingSourceKeys: Set<string>) => boolean
isLinearIssuesToggling: (togglingSourceKeys: Set<string>) => boolean
@@ -483,7 +456,6 @@ export interface signalSourcesLogicMeta {
errorTrackingIsFullyEnabled: (sourceConfigs: SignalSourceConfig[] | null) => boolean
ciSignalsIsFullyEnabled: (ciSignalsConfig: CISignalsConfigApi | null) => boolean
isCiSignalsToggling: (togglingSourceKeys: Set<string>) => boolean
- isSessionAnalysisRunning: (sessionAnalysisConfig: SignalSourceConfig | null) => boolean
hasEmittingScanner: (visionScanners: ReplayScannerApi[] | null) => boolean | null
errorTrackingTypeStates: (sourceConfigs: SignalSourceConfig[] | null) => {
enabled: boolean
@@ -519,9 +491,6 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
actions({
openSourcesModal: true,
closeSourcesModal: true,
- openSessionAnalysisSetup: true,
- closeSessionAnalysisSetup: true,
- toggleSessionAnalysis: true,
initiateDataWarehouseSourceToggle: (source: WarehouseBackedSource) => ({ source }),
startDataWarehouseSourceToggle: (source: WarehouseBackedSource) => ({ source }),
completeDataWarehouseSourceToggle: (source: WarehouseBackedSource) => ({ source }),
@@ -544,8 +513,6 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
toggleAnomalyInvestigation: true,
enableSourceTool: (enablement: SourceToolEnablement) => ({ enablement }),
enableSourceToolComplete: true,
- saveSessionAnalysisFilters: (filters: RecordingUniversalFilters) => ({ filters }),
- clearSessionAnalysisFilters: true,
}),
loaders(({ values }) => ({
@@ -646,14 +613,6 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
closeSourcesModal: () => false,
},
],
- sessionAnalysisSetupOpen: [
- false,
- {
- openSourcesModal: () => false,
- openSessionAnalysisSetup: () => true,
- closeSessionAnalysisSetup: () => false,
- },
- ],
dataSourceSetupSource: [
null as WarehouseBackedSource | null,
{
@@ -678,19 +637,6 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
},
],
sourceConfigs: {
- toggleSessionAnalysis: (state: SignalSourceConfig[] | null) =>
- toggleSourceConfigState(
- state,
- SignalSourceProduct.SessionReplay,
- SignalSourceType.SessionAnalysisCluster
- ),
- setDataWarehouseSourceEnabled: (state: SignalSourceConfig[] | null, { source, enabled }) => {
- const { completion } = WAREHOUSE_SOURCE_SETUP[source]
- if (completion.kind !== 'source_config') {
- return state
- }
- return setSourceConfigState(state, completion.sourceProduct, completion.sourceType, enabled)
- },
toggleHealthChecks: (state: SignalSourceConfig[] | null) =>
toggleSourceConfigState(state, SignalSourceProduct.HealthChecks, SignalSourceType.HealthIssue),
toggleEvalReports: (state: SignalSourceConfig[] | null) =>
@@ -761,15 +707,6 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
}),
selectors({
- sessionAnalysisConfig: [
- (s) => [s.sourceConfigs],
- (sourceConfigs: SignalSourceConfig[] | null): SignalSourceConfig | null =>
- sourceConfigs?.find(
- (c) =>
- c.source_product === SignalSourceProduct.SessionReplay &&
- c.source_type === SignalSourceType.SessionAnalysisCluster
- ) ?? null,
- ],
githubIssuesConfig: [
(s) => [s.sourceConfigs],
(sourceConfigs: SignalSourceConfig[] | null): SignalSourceConfig | null =>
@@ -808,11 +745,6 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
c.source_type === SignalSourceType.Ticket
) ?? null,
],
- isSessionAnalysisToggling: [
- (s) => [s.togglingSourceKeys],
- (keys: Set<string>): boolean =>
- keys.has(`${SignalSourceProduct.SessionReplay}_${SignalSourceType.SessionAnalysisCluster}`),
- ],
isConversationsToggling: [
(s) => [s.togglingSourceKeys],
(keys: Set<string>): boolean => keys.has(`${SignalSourceProduct.Conversations}_${SignalSourceType.Ticket}`),
@@ -922,7 +854,6 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
dataStatus: errorTrackingDataStatus,
},
replay_vision: sessionReplayTool,
- session_replay: sessionReplayTool,
conversations: {
toolName: 'Support',
enabled: team ? !!team.conversations_enabled : null,
@@ -967,10 +898,6 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
(s) => [s.togglingSourceKeys],
(keys: Set<string>): boolean => keys.has('engineering_analytics'),
],
- isSessionAnalysisRunning: [
- (s) => [s.sessionAnalysisConfig],
- (config: SignalSourceConfig | null): boolean => config?.status === SignalSourceConfigStatus.RUNNING,
- ],
// `null` until the scanners load, so callers can tell "no scanner emits" from "not asked yet".
hasEmittingScanner: [
(s) => [s.visionScanners],
@@ -1011,6 +938,12 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
!(
c.source_product === SignalSourceProduct.LlmAnalytics &&
c.source_type === SignalSourceType.Evaluation
+ ) &&
+ // Retired: rows survive until the cleanup migration runs, and counting
+ // them shows a watcher that cannot produce anything.
+ !(
+ c.source_product === SignalSourceProduct.SessionReplay &&
+ c.source_type === SignalSourceType.SessionAnalysisCluster
)
).length ?? 0
return configured + (hasEmittingScanner ? 1 : 0)
@@ -1300,15 +1233,6 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
actions.loadSourceConfigs()
}
},
- toggleSessionAnalysis: () => {
- const config = values.sessionAnalysisConfig
- const desiredEnabled = config?.enabled ?? true
- actions.toggleSignalSource({
- sourceProduct: SignalSourceProduct.SessionReplay,
- sourceType: SignalSourceType.SessionAnalysisCluster,
- enabled: desiredEnabled,
- })
- },
toggleHealthChecks: () => {
// The optimistic reducer flips the config before this listener runs,
// so config.enabled already reflects the desired state.
@@ -1377,47 +1301,6 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
enabled,
})
},
- saveSessionAnalysisFilters: async ({ filters }) => {
- try {
- const existing = values.sessionAnalysisConfig
- if (existing) {
- await api.signalSourceConfigs.update(existing.id, {
- config: { recording_filters: filters },
- enabled: true,
- })
- } else {
- await api.signalSourceConfigs.create({
- source_product: SignalSourceProduct.SessionReplay,
- source_type: SignalSourceType.SessionAnalysisCluster,
- config: { recording_filters: filters },
- enabled: true,
- })
- }
- lemonToast.success('Session analysis filters saved')
- actions.loadSourceConfigs()
- actions.closeSessionAnalysisSetup()
- } catch (error: any) {
- const errorMessage = error?.detail || error?.message || 'Failed to save filters'
- lemonToast.error(errorMessage)
- }
- },
- clearSessionAnalysisFilters: async () => {
- try {
- const existing = values.sessionAnalysisConfig
- if (
- existing &&
- existing.id !==
- `new_${SignalSourceProduct.SessionReplay}_${SignalSourceType.SessionAnalysisCluster}`
- ) {
- await api.signalSourceConfigs.update(existing.id, { config: {}, enabled: true })
- lemonToast.success('Session analysis filters cleared')
- }
- actions.loadSourceConfigs()
- } catch (error: any) {
- const errorMessage = error?.detail || error?.message || 'Failed to clear filters'
- lemonToast.error(errorMessage)
- }
- },
}
}),
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index 0b7f5114c33a..7f023ec77c55 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -270,17 +270,16 @@ tools:
title: Create signal source config
description: >
Create a signal source config for the current project, switching an inbox signal source on. A source ties a
- `source_product` to a `source_type` and an `enabled` flag. Valid `source_product` values: session_replay,
- llm_analytics, github, linear, zendesk, conversations, error_tracking, pganalyze, signals_scout, logs. Valid
- `source_type` values: session_analysis_cluster, evaluation_report, issue, ticket, issue_created,
- issue_reopened, issue_spiking, cross_source_issue, alert_state_change. To surface AI observability
- evaluation report findings in the inbox, create `source_product=llm_analytics`,
- `source_type=evaluation_report` — there is no per-evaluation-run source. The Signals scout source is ON BY
- DEFAULT — scout findings reach the inbox with no config row needed. The only reason to create a
- `source_product=signals_scout`, `source_type=cross_source_issue` row is to OPT OUT: create it with
- `enabled=false` (the per-scout `emit` flag is set separately via `scout-config-update`). There is at most
- one config per (source_product, source_type) per project; if one already exists, update it instead. Enabling
- the session_analysis_cluster source requires the organization to have approved AI data processing.
+ `source_product` to a `source_type` and an `enabled` flag. Valid `source_product` values: llm_analytics,
+ github, linear, zendesk, conversations, error_tracking, pganalyze, signals_scout, logs. Valid `source_type`
+ values: evaluation_report, issue, ticket, issue_created, issue_reopened, issue_spiking, cross_source_issue,
+ alert_state_change. To surface AI observability evaluation report findings in the inbox, create
+ `source_product=llm_analytics`, `source_type=evaluation_report` — there is no per-evaluation-run source. The
+ Signals scout source is ON BY DEFAULT — scout findings reach the inbox with no config row needed. The only
+ reason to create a `source_product=signals_scout`, `source_type=cross_source_issue` row is to OPT OUT:
+ create it with `enabled=false` (the per-scout `emit` flag is set separately via `scout-config-update`).
+ There is at most one config per (source_product, source_type) per project; if one already exists, update it
+ instead.
inbox-source-configs-destroy:
operation: signals_source_configs_destroy
enabled: false
@@ -322,8 +321,7 @@ tools:
description: >
Partially update an existing signal source config by ID — typically to flip its `enabled` flag on or off, or
to adjust its `config`. Only the fields you pass are changed. To turn the Signals scout source off for a
- project, set `enabled=false` on its `signals_scout` / `cross_source_issue` config. Enabling the
- session_analysis_cluster source requires the organization to have approved AI data processing.
+ project, set `enabled=false` on its `signals_scout` / `cross_source_issue` config.
inbox-source-configs-retrieve:
operation: signals_source_configs_retrieve
enabled: true
@@ -350,8 +348,7 @@ tools:
description: >
Replace an existing signal source config by ID (full update — `source_product` and `source_type` are
required; `enabled` and `config` are optional and keep their current values if omitted). Prefer
- `inbox-source-configs-partial-update` when you only need to flip `enabled` or tweak `config`. Enabling the
- session_analysis_cluster source requires the organization to have approved AI data processing.
+ `inbox-source-configs-partial-update` when you only need to flip `enabled` or tweak `config`.
scout-config-create:
operation: signals_scout_config_create
enabled: true
diff --git a/products/slack_app/backend/onboarding.py b/products/slack_app/backend/onboarding.py
index 4acc8f1376c9..f8cc2985a1e4 100644
--- a/products/slack_app/backend/onboarding.py
+++ b/products/slack_app/backend/onboarding.py
@@ -433,9 +433,8 @@ def mark_channel_joined(
_maybe_complete(integration, slack_user_id)
-def apply_sources_selection(integration: Integration, slack_user_id: str, selected_keys: list[str]) -> list[str]:
- """Sync the team's sources to the new selection. Returns the labels of any that couldn't be turned
- on (AI data processing not approved yet)."""
+def apply_sources_selection(integration: Integration, slack_user_id: str, selected_keys: list[str]) -> None:
+ """Sync the team's sources to the new selection."""
from products.signals.backend.facade.api import (
set_sources, # noqa: PLC0415 — keeps the signals stack off the slack import path
)
@@ -443,13 +442,10 @@ def apply_sources_selection(integration: Integration, slack_user_id: str, select
user_id = _resolve_onboarding_user(SlackIntegration(integration), integration, slack_user_id)
if user_id is None:
# Can't tie the clicker to an org member — don't mutate team state.
- return []
- blocked = set_sources(integration.team_id, user_id, selected_keys)
- capture_slack_event(
- integration, EVENT_SOURCE_ENABLED, slack_user_id=slack_user_id, selected=list(selected_keys), blocked=blocked
- )
+ return
+ set_sources(integration.team_id, user_id, selected_keys)
+ capture_slack_event(integration, EVENT_SOURCE_ENABLED, slack_user_id=slack_user_id, selected=list(selected_keys))
_maybe_complete(integration, slack_user_id, user_id)
- return blocked
def approve_ai_data_processing(integration: Integration, slack_user_id: str) -> bool:
diff --git a/products/slack_app/backend/services/inbox_interactivity.py b/products/slack_app/backend/services/inbox_interactivity.py
index e647d70fdf8e..18b9daa747ec 100644
--- a/products/slack_app/backend/services/inbox_interactivity.py
+++ b/products/slack_app/backend/services/inbox_interactivity.py
@@ -170,10 +170,5 @@ def handle_inbox_sources(payload: dict) -> HttpResponse:
None,
)
selected = [o.get("value") for o in (action or {}).get("selected_options", []) if o.get("value")]
- blocked = onboarding.apply_sources_selection(integration, slack_user_id, selected)
- if blocked:
- _post_ephemeral_via_response_url(
- payload.get("response_url", ""),
- f":warning: Approve AI data processing first to turn on *{', '.join(blocked)}*.",
- )
+ onboarding.apply_sources_selection(integration, slack_user_id, selected)
return HttpResponse(status=200)
diff --git a/products/slack_app/backend/tests/test_onboarding.py b/products/slack_app/backend/tests/test_onboarding.py
index 7cb6eaa0e04f..355d1eb67f3e 100644
--- a/products/slack_app/backend/tests/test_onboarding.py
+++ b/products/slack_app/backend/tests/test_onboarding.py
@@ -250,7 +250,7 @@ class TestOnboarding:
el for b in blocks if b["type"] == "actions" for el in b["elements"] if el.get("type") == "checkboxes"
)
# only the two built-in toggle sources, no Linear / GitHub issues
- assert {o["value"] for o in checkboxes["options"]} == {"error_tracking", "session_replay"}
+ assert {o["value"] for o in checkboxes["options"]} == {"error_tracking"}
block = next(b for b in blocks if b.get("block_id", "").startswith(onboarding.INBOX_SOURCES_BLOCK_PREFIX))
assert block["block_id"] == f"{onboarding.INBOX_SOURCES_BLOCK_PREFIX}:{self.integration.id}"
assert "Choose what I watch" in self._all_text(blocks)
@@ -299,84 +299,18 @@ class TestOnboarding:
self._client(mock_webclient_class)
_resolve.return_value = self.user.id
- assert onboarding.apply_sources_selection(self.integration, "U1", ["error_tracking"]) == []
+ onboarding.apply_sources_selection(self.integration, "U1", ["error_tracking"])
assert has_enabled_source(self.team.id) is True
# unticking everything turns them back off (set-semantics)
onboarding.apply_sources_selection(self.integration, "U1", [])
assert has_enabled_source(self.team.id) is False
- @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=None)
- @patch("posthog.models.integration.WebClient")
- def test_apply_sources_blocks_session_replay_without_ai_approval(self, mock_webclient_class, _resolve):
- from products.signals.backend.facade.api import has_enabled_source
-
- self._client(mock_webclient_class)
- _resolve.return_value = self.user.id
- self.organization.is_ai_data_processing_approved = False
- self.organization.save(update_fields=["is_ai_data_processing_approved"])
-
- blocked = onboarding.apply_sources_selection(self.integration, "U1", ["session_replay"])
-
- assert blocked == ["Session replay analysis (legacy)"] # surfaced so the handler can nudge the user
- assert has_enabled_source(self.team.id) is False
-
- @patch("products.slack_app.backend.services.inbox_interactivity._post_ephemeral_via_response_url")
- @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=None)
- @patch("posthog.models.integration.WebClient")
- def test_sources_handler_nudges_when_session_replay_blocked(self, mock_webclient_class, _resolve, mock_ephemeral):
- from products.slack_app.backend.services import inbox_interactivity
-
- self._client(mock_webclient_class)
- _resolve.return_value = self.user.id
- self.organization.is_ai_data_processing_approved = False
- self.organization.save(update_fields=["is_ai_data_processing_approved"])
- payload = {
- "team": {"id": "T12345"},
- "user": {"id": "U1"},
- "response_url": "https://hook",
- "actions": [
- {
- "action_id": onboarding.INBOX_SOURCES_CHECKBOXES_ACTION,
- "block_id": f"{onboarding.INBOX_SOURCES_BLOCK_PREFIX}:{self.integration.id}",
- "selected_options": [{"value": "session_replay"}],
- }
- ],
- }
-
- inbox_interactivity.handle_inbox_sources(payload)
-
- mock_ephemeral.assert_called_once()
- assert "Approve AI data processing" in mock_ephemeral.call_args.args[1]
-
- def test_set_sources_error_tracking_no_approval_needed(self):
- from products.signals.backend.facade.api import has_enabled_source, set_sources
-
- assert has_enabled_source(self.team.id) is False
- assert set_sources(self.team.id, None, ["error_tracking"]) == []
- assert has_enabled_source(self.team.id) is True
-
- def test_set_sources_session_replay_blocked_without_ai_approval(self):
+ def test_set_sources_enables_error_tracking(self):
from products.signals.backend.facade.api import has_enabled_source, set_sources
- self.organization.is_ai_data_processing_approved = False
- self.organization.save(update_fields=["is_ai_data_processing_approved"])
-
- assert set_sources(self.team.id, None, ["session_replay"]) == ["Session replay analysis (legacy)"]
assert has_enabled_source(self.team.id) is False
-
- def test_set_sources_keeps_enabled_source_when_ai_later_revoked(self):
- from products.signals.backend.facade.api import has_enabled_source, set_sources
-
- self.organization.is_ai_data_processing_approved = True
- self.organization.save(update_fields=["is_ai_data_processing_approved"])
- assert set_sources(self.team.id, None, ["session_replay"]) == []
- assert has_enabled_source(self.team.id) is True
-
- # AI revoked: re-submitting the still-ticked selection must leave it enabled, not disable it.
- self.organization.is_ai_data_processing_approved = False
- self.organization.save(update_fields=["is_ai_data_processing_approved"])
- assert set_sources(self.team.id, None, ["session_replay"]) == ["Session replay analysis (legacy)"]
+ set_sources(self.team.id, None, ["error_tracking"])
assert has_enabled_source(self.team.id) is True
@patch("posthog.models.integration.WebClient")
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 185b1911aa47..a3ae754eea2c 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -4847,7 +4847,7 @@
}
},
"inbox-source-configs-create": {
- "description": "Create a signal source config for the current project, switching an inbox signal source on. A source ties a `source_product` to a `source_type` and an `enabled` flag. Valid `source_product` values: session_replay, llm_analytics, github, linear, zendesk, conversations, error_tracking, pganalyze, signals_scout, logs. Valid `source_type` values: session_analysis_cluster, evaluation_report, issue, ticket, issue_created, issue_reopened, issue_spiking, cross_source_issue, alert_state_change. To surface AI observability evaluation report findings in the inbox, create `source_product=llm_analytics`, `source_type=evaluation_report` — there is no per-evaluation-run source. The Signals scout source is ON BY DEFAULT — scout findings reach the inbox with no config row needed. The only reason to create a `source_product=signals_scout`, `source_type=cross_source_issue` row is to OPT OUT: create it with `enabled=false` (the per-scout `emit` flag is set separately via `scout-config-update`). There is at most one config per (source_product, source_type) per project; if one already exists, update it instead. Enabling the session_analysis_cluster source requires the organization to have approved AI data processing.",
+ "description": "Create a signal source config for the current project, switching an inbox signal source on. A source ties a `source_product` to a `source_type` and an `enabled` flag. Valid `source_product` values: llm_analytics, github, linear, zendesk, conversations, error_tracking, pganalyze, signals_scout, logs. Valid `source_type` values: evaluation_report, issue, ticket, issue_created, issue_reopened, issue_spiking, cross_source_issue, alert_state_change. To surface AI observability evaluation report findings in the inbox, create `source_product=llm_analytics`, `source_type=evaluation_report` — there is no per-evaluation-run source. The Signals scout source is ON BY DEFAULT — scout findings reach the inbox with no config row needed. The only reason to create a `source_product=signals_scout`, `source_type=cross_source_issue` row is to OPT OUT: create it with `enabled=false` (the per-scout `emit` flag is set separately via `scout-config-update`). There is at most one config per (source_product, source_type) per project; if one already exists, update it instead.",
"category": "Signals",
"feature": "signals",
"summary": "Create signal source config",
@@ -4875,7 +4875,7 @@
}
},
"inbox-source-configs-partial-update": {
- "description": "Partially update an existing signal source config by ID — typically to flip its `enabled` flag on or off, or to adjust its `config`. Only the fields you pass are changed. To turn the Signals scout source off for a project, set `enabled=false` on its `signals_scout` / `cross_source_issue` config. Enabling the session_analysis_cluster source requires the organization to have approved AI data processing.",
+ "description": "Partially update an existing signal source config by ID — typically to flip its `enabled` flag on or off, or to adjust its `config`. Only the fields you pass are changed. To turn the Signals scout source off for a project, set `enabled=false` on its `signals_scout` / `cross_source_issue` config.",
"category": "Signals",
"feature": "signals",
"summary": "Update signal source config",
@@ -4903,7 +4903,7 @@
}
},
"inbox-source-configs-update": {
- "description": "Replace an existing signal source config by ID (full update — `source_product` and `source_type` are required; `enabled` and `config` are optional and keep their current values if omitted). Prefer `inbox-source-configs-partial-update` when you only need to flip `enabled` or tweak `config`. Enabling the session_analysis_cluster source requires the organization to have approved AI data processing.",
+ "description": "Replace an existing signal source config by ID (full update — `source_product` and `source_type` are required; `enabled` and `config` are optional and keep their current values if omitted). Prefer `inbox-source-configs-partial-update` when you only need to flip `enabled` or tweak `config`.",
"category": "Signals",
"feature": "signals",
"summary": "Replace signal source config",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 8b4f80176623..b79e3f3e0d7c 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5030,7 +5030,7 @@
}
},
"inbox-source-configs-create": {
- "description": "Create a signal source config for the current project, switching an inbox signal source on. A source ties a `source_product` to a `source_type` and an `enabled` flag. Valid `source_product` values: session_replay, llm_analytics, github, linear, zendesk, conversations, error_tracking, pganalyze, signals_scout, logs. Valid `source_type` values: session_analysis_cluster, evaluation_report, issue, ticket, issue_created, issue_reopened, issue_spiking, cross_source_issue, alert_state_change. To surface AI observability evaluation report findings in the inbox, create `source_product=llm_analytics`, `source_type=evaluation_report` — there is no per-evaluation-run source. The Signals scout source is ON BY DEFAULT — scout findings reach the inbox with no config row needed. The only reason to create a `source_product=signals_scout`, `source_type=cross_source_issue` row is to OPT OUT: create it with `enabled=false` (the per-scout `emit` flag is set separately via `scout-config-update`). There is at most one config per (source_product, source_type) per project; if one already exists, update it instead. Enabling the session_analysis_cluster source requires the organization to have approved AI data processing.",
+ "description": "Create a signal source config for the current project, switching an inbox signal source on. A source ties a `source_product` to a `source_type` and an `enabled` flag. Valid `source_product` values: llm_analytics, github, linear, zendesk, conversations, error_tracking, pganalyze, signals_scout, logs. Valid `source_type` values: evaluation_report, issue, ticket, issue_created, issue_reopened, issue_spiking, cross_source_issue, alert_state_change. To surface AI observability evaluation report findings in the inbox, create `source_product=llm_analytics`, `source_type=evaluation_report` — there is no per-evaluation-run source. The Signals scout source is ON BY DEFAULT — scout findings reach the inbox with no config row needed. The only reason to create a `source_product=signals_scout`, `source_type=cross_source_issue` row is to OPT OUT: create it with `enabled=false` (the per-scout `emit` flag is set separately via `scout-config-update`). There is at most one config per (source_product, source_type) per project; if one already exists, update it instead.",
"category": "Signals",
"feature": "signals",
"summary": "Create signal source config",
@@ -5058,7 +5058,7 @@
}
},
"inbox-source-configs-partial-update": {
- "description": "Partially update an existing signal source config by ID — typically to flip its `enabled` flag on or off, or to adjust its `config`. Only the fields you pass are changed. To turn the Signals scout source off for a project, set `enabled=false` on its `signals_scout` / `cross_source_issue` config. Enabling the session_analysis_cluster source requires the organization to have approved AI data processing.",
+ "description": "Partially update an existing signal source config by ID — typically to flip its `enabled` flag on or off, or to adjust its `config`. Only the fields you pass are changed. To turn the Signals scout source off for a project, set `enabled=false` on its `signals_scout` / `cross_source_issue` config.",
"category": "Signals",
"feature": "signals",
"summary": "Update signal source config",
@@ -5086,7 +5086,7 @@
}
},
"inbox-source-configs-update": {
- "description": "Replace an existing signal source config by ID (full update — `source_product` and `source_type` are required; `enabled` and `config` are optional and keep their current values if omitted). Prefer `inbox-source-configs-partial-update` when you only need to flip `enabled` or tweak `config`. Enabling the session_analysis_cluster source requires the organization to have approved AI data processing.",
+ "description": "Replace an existing signal source config by ID (full update — `source_product` and `source_type` are required; `enabled` and `config` are optional and keep their current values if omitted). Prefer `inbox-source-configs-partial-update` when you only need to flip `enabled` or tweak `config`.",
"category": "Signals",
"feature": "signals",
"summary": "Replace signal source config",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8e98d3f16f2d..936586d405fc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -39905,7 +39905,6 @@ export namespace Schemas {
expiry_time?: string | null;
/** External references to third party issues. */
external_references?: SessionRecordingExternalReference[] | null;
- has_summary?: boolean | null;
id: string;
inactive_seconds?: number | null;
keypress_count?: number | null;