:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(subscriptions): code-computed timezone-aware AI report window (#66804)
Vasco de Krijger03259cabf2a3
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex f23bb52e129a..8edd18cf813d 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -128,6 +128,73 @@ class DashboardExportInsightsField(serializers.Field):return data+class AIWindowConfigSerializer(serializers.Serializer):+ mode = serializers.ChoiceField(+ choices=Subscription.AIWindowMode.choices,+ default=Subscription.AIWindowMode.SINCE_LAST_SENT,+ help_text=(+ "What the report analyzes each run:\n"+ "* `since_last_sent` (default) — everything since the previous successful scheduled delivery (gap-free; test/manual sends don't move the anchor)\n"+ "* `last_n_days` — a fixed trailing window of start_days_ago days\n"+ "* `days_ago_range` — the explicit range from start_days_ago to end_days_ago days ago"+ ),+ )+ start_days_ago = serializers.IntegerField(+ required=False,+ allow_null=True,+ min_value=1,+ max_value=365,+ help_text=(+ "Lower bound of the analysis window, in days before the run. Required for 'last_n_days' "+ "(the N) and 'days_ago_range'; ignored for 'since_last_sent'. 1-365."+ ),+ )+ end_days_ago = serializers.IntegerField(+ required=False,+ allow_null=True,+ min_value=0,+ max_value=365,+ help_text=(+ "Upper bound of the analysis window, in days before the run (0 = now). Required for "+ "'days_ago_range' and must be less than start_days_ago; ignored for other modes. 0-365."+ ),+ )++ def to_representation(self, instance: Any) -> dict:+ return Subscription.normalize_ai_window(instance)++ def validate(self, attrs: dict) -> dict:+ mode = attrs.get("mode") or Subscription.AIWindowMode.SINCE_LAST_SENT+ start = attrs.get("start_days_ago")+ end = attrs.get("end_days_ago")++ if mode == Subscription.AIWindowMode.SINCE_LAST_SENT:+ # Day bounds are meaningless here; normalise them away so a later mode switch starts clean.+ attrs["start_days_ago"] = None+ attrs["end_days_ago"] = None+ return attrs+ if not start:+ raise ValidationError({"start_days_ago": [f"Required when mode is '{mode}'."]})+ if mode == Subscription.AIWindowMode.LAST_N_DAYS:+ attrs["end_days_ago"] = None+ return attrs+ # DAYS_AGO_RANGE+ if end is None:+ raise ValidationError({"end_days_ago": [f"Required when mode is '{mode}'."]})+ if end >= start:+ raise ValidationError(+ {"end_days_ago": ["Must be less than start_days_ago (the window must end after it starts)."]}+ )+ return attrs+++class AIPromptConfigSerializer(serializers.Serializer):+ window = AIWindowConfigSerializer(+ required=False,+ help_text="Analysis window for the report. Omitted = 'since_last_sent' (everything since the previous scheduled delivery).",+ )++class SubscriptionSerializer(serializers.ModelSerializer):"""Standard Subscription serializer."""@@ -157,6 +224,13 @@ class SubscriptionSerializer(serializers.ModelSerializer):required=False,help_text="List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6.",)+ ai_prompt_config = AIPromptConfigSerializer(+ required=False,+ help_text=(+ "Configuration for AI report subscriptions (analysis window, future knobs). Only valid "+ "when resource_type is 'ai_prompt'. Replaced wholesale on writes."+ ),+ )insight_short_id = serializers.SerializerMethodField()resource_name = serializers.SerializerMethodField()resource_type = serializers.ChoiceField(@@ -181,6 +255,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):"resource_name","dashboard_export_insights","prompt",+ "ai_prompt_config","target_type","target_value","frequency",@@ -357,6 +432,8 @@ class SubscriptionSerializer(serializers.ModelSerializer):# diagnosable, an unhandled KeyError surfaces as a 500.if validate_for_resource_type is None:raise ValidationError({"resource_type": [f"Unsupported resource_type: {resource_type}."]})+ if resource_type != Subscription.ResourceType.AI_PROMPT and attrs.get("ai_prompt_config"):+ raise ValidationError({"ai_prompt_config": ["AI report settings only apply to AI subscriptions."]})validate_for_resource_type(attrs, existing)self._validate_dashboard_export_subscription(attrs)diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex 1847a079f158..a5b44603ccd0 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -109,6 +109,7 @@ class TestSubscriptionTemporal(APILicensedTest):"resource_name": data["resource_name"],"dashboard_export_insights": [],"prompt": None,+ "ai_prompt_config": {},"target_type": "email","target_value": "[email protected]","frequency": "weekly",@@ -2801,3 +2802,80 @@ class TestAISubscriptionAPI(APILicensedTest):)assert patch_resp.status_code == status.HTTP_400_BAD_REQUEST, patch_resp.json()assert "prompt" in str(patch_resp.json()).lower(), patch_resp.json()++ @parameterized.expand(+ [+ ("last_n_days_missing_start", {"mode": "last_n_days"}, "start_days_ago"),+ ("range_missing_end", {"mode": "days_ago_range", "start_days_ago": 10}, "end_days_ago"),+ (+ "range_end_not_before_start",+ {"mode": "days_ago_range", "start_days_ago": 3, "end_days_ago": 5},+ "end_days_ago",+ ),+ ("start_out_of_bounds", {"mode": "last_n_days", "start_days_ago": 400}, "start_days_ago"),+ ("unknown_mode", {"mode": "calendar_week"}, "mode"),+ ]+ )+ def test_invalid_ai_window_config_is_rejected(+ self, mock_is_cloud, mock_flag, mock_sync, _name, window, expected_error_field+ ):+ self._enable_ai()+ self._mock_temporal(mock_sync)+ response = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._make_ai_payload(ai_prompt_config={"window": window}),+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert expected_error_field in str(response.json()), response.json()++ def test_ai_window_round_trips_and_mode_switch_clears_day_bounds(self, mock_is_cloud, mock_flag, mock_sync):+ # Stale day bounds surviving a switch back to since_last_sent would silently pin the window+ # to old day values if the row is ever read without mode dispatch.+ self._enable_ai()+ self._mock_temporal(mock_sync)+ create_resp = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._make_ai_payload(ai_prompt_config={"window": {"mode": "last_n_days", "start_days_ago": 14}}),+ )+ assert create_resp.status_code == status.HTTP_201_CREATED, create_resp.json()+ created = create_resp.json()+ assert created["ai_prompt_config"]["window"]["mode"] == "last_n_days"+ assert created["ai_prompt_config"]["window"]["start_days_ago"] == 14++ patch_resp = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{created['id']}",+ {"ai_prompt_config": {"window": {"mode": "since_last_sent"}}},+ )+ assert patch_resp.status_code == status.HTTP_200_OK, patch_resp.json()+ window = patch_resp.json()["ai_prompt_config"]["window"]+ assert window["mode"] == "since_last_sent"+ assert window["start_days_ago"] is None++ def test_garbage_ai_prompt_config_still_serializes_on_read(self, mock_is_cloud, mock_flag, mock_sync):+ # The read path routes through the fail-soft normalizer; without it, DRF's+ # IntegerField.to_representation (int(value)) 500s the detail GET and the team's whole+ # subscription list on an out-of-band row. Guards against removing the override.+ self._enable_ai()+ self._mock_temporal(mock_sync)+ create_resp = self.client.post(f"/api/projects/{self.team.id}/subscriptions", self._make_ai_payload())+ sub_id = create_resp.json()["id"]+ Subscription.objects.filter(pk=sub_id).update(+ ai_prompt_config={"window": {"mode": "bogus", "start_days_ago": "seven", "end_days_ago": True}}+ )++ response = self.client.get(f"/api/projects/{self.team.id}/subscriptions/{sub_id}")++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["ai_prompt_config"]["window"] == {+ "mode": "since_last_sent",+ "start_days_ago": None,+ "end_days_ago": None,+ }++ def test_ai_prompt_config_rejected_on_insight_subscription(self, mock_is_cloud, mock_flag, mock_sync):+ self._mock_temporal(mock_sync)+ payload = self._insight_payload()+ payload["ai_prompt_config"] = {"window": {"mode": "last_n_days", "start_days_ago": 7}}+ response = self.client.post(f"/api/projects/{self.team.id}/subscriptions", payload)+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert "ai_prompt_config" in str(response.json()), response.json()diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex aaf0bc16976d..865af99490d6 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1391,7 +1391,7 @@ snapshots:components-playerinspector--with-logs-filter--dark:hash: v1.k794b7964.4a27837802248b94d5c146c18b6962bfc713ce40ec3da10a23d4fc89639cf794.PRcX4NksDqdhgKXU-BTlmrZ4mkRVcQIAlLsj5nbUq9Icomponents-playerinspector--with-logs-filter--light:- hash: v1.k794b7964.6a9ed3bc4517e86c66a587197537ef454d902596d2d78e151de1d26541444ca7.999h6vfa3n6nYUoAkRrCg0mD3k_wWQEf9wxjCbeImZM+ hash: v1.k794b7964.38aa19a7b129b0696518fb42d0dcdfc9e494e26b253983368459b3618a4eda41.Y_UKzWL0hrd0ogvUR7VRKscdpushkyhg2qEMimTjRf4components-playerinspector--with-logs-filter-upsell--dark:hash: v1.k794b7964.5e4afe863e34df7278c0dd092946adfd396ee778f0cd0a41e5e3f5e1771a9601.SBOdVp0jJnn1w2H4fMR-3Vf2ac00QSBFQjsl93AbcYAcomponents-playerinspector--with-logs-filter-upsell--light:diff --git a/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts b/frontend/src/lib/components/Subscriptions/subscriptionLogic.tsindex 73e5189802b7..cbbb6a139c74 100644--- a/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts+++ b/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts@@ -13,6 +13,8 @@ import { getInsightId } from 'scenes/insights/utils'import { ExportedAssetType, ExporterFormat, SubscriptionResourceTypes, SubscriptionType } from '~/types'+import type { AIWindowConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'+import type { subscriptionLogicType } from './subscriptionLogicType'import { subscriptionsLogic } from './subscriptionsLogic'import { AI_PROMPT_MAX_LENGTH, SubscriptionBaseProps, urlForSubscription } from './utils'@@ -34,6 +36,66 @@ function validatePrompt(return undefined}+const AI_WINDOW_MAX_DAYS = 365++function validateAiWindow(subscription: Partial<SubscriptionType>): {+ ai_prompt_config?: { window: { start_days_ago?: any; end_days_ago?: any } }+} {+ if (subscription.resource_type !== SubscriptionResourceTypes.AiPrompt) {+ return {}+ }+ const window = subscription.ai_prompt_config?.window+ const mode = window?.mode ?? 'since_last_sent'+ if (mode === 'since_last_sent') {+ return {}+ }+ const start = window?.start_days_ago+ if (start === null || start === undefined) {+ return { ai_prompt_config: { window: { start_days_ago: 'Set how many days back the report should look' } } }+ }+ if (start < 1 || start > AI_WINDOW_MAX_DAYS) {+ return { ai_prompt_config: { window: { start_days_ago: `Must be between 1 and ${AI_WINDOW_MAX_DAYS} days` } } }+ }+ if (mode === 'last_n_days') {+ return {}+ }+ const end = window?.end_days_ago+ if (end === null || end === undefined) {+ return { ai_prompt_config: { window: { end_days_ago: 'Set where the analyzed range should end' } } }+ }+ if (end < 0 || end > AI_WINDOW_MAX_DAYS) {+ return { ai_prompt_config: { window: { end_days_ago: `Must be between 0 and ${AI_WINDOW_MAX_DAYS} days` } } }+ }+ if (end >= start) {+ return { ai_prompt_config: { window: { end_days_ago: 'Must be closer to now than the start of the range' } } }+ }+ return {}+}++function validateTargetValue(target_type: string, target_value: string | undefined): string | undefined {+ if (!target_value) {+ return target_type === 'email'+ ? 'At least one email is required'+ : target_type === 'slack'+ ? 'A channel is required'+ : 'This field is required.'+ }+ if (target_type === 'email' && !target_value.split(',').every((email) => isEmail(email))) {+ return 'All emails must be valid'+ }+ return undefined+}++function validateDashboardExportInsights(+ subscription: Partial<SubscriptionType>,+ dashboardId: number | undefined+): any {+ if (subscription.resource_type === SubscriptionResourceTypes.AiPrompt || !dashboardId) {+ return undefined+ }+ return subscription.dashboard_export_insights?.length ? undefined : 'Select at least one insight'+}+function subscriptionSaveErrorMessage(error: unknown): string {if (error instanceof ApiError) {const msg = (error.detail || error.message || '').trim()@@ -58,6 +120,7 @@ const NEW_SUBSCRIPTION: Partial<SubscriptionType> = {enabled: true,summary_enabled: false,summary_prompt_guide: '',+ ai_prompt_config: { window: { mode: 'since_last_sent' } },}export interface SubscriptionLogicProps extends SubscriptionBaseProps {@@ -74,7 +137,11 @@ export const subscriptionLogic = kea<subscriptionLogicType>([setPreviewLoading: (loading: boolean) => ({ loading }),setPreviewError: (error: string | null) => ({ error }),setPreviewImageUrl: (url: string | null) => ({ url }),- selectAiExamplePrompt: (prompt: string, label: string) => ({ prompt, label }),+ selectAiExamplePrompt: (prompt: string, label: string, window?: AIWindowConfigApi) => ({+ prompt,+ label,+ window,+ }),}),reducers({@@ -109,7 +176,19 @@ export const subscriptionLogic = kea<subscriptionLogicType>([__default: undefined as unknown as SubscriptionType,loadSubscription: async () => {if (props.id && props.id !== 'new') {- return await api.subscriptions.get(props.id)+ const subscription = await api.subscriptions.get(props.id)+ // Rows created before a window was chosen carry ai_prompt_config: {} — normalise+ // so the analysis window select renders the effective default instead of empty.+ return {+ ...subscription,+ ai_prompt_config: {+ ...subscription.ai_prompt_config,+ window: {+ ...subscription.ai_prompt_config?.window,+ mode: subscription.ai_prompt_config?.window?.mode ?? 'since_last_sent',+ },+ },+ }}return { ...NEW_SUBSCRIPTION }},@@ -125,42 +204,18 @@ export const subscriptionLogic = kea<subscriptionLogicType>([forms(({ props, actions }) => ({subscription: {defaults: { enabled: NEW_SUBSCRIPTION.enabled } as unknown as SubscriptionType,- errors: ({- frequency,- interval,- target_value,- target_type,- title,- start_date,- dashboard_export_insights,- resource_type,- prompt,- }) => ({- frequency: !frequency ? 'You need to set a schedule frequency' : undefined,- title: !title ? 'You need to give your subscription a name' : undefined,- interval: !interval ? 'You need to set an interval' : undefined,- start_date: !start_date ? 'You need to set a delivery time' : undefined,- target_type: !['slack', 'email'].includes(target_type) ? 'Unsupported target type' : undefined,- prompt: validatePrompt(resource_type, prompt),- target_value: !target_value- ? 'This field is required.'- : target_type == 'email'- ? !target_value- ? 'At least one email is required'- : !target_value.split(',').every((email) => isEmail(email))- ? 'All emails must be valid'- : undefined- : target_type == 'slack'- ? !target_value- ? 'A channel is required'- : undefined- : undefined,- dashboard_export_insights:- resource_type !== SubscriptionResourceTypes.AiPrompt &&- props.dashboardId &&- (!dashboard_export_insights || dashboard_export_insights.length === 0)- ? ('Select at least one insight' as any)- : undefined,+ errors: (subscription) => ({+ frequency: !subscription.frequency ? 'You need to set a schedule frequency' : undefined,+ title: !subscription.title ? 'You need to give your subscription a name' : undefined,+ interval: !subscription.interval ? 'You need to set an interval' : undefined,+ start_date: !subscription.start_date ? 'You need to set a delivery time' : undefined,+ target_type: !['slack', 'email'].includes(subscription.target_type)+ ? 'Unsupported target type'+ : undefined,+ prompt: validatePrompt(subscription.resource_type, subscription.prompt),+ ...validateAiWindow(subscription),+ target_value: validateTargetValue(subscription.target_type, subscription.target_value),+ dashboard_export_insights: validateDashboardExportInsights(subscription, props.dashboardId),}),submit: async (subscription, breakpoint) => {const isAi = subscription.resource_type === SubscriptionResourceTypes.AiPrompt@@ -176,6 +231,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([// Only AI subscriptions carry a prompt; a stale one on a non-AI sub (e.g. after// toggling resource_type back) would be rejected by the backend, so drop it.prompt: isAi ? subscription.prompt?.trim() : undefined,+ ai_prompt_config: isAi ? subscription.ai_prompt_config : undefined,}breakpoint()@@ -212,15 +268,24 @@ export const subscriptionLogic = kea<subscriptionLogicType>([},})),- listeners(({ actions, values, props }) => ({+ listeners(({ actions, values, props, selectors }) => ({submitSubscriptionSuccess: ({ subscription }) => {if (subscription?.target_type === 'slack' && subscription.target_value && subscription.integration_id) {recordRecentSlackChannel(subscription.integration_id, slackChannelId(subscription.target_value))}},- selectAiExamplePrompt: ({ prompt, label }) => {+ selectAiExamplePrompt: ({ prompt, label, window }) => {posthog.capture('subscription_ai_example_prompt_selected', { label })actions.setSubscriptionValue('prompt', prompt)+ const currentMode = values.subscription?.ai_prompt_config?.window?.mode ?? 'since_last_sent'+ if (window && currentMode === 'since_last_sent') {+ // Presets that imply a timeframe prefill the analysis window — but only while the+ // window is still the default, so a deliberately-chosen one survives the click.+ // Spread keeps future sibling config keys intact.+ actions.setSubscriptionValues({+ ai_prompt_config: { ...values.subscription?.ai_prompt_config, window },+ })+ }},submitSubscriptionFailure: ({ error }) => {// Kea-forms emits this when client validation fails; fields already show errors.@@ -234,7 +299,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([lemonToast.error(message)},- setSubscriptionValue: ({ name, value }) => {+ setSubscriptionValue: ({ name, value }, _breakpoint, _action, previousState) => {const key = Array.isArray(name) ? name[0] : nameif (key === 'frequency') {if (value === 'daily') {@@ -256,6 +321,18 @@ export const subscriptionLogic = kea<subscriptionLogicType>([integration_id: null,})}++ const path = Array.isArray(name) ? name.join('.') : name+ if (path === 'ai_prompt_config.window.mode') {+ // Reducers run before listeners, so previousState tells a real mode switch (reset the+ // day bounds) apart from a same-mode re-select (keep them).+ const previousConfig = selectors.subscription(previousState)?.ai_prompt_config+ if (value !== previousConfig?.window?.mode) {+ actions.setSubscriptionValues({+ ai_prompt_config: { ...previousConfig, window: { mode: value } },+ })+ }+ }},generatePreview: async (_, breakpoint) => {diff --git a/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx b/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsxindex 0ecbff1e6c9a..84d7d4509967 100644--- a/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx+++ b/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx@@ -36,6 +36,8 @@ import { userLogic } from 'scenes/userLogic'import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'import { AvailableFeature, DashboardType, InsightShortId, SubscriptionResourceTypes, SubscriptionType } from '~/types'+import type { AIWindowConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'+import { InsightSelector } from '../InsightSelector'import { subscriptionCountLogic } from '../subscriptionCountLogic'import { subscriptionLogic } from '../subscriptionLogic'@@ -69,25 +71,26 @@ function AiConsentGateMessage(): JSX.Element {)}-// Concrete starter prompts — each one maps cleanly to a flat HogQL pattern the-// planner already knows (see PLAN_GENERATION_PROMPT reference patterns). Click-// populates the textarea verbatim so users can tweak rather than start cold.-const AI_PROMPT_EXAMPLES: { label: string; prompt: string }[] = [+const AI_PROMPT_EXAMPLES: { label: string; prompt: string; window?: AIWindowConfigApi }[] = [{- label: 'Top events this week',- prompt: 'Top 5 events by volume in the last 7 days, with counts and unique users for each.',+ label: 'Top events',+ prompt: 'Top 5 events by volume, with counts and unique users for each.',+ window: { mode: 'last_n_days', start_days_ago: 7 },},{- label: 'Week-over-week growth',- prompt: 'For the top 10 events by volume, compare this week vs last week and rank by growth rate. Flag any event that more than doubled or halved.',+ label: 'Period-over-period growth',+ prompt: 'For the top 10 events by volume, compare the current period vs the previous one and rank by growth rate. Flag any event that more than doubled or halved.',+ window: { mode: 'last_n_days', start_days_ago: 7 },},{- label: 'Weekly health check',- prompt: 'Weekly health check: total event volume and unique active users in the last 7 days, and how each compares to the previous 7 days.',+ label: 'Health check',+ prompt: 'Health check: total event volume and unique active users, and how each compares to the previous period.',+ window: { mode: 'last_n_days', start_days_ago: 7 },},{label: 'Tracking gaps',- prompt: 'Which events we normally track received no data in the last 7 days? List them so I can catch broken instrumentation.',+ prompt: 'Which events we normally track received no data? List them so I can catch broken instrumentation.',+ window: { mode: 'last_n_days', start_days_ago: 7 },},]@@ -159,14 +162,51 @@ function FreeTierCreateGate(props: EditSubscriptionProps): JSX.Element {return <EditSubscriptionForm {...props} />}+const AI_WINDOW_MODE_OPTIONS = [+ {+ value: 'since_last_sent' as const,+ label: 'Since last report',+ labelInMenu: (+ <div className="flex flex-col">+ <span>Since last report</span>+ <span className="text-xs text-secondary">+ Everything new since the previous scheduled report (no gaps)+ </span>+ </div>+ ),+ },+ {+ value: 'last_n_days' as const,+ label: 'Last N days',+ labelInMenu: (+ <div className="flex flex-col">+ <span>Last N days</span>+ <span className="text-xs text-secondary">A fixed trailing window, e.g. always the last 7 days</span>+ </div>+ ),+ },+ {+ value: 'days_ago_range' as const,+ label: 'Between X and Y days ago',+ labelInMenu: (+ <div className="flex flex-col">+ <span>Between X and Y days ago</span>+ <span className="text-xs text-secondary">An explicit historical range, e.g. 14 to 7 days ago</span>+ </div>+ ),+ },+]+function AiPromptFields({prompt,+ windowMode,showConsentBanner,onSelectExample,}: {prompt?: string | null+ windowMode?: AIWindowConfigApi['mode']showConsentBanner: boolean- onSelectExample: (prompt: string, label: string) => void+ onSelectExample: (prompt: string, label: string, window?: AIWindowConfigApi) => void}): JSX.Element {return (<>@@ -201,7 +241,7 @@ function AiPromptFields({key={example.label}size="xsmall"type="secondary"- onClick={() => onSelectExample(example.prompt, example.label)}+ onClick={() => onSelectExample(example.prompt, example.label, example.window)}>{example.label}</LemonButton>@@ -209,6 +249,58 @@ function AiPromptFields({</div></div>)}+ <LemonField+ name={['ai_prompt_config', 'window', 'mode']}+ label="Analysis window"+ help="The exact time range is computed in your project's timezone each time the report runs."+ >+ <LemonSelect options={AI_WINDOW_MODE_OPTIONS} />+ </LemonField>+ {windowMode === 'last_n_days' && (+ <LemonField name={['ai_prompt_config', 'window', 'start_days_ago']} label="Number of days to analyze">+ {({ value, onChange }) => (+ <div className="flex items-center gap-2">+ <LemonInput+ type="number"+ min={1}+ max={365}+ value={value ?? undefined}+ onChange={(newValue) => onChange(newValue ?? null)}+ className="w-24"+ />+ <span>days back from each run</span>+ </div>+ )}+ </LemonField>+ )}+ {windowMode === 'days_ago_range' && (+ <div className="flex items-start gap-2">+ <LemonField name={['ai_prompt_config', 'window', 'start_days_ago']} label="From (days ago)">+ {({ value, onChange }) => (+ <LemonInput+ type="number"+ min={1}+ max={365}+ value={value ?? undefined}+ onChange={(newValue) => onChange(newValue ?? null)}+ className="w-24"+ />+ )}+ </LemonField>+ <LemonField name={['ai_prompt_config', 'window', 'end_days_ago']} label="To (days ago)">+ {({ value, onChange }) => (+ <LemonInput+ type="number"+ min={0}+ max={365}+ value={value ?? undefined}+ onChange={(newValue) => onChange(newValue ?? null)}+ className="w-24"+ />+ )}+ </LemonField>+ </div>+ )}</>)}@@ -436,6 +528,7 @@ function EditSubscriptionForm({{isAiPrompt ? (<AiPromptFieldsprompt={subscription.prompt}+ windowMode={subscription.ai_prompt_config?.window?.mode}showConsentBanner={aiGate.showAiFormConsentBanner}onSelectExample={logic.actions.selectAiExamplePrompt}/>diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex b5211a466571..d16471c9bb6f 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -79,6 +79,7 @@ import type {} from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'+import type { AIPromptConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'import { CyclotronInputType } from 'products/workflows/frontend/Workflows/hogflows/steps/types'import type { HogFlow } from 'products/workflows/frontend/Workflows/hogflows/types'@@ -5320,6 +5321,7 @@ export interface SubscriptionType {dashboard_export_insights?: number[]integration_id?: number | nullprompt?: string | null+ ai_prompt_config?: AIPromptConfigApi | nulltarget_type: stringtarget_value: stringfrequency: 'daily' | 'weekly' | 'monthly' | 'yearly'diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.pyindex e257aedac59b..95e57ab0a771 100644--- a/posthog/temporal/tests/test_subscriptions_workflows.py+++ b/posthog/temporal/tests/test_subscriptions_workflows.py@@ -2109,7 +2109,10 @@ async def test_generate_ai_report_persists_report_for_delivery(team, user):sub = await _create_ai_subscription(team, user)delivery = await _create_ai_delivery(sub)- with patch(_GENERATE_REPORT, return_value=AiReportResult(markdown="# Report", diagnostics=())):+ with patch(+ _GENERATE_REPORT,+ return_value=AiReportResult(markdown="# Report", diagnostics=(), window_end_utc="2026-06-25T12:00:00+00:00"),+ ):result = await ActivityEnvironment().run(generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id))@@ -2226,7 +2229,12 @@ async def test_generate_ai_report_credit_check_fails_open(team, user):with (patch(_IS_OVER_BUDGET, side_effect=RuntimeError("quota cache unavailable")),- patch(_GENERATE_REPORT, return_value=AiReportResult(markdown="# Report", diagnostics=())) as mock_generate,+ patch(+ _GENERATE_REPORT,+ return_value=AiReportResult(+ markdown="# Report", diagnostics=(), window_end_utc="2026-06-25T12:00:00+00:00"+ ),+ ) as mock_generate,):result = await ActivityEnvironment().run(generate_ai_subscription_report, GenerateAIReportInputs(subscription_id=sub.id, delivery_id=delivery.id)@@ -2430,7 +2438,7 @@ async def test_schedule_ai_subscription_over_credit_budget_lands_skipped(@patch("products.exports.backend.temporal.subscriptions.ai_subscription.activities.send_email_ai_subscription_report")@patch("products.exports.backend.temporal.subscriptions.ai_subscription.activities.build_ai_subscription_report",- return_value=AiReportResult(markdown="# AI Report", diagnostics=()),+ return_value=AiReportResult(markdown="# AI Report", diagnostics=(), window_end_utc="2026-06-25T12:00:00+00:00"),)@freeze_time("2022-02-02T08:55:00.000Z")@pytest.mark.asynciodiff --git a/products/exports/backend/migrations/0004_subscription_ai_prompt_config.py b/products/exports/backend/migrations/0004_subscription_ai_prompt_config.pynew file mode 100644index 000000000000..90dc07f7882e--- /dev/null+++ b/products/exports/backend/migrations/0004_subscription_ai_prompt_config.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-07-07 07:50++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("exports", "0003_alter_subscription_target_type"),+ ]++ operations = [+ migrations.AddField(+ model_name="subscription",+ name="ai_prompt_config",+ field=models.JSONField(blank=True, default=dict),+ ),+ ]diff --git a/products/exports/backend/migrations/0005_subscriptiondelivery_posthog_subdel_sub_fin.py b/products/exports/backend/migrations/0005_subscriptiondelivery_posthog_subdel_sub_fin.pynew file mode 100644index 000000000000..96e27679568b--- /dev/null+++ b/products/exports/backend/migrations/0005_subscriptiondelivery_posthog_subdel_sub_fin.py@@ -0,0 +1,21 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("exports", "0004_subscription_ai_prompt_config"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="subscriptiondelivery",+ index=models.Index(+ fields=["subscription", "status", "-finished_at"],+ name="posthog_subdel_sub_fin",+ ),+ ),+ ]diff --git a/products/exports/backend/migrations/max_migration.txt b/products/exports/backend/migrations/max_migration.txtindex 7e6c11d968bb..6678367b5e9b 100644--- a/products/exports/backend/migrations/max_migration.txt+++ b/products/exports/backend/migrations/max_migration.txt@@ -1 +1 @@-0003_alter_subscription_target_type+0005_subscriptiondelivery_posthog_subdel_sub_findiff --git a/products/exports/backend/models/subscription.py b/products/exports/backend/models/subscription.pyindex 2adbad939c34..078315c8047f 100644--- a/products/exports/backend/models/subscription.py+++ b/products/exports/backend/models/subscription.py@@ -126,6 +126,11 @@ class Subscription(ModelActivityMixin, models.Model):DASHBOARD = "dashboard"AI_PROMPT = "ai_prompt", "AI prompt"+ class AIWindowMode(models.TextChoices):+ SINCE_LAST_SENT = "since_last_sent", "Since last report"+ LAST_N_DAYS = "last_n_days", "Last N days"+ DAYS_AGO_RANGE = "days_ago_range", "Between X and Y days ago"+RRULE_FIELDS = {"frequency", "count", "interval", "start_date", "until_date", "bysetpos", "byweekday"}_FREQ_MAP: dict[str, int] = {@@ -164,6 +169,10 @@ class Subscription(ModelActivityMixin, models.Model):prompt = models.TextField(null=True, blank=True)+ # Source of truth for the shape: ee.api.subscription.AIPromptConfigSerializer (writes) and+ # normalize_ai_window below (reads).+ ai_prompt_config = models.JSONField(default=dict, blank=True)+# Subscription type (email, slack etc.)title = models.CharField(max_length=100, null=True, blank=True)target_type = models.CharField(max_length=10, choices=SubscriptionTarget)@@ -319,6 +328,56 @@ class Subscription(ModelActivityMixin, models.Model):"""Days of history an AI report for this subscription should analyse, derived from its cadence."""return self._AI_REPORT_WINDOW_DAYS.get(self.frequency, self.DEFAULT_AI_REPORT_WINDOW_DAYS)+ AI_WINDOW_MAX_DAYS = 365++ @classmethod+ def normalize_ai_window(cls, window: Any) -> dict:+ """Coerce an arbitrary ai_prompt_config["window"] shape to the serializer's contract —+ the JSONField is untyped at runtime, so a row edited out-of-band can carry anything and+ must degrade to the default window instead of crashing reads or delivery runs. Shared by+ the model readers and the API read path."""++ def day_bound(value: Any, minimum: int) -> Optional[int]:+ if isinstance(value, bool) or not isinstance(value, int):+ return None+ return value if minimum <= value <= cls.AI_WINDOW_MAX_DAYS else None++ raw = window if isinstance(window, dict) else {}+ raw_mode = raw.get("mode")+ mode = raw_mode if raw_mode in cls.AIWindowMode.values else cls.AIWindowMode.SINCE_LAST_SENT+ start = day_bound(raw.get("start_days_ago"), 1)+ end = day_bound(raw.get("end_days_ago"), 0)+ # Mirror AIWindowConfigSerializer's per-mode normalisation, so a garbage value in a field+ # the mode ignores can't affect the fields it uses.+ if mode == cls.AIWindowMode.SINCE_LAST_SENT:+ start, end = None, None+ elif mode == cls.AIWindowMode.LAST_N_DAYS:+ end = None+ elif start is not None and end is not None and end >= start:+ start, end = None, None+ return {+ "mode": mode,+ "start_days_ago": start,+ "end_days_ago": end,+ }++ @property+ def _ai_window_config(self) -> dict:+ config = self.ai_prompt_config if isinstance(self.ai_prompt_config, dict) else {}+ return self.normalize_ai_window(config.get("window"))++ @property+ def ai_window_mode(self) -> str:+ return self._ai_window_config["mode"]++ @property+ def ai_window_start_days_ago(self) -> Optional[int]:+ return self._ai_window_config["start_days_ago"]++ @property+ def ai_window_end_days_ago(self) -> Optional[int]:+ return self._ai_window_config["end_days_ago"]+@propertydef url(self) -> str | None:if not self._has_resource:@@ -405,6 +464,7 @@ class Subscription(ModelActivityMixin, models.Model):"byweekday": self.byweekday,"bysetpos": self.bysetpos,"prompt_length": len(self.prompt or ""),+ "ai_window_mode": self.ai_window_mode if self.resource_type == self.ResourceType.AI_PROMPT else None,}@@ -518,6 +578,8 @@ class SubscriptionDelivery(UUIDModel):indexes = [models.Index(fields=["subscription", "-created_at"], name="posthog_subdel_sub_crtd"),models.Index(fields=["team", "-created_at"], name="posthog_subdel_team_crtd"),+ # Serves the per-run "last successful delivery" anchor lookup.+ models.Index(fields=["subscription", "status", "-finished_at"], name="posthog_subdel_sub_fin"),]ordering = ["-created_at"]diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.pyindex 772860e26ba1..b269b18d24e0 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py@@ -33,6 +33,7 @@ from products.exports.backend.temporal.subscriptions.types import (AI_REPORT_DIAGNOSTICS_KEY,AI_REPORT_PROMPT_SNAPSHOT_KEY,AI_REPORT_SNAPSHOT_KEY,+ AI_REPORT_WINDOW_END_KEY,DeliverSubscriptionInputs,DeliverSubscriptionResult,GenerateAIReportInputs,@@ -108,6 +109,7 @@ async def _persist_ai_report(delivery_id: uuid.UUID, result: AiReportResult, pro**(delivery.content_snapshot or {}),AI_REPORT_SNAPSHOT_KEY: result.markdown,AI_REPORT_DIAGNOSTICS_KEY: [dataclasses.asdict(d) for d in result.diagnostics],+ AI_REPORT_WINDOW_END_KEY: result.window_end_utc,# prompt is None for non-AI subs; "" if cleared — omit either.**({AI_REPORT_PROMPT_SNAPSHOT_KEY: prompt} if prompt else {}),}diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.pyindex f2bc5a30ba12..d03717461744 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py@@ -1,5 +1,5 @@import uuid-from datetime import datetime+from datetime import UTC, datetimefrom urllib.parse import urlencodeimport nh3@@ -8,6 +8,7 @@ from markdown_it import MarkdownItfrom markdown_to_mrkdwn import SlackMarkdownConverterfrom posthog.email import EmailMessage+from posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.markdown_safety import strip_external_links_markdownfrom posthog.helpers.slack_subscription_explore import build_explore_hintfrom posthog.models import Team, User@@ -15,12 +16,17 @@ from posthog.models.integration import Integrationfrom posthog.sync import database_sync_to_asyncfrom posthog.utils import absolute_uri-from products.exports.backend.models.subscription import Subscription, get_unsubscribe_token+from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery, get_unsubscribe_tokenfrom products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import (AiReportResult,generate_ai_report,)-from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import PromptRejectedError+from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import (+ PromptRejectedError,+ ReportWindow,+ compute_report_window,+)+from products.exports.backend.temporal.subscriptions.types import AI_REPORT_WINDOW_END_KEY, SubscriptionTriggerTypefrom ee.tasks.subscriptions.slack_subscriptions import (UTM_TAGS_BASE,@@ -93,13 +99,73 @@ def _split_text_into_chunks(text: str, limit: int = SLACK_MRKDWN_SECTION_LIMIT)return chunks-def _resolve_subscription_actors(subscription: Subscription) -> tuple[Team, User | None]:- # team/created_by are FK relations; reading them may hit the DB, so this runs off the event loop- return subscription.team, subscription.created_by+def _last_scheduled_report_cutoff(subscription: Subscription) -> datetime | None:+ try:+ row = (+ SubscriptionDelivery.objects.filter(+ subscription_id=subscription.id,+ status=SubscriptionDelivery.Status.COMPLETED,+ # Only real scheduled sends move the anchor: a manual "Test delivery" (or an immediate+ # target-change confirmation) right before a run would otherwise shrink its window to+ # near-empty — a test is a preview, not a send.+ trigger_type=SubscriptionTriggerType.SCHEDULED,+ finished_at__isnull=False,+ )+ .order_by("-finished_at")+ .values_list("finished_at", "content_snapshot")+ .first()+ )+ if row is None:+ return None+ finished_at, snapshot = row+ # Prefer the run's persisted window end: anchoring on finished_at leaves the run's own+ # generation+send time uncovered. Rows written before the key existed fall back.+ window_end = (snapshot or {}).get(AI_REPORT_WINDOW_END_KEY)+ if isinstance(window_end, str):+ try:+ return datetime.fromisoformat(window_end)+ except ValueError:+ pass+ return finished_at+ except Exception as exc:+ # A transient DB error on this one lookup shouldn't fail the whole delivery — None falls+ # back to the cadence window (which may re-cover already-sent data, never drop any).+ logger.warning(+ "ai_report.last_delivery_lookup_failed",+ subscription_id=subscription.id,+ team_id=subscription.team_id,+ exc_info=True,+ )+ capture_exception(exc, {"subscription_id": subscription.id, "feature": "ai_subscription"})+ return None+++def _resolve_subscription_context(subscription: Subscription) -> tuple[Team, User | None, ReportWindow]:+ # team/created_by are FK relations and the last-delivery lookup hits the DB; resolving the window+ # here keeps all ORM access (and the timezone math) off the event loop in one sync hop.+ team = subscription.team+ # Day-based window modes don't anchor to delivery history — skip the lookup for them.+ last_scheduled_cutoff = (+ _last_scheduled_report_cutoff(subscription)+ if subscription.ai_window_mode == Subscription.AIWindowMode.SINCE_LAST_SENT+ else None+ )+ window = compute_report_window(+ team=team,+ last_scheduled_cutoff=last_scheduled_cutoff,+ now=datetime.now(tz=UTC),+ window_days=subscription.ai_report_window_days,+ mode=subscription.ai_window_mode,+ start_days_ago=subscription.ai_window_start_days_ago,+ end_days_ago=subscription.ai_window_end_days_ago,+ )+ return team, subscription.created_by, windowasync def build_ai_subscription_report(subscription: Subscription) -> AiReportResult:- team, user = await database_sync_to_async(_resolve_subscription_actors, thread_sensitive=False)(subscription)+ team, user, window = await database_sync_to_async(_resolve_subscription_context, thread_sensitive=False)(+ subscription+ )# created_by is FK SET_NULL; the pipeline requires a non-None userif user is None:raise PromptRejectedError("AI subscription has no creator (created_by deleted); cannot deliver.")@@ -108,7 +174,7 @@ async def build_ai_subscription_report(subscription: Subscription) -> AiReportReteam=team,user=user,prompt=subscription.prompt,- window_days=subscription.ai_report_window_days,+ window=window,trace_correlation_id=subscription.id,)diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py b/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.pyindex 6afb78a28c12..c8d1fda2e23a 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/prompts.py@@ -107,8 +107,16 @@ Output rules:When context lists "Events matching your request", prefer those exact event names — they wereselected for this prompt. For an event's properties, use only the names listed under its"`<event>` properties" line (access as `properties.<name>`); do not invent property names.-- Use the suggested analysis window from context as the default timeframe. Override only if the prompt- explicitly requests a different window.+- The analysis window is fixed and provided in <project_context> as "Analysis window start" and+ "Analysis window end" (concrete timestamps in the project timezone). Filter EVERY query on exactly+ that half-open range — copy the provided literals into a filter of the form+ `timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')`. Do NOT compute the window+ yourself with `now()` / `now() - INTERVAL …` / `today()` — those drift between runs and force fragile+ timezone math. Use the provided literals verbatim, even when the prompt names a relative period+ ("today", "this week"); the bounds already encode it. For sub-windows inside the range (e.g. day-over-day+ within the window), bucket with `toStartOfDay(timestamp)` etc., but keep the outer filter on the literals.+ The one exception is period-over-period growth ("vs last week/yesterday"), which may read back to the+ "Previous-period start" literal `<compare_start>` — see the growth reference pattern below.- Each step's `description` must briefly explain *why* that query is relevant to the prompt.- Keep queries cheap: prefer aggregation over raw selects; cap with LIMIT 50; avoid wildcards on large tables.@@ -119,7 +127,7 @@ are common LLM mistakes that HogQL rejects:- Do NOT nest `WITH … AS (…)` CTEs inside subqueries, FROM clauses, or scalar/IN comparisons.The pattern `WHERE event = (SELECT … FROM (WITH cte AS (…) SELECT …))` fails to parse. If youreach for a CTE, rewrite the whole query as one flat SELECT with conditional aggregation- (see week-over-week example below).+ (`countIf`/`sumIf`/`uniqIf`) — see the reference patterns below.- Do NOT use window functions (`ROW_NUMBER() OVER`, `LAG`, `LEAD`, `RANK`). Use `argMax`/`argMin`or `ORDER BY … LIMIT N` instead.- Do NOT use LATERAL joins, recursive CTEs, `UNNEST`, or `ARRAY JOIN` on a subquery.@@ -129,52 +137,61 @@ are common LLM mistakes that HogQL rejects:null-safe join keys with "Cannot determine join keys", so a JOIN will fail at execution time.(Person, session, and group/account data IS still available without a JOIN — see "Joined dataavailable" below.)-- Date math: `now() - INTERVAL 7 DAY` (unquoted, singular `DAY`/`HOUR`/`WEEK`/`MONTH`).-- Time bucketing: `toStartOfHour(timestamp)`, `toStartOfDay(timestamp)`, `toStartOfWeek(timestamp)`.+- Window filter: use the provided literals — `timestamp >= toDateTime('<start>') AND timestamp <+ toDateTime('<end>')`. Never `now()` / `now() - INTERVAL …` / `today()` for the window.+- Time bucketing (for sub-windows WITHIN the range): `toStartOfHour(timestamp)`,+ `toStartOfDay(timestamp)`, `toStartOfWeek(timestamp)`.- Conditional aggregation: `countIf(cond)`, `uniqIf(field, cond)`, `sumIf(field, cond)`,`avgIf(field, cond)`. Combine these for comparisons across windows in one query.- Top-N within a group: `argMax(field, metric)` for one winner, or `groupArray(field)` +`arraySlice(arraySort(…), 1, N)` for many. Never `ROW_NUMBER() OVER (PARTITION BY …)`.- String literals use single quotes; identifiers are unquoted.-Reference patterns (use as templates):+Reference patterns (use as templates). `<start>` and `<end>` below stand for the exact+"Analysis window start" / "Analysis window end" literals from <project_context> — substitute them+verbatim; never write `now()` or `now() - INTERVAL …`:-Top events in the last 7 days:+Top events across the window:SELECT event, count() AS count, uniq(distinct_id) AS usersFROM events- WHERE timestamp >= now() - INTERVAL 7 DAY+ WHERE timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')GROUP BY eventORDER BY count DESCLIMIT 50-Week-over-week growth in ONE flat query (USE THIS PATTERN INSTEAD OF NESTED CTES):- SELECT- event,- countIf(timestamp >= now() - INTERVAL 7 DAY) AS this_week,- countIf(timestamp >= now() - INTERVAL 14 DAY- AND timestamp < now() - INTERVAL 7 DAY) AS last_week,- (this_week - last_week) / nullIf(last_week, 0) AS growth_rate- FROM events- WHERE timestamp >= now() - INTERVAL 14 DAY- GROUP BY event- HAVING last_week > 0 OR this_week > 0- ORDER BY growth_rate DESC- LIMIT 50-Daily time series for a single event:SELECT toStartOfDay(timestamp) AS day, count() AS count, uniq(distinct_id) AS usersFROM events- WHERE event = '$pageview' AND timestamp >= now() - INTERVAL 14 DAY+ WHERE event = '$pageview' AND timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')GROUP BY dayORDER BY dayHourly distribution to spot spikes:SELECT toStartOfHour(timestamp) AS hour, count() AS countFROM events- WHERE event = '$pageview' AND timestamp >= now() - INTERVAL 7 DAY+ WHERE event = '$pageview' AND timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')GROUP BY hourORDER BY hour+Period-over-period growth (the window vs the equal-length period immediately before it). For a+regular send that's roughly the prior cadence period (about last week for a weekly report, yesterday+for a daily one), but it tracks the window's ACTUAL length — a short re-fire window compares two+short slices, so describe the result as "vs the previous period", not as an exact "week over week".+This is the ONLY case that reads data before `<start>`: filter the wider `[<compare_start>, <end>)`+range and split at `<start>` with conditional aggregation. `<compare_start>` is the "Previous-period+start" literal from <project_context>. Still never `now()`:+ SELECT+ event,+ countIf(timestamp >= toDateTime('<start>')) AS current,+ countIf(timestamp < toDateTime('<start>')) AS previous,+ (current - previous) / nullIf(previous, 0) AS growth_rate+ FROM events+ WHERE timestamp >= toDateTime('<compare_start>') AND timestamp < toDateTime('<end>')+ GROUP BY event+ HAVING previous > 0 OR current > 0+ ORDER BY growth_rate DESC+ LIMIT 50+Events with no data: do NOT write a query for this. The events table only contains events thatfired, so it cannot enumerate zero-data events. The set of events defined in the project but withno data in the window is already provided in <project_context> as "Events defined but with no@@ -184,14 +201,14 @@ Top AND bottom events — a single `ORDER BY … DESC LIMIT n` only returns thewith an ASC tail to read both the most- and least-active events regardless of how many events exist:(SELECT event, count() AS event_count, uniq(distinct_id) AS usersFROM events- WHERE timestamp >= now() - INTERVAL 7 DAY+ WHERE timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')GROUP BY eventORDER BY event_count DESCLIMIT 25)UNION ALL(SELECT event, count() AS event_count, uniq(distinct_id) AS usersFROM events- WHERE timestamp >= now() - INTERVAL 7 DAY+ WHERE timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')GROUP BY eventORDER BY event_count ASCLIMIT 25)@@ -212,13 +229,13 @@ Breakdown by a person property (USE the dotted path, NOT a JOIN):count() AS event_count,uniq(distinct_id) AS usersFROM events- WHERE timestamp >= now() - INTERVAL 7 DAY+ WHERE timestamp >= toDateTime('<start>') AND timestamp < toDateTime('<end>')GROUP BY planORDER BY event_count DESCLIMIT 50First-EVER occurrence of an event per user, landing in the window (e.g. "users whose first ever-'Dashboard created' is today", broken down by a property of that first event). "First ever" needs each+'Dashboard created' falls in the window", broken down by a property of that first event). "First ever" needs eachuser's earliest event across ALL history, so compute it in a FROM-subquery, then filter to thewindow — never approximate it with a flat `countIf`, and never use a JOIN or window function:SELECT@@ -233,7 +250,7 @@ window — never approximate it with a flat `countIf`, and never use a JOIN or wWHERE event = 'Dashboard created'GROUP BY distinct_id)- WHERE first_seen >= toStartOfDay(now()) AND first_seen < toStartOfDay(now() + INTERVAL 1 DAY)+ WHERE first_seen >= toDateTime('<start>') AND first_seen < toDateTime('<end>')GROUP BY templateORDER BY first_time_users DESCLIMIT 50@@ -312,9 +329,12 @@ rewrite MUST follow the same HogQL syntax constraints used by the planner:rewrite it with conditional aggregation (`countIf(cond)`, `uniqIf(field, cond)`, `sumIf(...)`).- No window functions (`ROW_NUMBER`, `LAG`, `LEAD`, `RANK`). No LATERAL joins, recursive CTEs,UNNEST, or ARRAY JOIN on subqueries.-- No JOINs of any kind, including self-joins on `event`. Use conditional aggregation over a wider- time window instead (ClickHouse rejects HogQL's null-safe join keys).-- Date math: `now() - INTERVAL 7 DAY` (unquoted, singular `DAY`/`HOUR`/`WEEK`/`MONTH`).+- No JOINs of any kind, including self-joins on `event`. Use conditional aggregation instead+ (ClickHouse rejects HogQL's null-safe join keys).+- Time window: PRESERVE the original query's `timestamp >= toDateTime('…') AND timestamp <+ toDateTime('…')` bounds verbatim — those are the report's fixed analysis window. Do NOT introduce+ `now()` / `now() - INTERVAL …` / `today()`; if the original already uses them, keep its existing+ literal bounds rather than inventing new ones.- Time bucketing: `toStartOfHour/Day/Week(timestamp)`.- String literals use single quotes; identifiers are unquoted.- Keep it cheap: LIMIT 50.diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.pyindex b675858a35c1..0cf9034ea254 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py@@ -36,6 +36,7 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generaDEFAULT_PLANNER_MODEL,DEFAULT_SYNTHESIS_MODEL,PromptRejectedError,+ ReportWindow,build_enriched_prompt,)@@ -143,6 +144,8 @@ class QueryStepDiagnostic:class AiReportResult:markdown: strdiagnostics: tuple[QueryStepDiagnostic, ...]+ # The window's end as a UTC ISO instant — persisted so the next run can anchor exactly here.+ window_end_utc: strasync def generate_ai_report(@@ -150,7 +153,7 @@ async def generate_ai_report(team: Team,user: Optional[User],prompt: Optional[str],- window_days: int,+ window: ReportWindow,trace_correlation_id: Optional[Union[int, str]] = None,) -> AiReportResult:if user is None:@@ -164,12 +167,10 @@ async def generate_ai_report(team_id=team.id,resource_id=str(trace_correlation_id) if trace_correlation_id is not None else None,),- properties={"window_days": window_days},+ properties={"window_start": window.start_literal, "window_end": window.end_literal},) as slo:try:- spec = await _plan(- team=team, user=user, prompt=prompt, window_days=window_days, trace_id=trace_correlation_id- )+ spec = await _plan(team=team, user=user, prompt=prompt, window=window, trace_id=trace_correlation_id)rendered_results, failed_count, diagnostics = await _execute_plan(spec, team, user, trace_correlation_id)report = await _synthesize(spec, rendered_results, team, user, trace_correlation_id)except PromptRejectedError:@@ -199,18 +200,22 @@ async def generate_ai_report(# deterministic notice (not left to the synthesis LLM) so the recipient gets a clear signal# instead of a confident-looking but empty report.report = _all_queries_failed_notice(total_steps) + report- return AiReportResult(markdown=report, diagnostics=tuple(diagnostics))+ return AiReportResult(+ markdown=report,+ diagnostics=tuple(diagnostics),+ window_end_utc=window.end.astimezone(UTC).isoformat(),+ )async def _plan(- *, team: Team, user: User, prompt: Optional[str], window_days: int, trace_id: Optional[Union[int, str]]+ *, team: Team, user: User, prompt: Optional[str], window: ReportWindow, trace_id: Optional[Union[int, str]]) -> EnrichedPromptSpec:try:return await database_sync_to_async(build_enriched_prompt, thread_sensitive=False)(team=team,user=user,prompt=prompt,- window_days=window_days,+ window=window,trace_correlation_id=trace_id,)except PromptRejectedError:diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py b/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.pyindex a5e1d67156df..89950ead4536 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py@@ -1,5 +1,6 @@from collections.abc import Sequence-from datetime import UTC, datetime, timedelta+from dataclasses import dataclass+from datetime import UTC, datetime, timedelta, tzinfofrom typing import Optional, Unionfrom django.db.models import F, Q@@ -14,6 +15,7 @@ from posthog.models import EventDefinition, EventProperty, PropertyDefinition, Tfrom posthog.models.group_type_mapping import get_group_types_for_projectfrom posthog.security.llm_prompt_sanitization import sanitize_user_text+from products.exports.backend.models.subscription import Subscriptionfrom products.exports.backend.temporal.subscriptions.ai_subscription.prompts import (EVENT_SELECTION_PROMPT,EVENT_SELECTION_PROMPT_NAME,@@ -41,6 +43,10 @@ PROMPT_MAX_LENGTH: int = int(SubscriptionAIPromptMaxLength.model_fields["root"].EVENT_NAMES_SAMPLE_LIMIT = 20# bounds the Postgres scan + context size for the dormant-events listNO_DATA_EVENT_NAMES_LIMIT = 25+# "Dormant" is a fixed, long-horizon signal independent of the report window: an event not seen in this+# many days is worth flagging so the planner doesn't fabricate it, regardless of how short a given run's+# analysis window is.+NO_DATA_LOOKBACK_DAYS = 30PERSON_PROPERTY_NAMES_LIMIT = 30EVENT_NAME_MAX_LENGTH = 120# The top-events list is volume-ranked, so a targeted request ("how are exports doing?") never surfaces@@ -65,6 +71,89 @@ class PromptRejectedError(ValueError):pass+@dataclass(frozen=True)+class ReportWindow:+ """Half-open `[start, end)` analysis bounds for a report run, tz-aware in the team timezone.++ The literals render as project-tz wall clock without an offset: HogQL resolves bare datetime+ literals against the project timezone, which keeps the LLM out of timezone math entirely.+ `compare_start` is the equal-length period immediately before the window, for+ period-over-period queries.+ """++ start: datetime+ end: datetime++ @property+ def start_literal(self) -> str:+ return self.start.strftime("%Y-%m-%d %H:%M:%S")++ @property+ def end_literal(self) -> str:+ return self.end.strftime("%Y-%m-%d %H:%M:%S")++ @property+ def compare_start(self) -> datetime:+ return self.start - (self.end - self.start)++ @property+ def compare_start_literal(self) -> str:+ return self.compare_start.strftime("%Y-%m-%d %H:%M:%S")+++def _in_tz(dt: datetime, tz: tzinfo) -> datetime:+ """Normalise to `tz`. Naive inputs are assumed UTC (Django stores tz-aware UTC datetimes, but+ management commands / tests may hand us a naive value)."""+ return (dt if dt.tzinfo is not None else dt.replace(tzinfo=UTC)).astimezone(tz)+++def compute_report_window(+ team: Team,+ last_scheduled_cutoff: Optional[datetime],+ now: datetime,+ window_days: int,+ mode: str = Subscription.AIWindowMode.SINCE_LAST_SENT,+ start_days_ago: Optional[int] = None,+ end_days_ago: Optional[int] = None,+) -> ReportWindow:+ """Compute the `[start, end)` analysis window for a run. Pure — callers resolve the cutoff+ and `now` and pass them in.++ Mode shapes and defaults are documented on `AIPromptConfigSerializer` (the write-side schema);+ day values arrive pre-validated via `Subscription.normalize_ai_window`. SINCE_LAST_SENT starts+ where the previous scheduled report's coverage ended (gap-free "since last report"), falling+ back to `end - window_days`; a day-based mode missing its values degrades to that same+ fallback, with a warning so the ignored config is diagnosable.+ """+ tz = team.timezone_info+ run_now = _in_tz(now, tz)++ if mode == Subscription.AIWindowMode.LAST_N_DAYS and start_days_ago:+ return ReportWindow(start=run_now - timedelta(days=start_days_ago), end=run_now)++ if mode == Subscription.AIWindowMode.DAYS_AGO_RANGE and start_days_ago:+ return ReportWindow(+ start=run_now - timedelta(days=start_days_ago),+ end=run_now - timedelta(days=end_days_ago or 0),+ )++ if mode != Subscription.AIWindowMode.SINCE_LAST_SENT:+ logger.warning(+ "ai_report.window_config_invalid_fallback",+ team_id=team.pk,+ mode=mode,+ start_days_ago=start_days_ago,+ end_days_ago=end_days_ago,+ )++ end = run_now+ start = _in_tz(last_scheduled_cutoff, tz) if last_scheduled_cutoff is not None else None+ if start is None or start >= end:+ start = end - timedelta(days=window_days)++ return ReportWindow(start=start, end=end)++def sanitize_prompt(raw: str | None) -> str:if not raw or not raw.strip():raise PromptRejectedError("Prompt is empty.")@@ -92,13 +181,14 @@ def _top_event_names(team: Team, limit: int) -> list[str]:return [name for name in sanitized if name]-def _no_data_event_names(team: Team, window_days: int, limit: int) -> list[str]:+def _no_data_event_names(team: Team, limit: int) -> list[str]:# Ground truth for "events with no data" lives in the event-definitions taxonomy, not the events- # table (which only contains events that fired). An event whose `last_seen_at` predates the window —- # or was never seen — had no data in it. `last_seen_at` is maintained on ingestion so it can lag- # slightly, but it's the authoritative taxonomy signal and stops the LLM fabricating a plausible- # list of dormant events from its general knowledge of PostHog event names.- cutoff = datetime.now(tz=UTC) - timedelta(days=window_days)+ # table (which only contains events that fired). An event whose `last_seen_at` predates the dormancy+ # cutoff — or was never seen — is treated as dormant. `last_seen_at` is maintained on ingestion so it+ # can lag slightly, but it's the authoritative taxonomy signal and stops the LLM fabricating a+ # plausible list of dormant events from its general knowledge of PostHog event names. The cutoff is a+ # fixed lookback, decoupled from the report window: dormancy is a property of the event, not the run.+ cutoff = datetime.now(tz=UTC) - timedelta(days=NO_DATA_LOOKBACK_DAYS)names = (EventDefinition.objects.filter(team_id=team.pk).filter(Q(last_seen_at__isnull=True) | Q(last_seen_at__lt=cutoff))@@ -219,21 +309,27 @@ def _event_property_names(team: Team, events: list[str], per_event_limit: int) -return by_event-def build_context_blob(team: Team, window_days: int, relevant_events: Sequence[str] = ()) -> str:+def build_context_blob(team: Team, window: ReportWindow, relevant_events: Sequence[str] = ()) -> str:event_names = _top_event_names(team, EVENT_NAMES_SAMPLE_LIMIT)- now_iso = datetime.now(tz=UTC).isoformat(timespec="seconds")# Team / org names are also user-controlled and end up in the LLM context, so# apply the same sanitization as event names.team_name = sanitize_user_text(team.name, EVENT_NAME_MAX_LENGTH) or "(unnamed)"org_name = sanitize_user_text(team.organization.name, EVENT_NAME_MAX_LENGTH) or "(unnamed)"+ # Exact, code-computed bounds in the project timezone — the planner filters on these literals+ # instead of writing its own `now() - INTERVAL`, so there's no timezone math in HogQL and the+ # window is gap-free run-to-run. Half-open: include `start`, exclude `end`.lines = [f"- Project: {team_name}",f"- Organization: {org_name}",f"- Project timezone: {team.timezone}",- f"- Current UTC time: {now_iso}",- f"- Suggested analysis window: last {window_days} day(s)",+ f"- Analysis window start (inclusive, project timezone): {window.start_literal}",+ f"- Analysis window end (exclusive, project timezone): {window.end_literal}",+ f"- Filter timestamps with: timestamp >= toDateTime('{window.start_literal}') "+ f"AND timestamp < toDateTime('{window.end_literal}')",+ f"- Previous-period start (for period-over-period comparisons only, project timezone): "+ f"{window.compare_start_literal}",]if event_names:lines.append("- Top events: " + ", ".join(event_names))@@ -264,10 +360,11 @@ def build_context_blob(team: Team, window_days: int, relevant_events: Sequence[sif clean_props:lines.append(f" - `{clean}` properties (use properties.<name>): " + ", ".join(clean_props))- no_data_events = _no_data_event_names(team, window_days, NO_DATA_EVENT_NAMES_LIMIT)+ no_data_events = _no_data_event_names(team, NO_DATA_EVENT_NAMES_LIMIT)if no_data_events:lines.append(- f"- Events defined but with no data in the last {window_days} day(s): " + ", ".join(no_data_events)+ f"- Events defined but with no data in the last {NO_DATA_LOOKBACK_DAYS} day(s): "+ + ", ".join(no_data_events))person_properties = _person_property_names(team, PERSON_PROPERTY_NAMES_LIMIT)@@ -324,12 +421,12 @@ def build_enriched_prompt(team: Team,user: User,prompt: Optional[str],- window_days: int,+ window: ReportWindow,trace_correlation_id: Optional[Union[int, str]] = None,) -> EnrichedPromptSpec:cleaned = sanitize_prompt(prompt)relevant_events = _select_relevant_events(team, user, cleaned, trace_correlation_id)- context_blob = build_context_blob(team, window_days, relevant_events=relevant_events)+ context_blob = build_context_blob(team, window, relevant_events=relevant_events)plan = generate_query_plan(cleaned_prompt=cleaned,context_blob=context_blob,diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.pyindex cf86d15ffcca..f81dcd6b48f3 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py@@ -24,6 +24,8 @@ from products.exports.backend.temporal.subscriptions.types import ()from products.product_analytics.backend.models.insight import Insight+_WINDOW_END_UTC = "2026-06-25T12:00:00+00:00"+pytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]@@ -59,6 +61,7 @@ async def test_persist_ai_report_writes_markdown_query_diagnostics_and_prompt(tedelivery.id,AiReportResult(markdown="# Weekly report",+ window_end_utc=_WINDOW_END_UTC,diagnostics=(QueryStepDiagnostic(description="adoption", hogql="SELECT count()", ok=True, error_type=None),QueryStepDiagnostic(@@ -99,7 +102,7 @@ async def test_persist_ai_report_omits_blank_prompt(team, user, prompt) -> None:await _persist_ai_report(delivery.id,- AiReportResult(markdown="# report", diagnostics=()),+ AiReportResult(markdown="# report", diagnostics=(), window_end_utc=_WINDOW_END_UTC),prompt=prompt,)@@ -121,6 +124,7 @@ class TestReportDiagnosticCounts:):result = AiReportResult(markdown="report",+ window_end_utc=_WINDOW_END_UTC,diagnostics=tuple(QueryStepDiagnostic(description=f"step {i}",@@ -136,6 +140,7 @@ class TestReportDiagnosticCounts:def test_distinct_error_types_are_sorted_and_deduped(self):result = AiReportResult(markdown="report",+ window_end_utc=_WINDOW_END_UTC,diagnostics=(QueryStepDiagnostic(description="a", hogql="x", ok=False, error_type="ResolutionError"),QueryStepDiagnostic(description="b", hogql="y", ok=False, error_type="ExposedHogQLError"),@@ -153,6 +158,7 @@ async def test_snapshot_diagnostic_counts_reads_persisted_failure_shape(team, usdelivery.id,AiReportResult(markdown="report",+ window_end_utc=_WINDOW_END_UTC,diagnostics=(QueryStepDiagnostic(description="ok step", hogql="SELECT 1", ok=True, error_type=None),QueryStepDiagnostic(description="bad step", hogql="SELECT bad", ok=False, error_type="ResolutionError"),diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.pyindex d930374b7c81..3f9b4242665a 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py@@ -1,17 +1,22 @@import uuid+from datetime import UTC, datetime, timedeltaimport pytest+from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patchfrom posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES+from products.exports.backend.models.subscription import Subscription, SubscriptionDeliveryfrom products.exports.backend.temporal.subscriptions.ai_subscription.delivery import (SLACK_MRKDWN_SECTION_LIMIT,_build_ai_slack_message,+ _last_scheduled_report_cutoff,_split_text_into_chunks,render_ai_email_html,send_email_ai_subscription_report,)+from products.exports.backend.temporal.subscriptions.types import AI_REPORT_WINDOW_END_KEY, SubscriptionTriggerTypefrom ee.tasks.subscriptions.slack_subscriptions import SlackMessageData@@ -277,3 +282,82 @@ class TestFeedbackFooter:)context = email_message.call_args.kwargs["template_context"]assert context[f"feedback_{feedback}_url"] == _feedback_url(feedback, "email")+++class TestLastSuccessfulDeliveryAnchor(APIBaseTest):+ def _delivery(+ self, trigger_type: str, status: str, finished_at: datetime | None, snapshot: dict | None = None+ ) -> None:+ SubscriptionDelivery.objects.create(+ subscription=self.subscription,+ team=self.team,+ temporal_workflow_id="wf",+ idempotency_key=str(uuid.uuid4()),+ trigger_type=trigger_type,+ target_type="email",+ target_value="[email protected]",+ status=status,+ finished_at=finished_at,+ content_snapshot=snapshot or {},+ )++ def setUp(self) -> None:+ super().setUp()+ self.subscription = Subscription.objects.create(+ team=self.team,+ prompt="p?",+ target_type="email",+ target_value="[email protected]",+ frequency="weekly",+ interval=1,+ start_date=datetime(2026, 1, 1, tzinfo=UTC),+ )++ def test_non_scheduled_deliveries_do_not_move_the_anchor(self) -> None:+ # Only completed SCHEDULED sends move the anchor: a manual "Test delivery" or a target-change+ # confirmation right before a run must not shrink its window to near-empty.+ scheduled_at = datetime(2026, 6, 22, 12, 0, tzinfo=UTC)+ self._delivery(SubscriptionTriggerType.SCHEDULED, SubscriptionDelivery.Status.COMPLETED, scheduled_at)+ self._delivery(+ SubscriptionTriggerType.MANUAL, SubscriptionDelivery.Status.COMPLETED, scheduled_at + timedelta(days=1)+ )+ self._delivery(+ SubscriptionTriggerType.TARGET_CHANGE,+ SubscriptionDelivery.Status.COMPLETED,+ scheduled_at + timedelta(days=2),+ )++ assert _last_scheduled_report_cutoff(self.subscription) == scheduled_at++ def test_anchor_prefers_the_persisted_window_end(self) -> None:+ # finished_at trails the run's window end by the generation+send time; anchoring there leaves+ # that interval uncovered. The persisted window end closes the gap exactly.+ window_end = datetime(2026, 6, 22, 12, 0, tzinfo=UTC)+ finished_at = window_end + timedelta(minutes=3)+ self._delivery(+ SubscriptionTriggerType.SCHEDULED,+ SubscriptionDelivery.Status.COMPLETED,+ finished_at,+ snapshot={AI_REPORT_WINDOW_END_KEY: window_end.isoformat()},+ )++ assert _last_scheduled_report_cutoff(self.subscription) == window_end++ def test_anchor_falls_back_to_finished_at_without_window_end(self) -> None:+ # Rows written before the key existed (or with a garbled value) anchor on finished_at as before.+ finished_at = datetime(2026, 6, 22, 12, 3, tzinfo=UTC)+ self._delivery(+ SubscriptionTriggerType.SCHEDULED,+ SubscriptionDelivery.Status.COMPLETED,+ finished_at,+ snapshot={AI_REPORT_WINDOW_END_KEY: "not-a-date"},+ )++ assert _last_scheduled_report_cutoff(self.subscription) == finished_at++ def test_no_scheduled_delivery_yields_none(self) -> None:+ self._delivery(+ SubscriptionTriggerType.MANUAL, SubscriptionDelivery.Status.COMPLETED, datetime(2026, 6, 22, tzinfo=UTC)+ )++ assert _last_scheduled_report_cutoff(self.subscription) is Nonediff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.pyindex b09c54016b70..c59af03e333b 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py@@ -1,4 +1,5 @@import asyncio+from datetime import UTC, datetime, timedeltaimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch@@ -22,12 +23,21 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.schemas impQueryPlan,QueryPlanStep,)-from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import PromptRejectedError+from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import (+ PromptRejectedError,+ ReportWindow,+)_RP = "products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline"# slo_operation emits through posthoganalytics.capture; patch that boundary to inspect the SLO events._SLO_CAPTURE = "posthog.slo.events.posthoganalytics.capture"+_WINDOW_END = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)+++def _test_window() -> ReportWindow:+ return ReportWindow(start=_WINDOW_END - timedelta(days=1), end=_WINDOW_END)+def _spec(steps: int = 1) -> EnrichedPromptSpec:return EnrichedPromptSpec(@@ -49,20 +59,20 @@ def _slo_completed(capture_mock: MagicMock) -> dict:async def test_user_none_raises_prompt_rejected() -> None:with pytest.raises(PromptRejectedError):- await generate_ai_report(team=MagicMock(), user=None, prompt="x", window_days=7)+ await generate_ai_report(team=MagicMock(), user=None, prompt="x", window=_test_window())@patch(f"{_RP}.build_enriched_prompt", side_effect=PromptRejectedError("empty"))async def test_prompt_rejected_propagates_unwrapped(_mock_bep: object) -> None:# PromptRejectedError must NOT be wrapped as AiReportStageError — callers catch it by type.with pytest.raises(PromptRejectedError):- await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="", window_days=7)+ await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="", window=_test_window())@patch(f"{_RP}.build_enriched_prompt", side_effect=RuntimeError("planner boom"))async def test_planner_failure_wrapped_with_stage(_mock_bep: object) -> None:with pytest.raises(AiReportStageError) as exc_info:- await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window_days=7)+ await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window=_test_window())assert exc_info.value.stage == "planner"@@ -84,7 +94,7 @@ async def test_successful_report_emits_slo_success()mock_chat.return_value.invoke.return_value = MagicMock(content="# Report")- result = await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window_days=7)+ result = await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window=_test_window())assert result.markdown == "# Report"props = _slo_completed(mock_capture)@@ -111,7 +121,7 @@ async def test_degraded_report_still_synthesizes()mock_chat.return_value.invoke.return_value = MagicMock(content="# Weekly report")- result = await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window_days=7)+ result = await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window=_test_window())# Every query failed, so the delivered report leads with the deterministic failure notice# prepended to the synthesis output, not a bare confident-looking report.@@ -144,7 +154,7 @@ async def test_synthesis_failure_wrapped_with_stage(mock_chat.return_value.invoke.side_effect = RuntimeError("synth boom")with pytest.raises(AiReportStageError) as exc_info:- await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window_days=7)+ await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window=_test_window())assert exc_info.value.stage == "synthesis"# A raised stage error burns the SLO error budget.assert _slo_completed(mock_capture)["outcome"] == "failure"@@ -155,7 +165,7 @@ async def test_synthesis_failure_wrapped_with_stage(async def test_prompt_rejected_marks_slo_success_not_failure(_mock_bep: MagicMock, mock_capture: MagicMock) -> None:# A rejected prompt is the input guard working — it must not count against the error budget.with pytest.raises(PromptRejectedError):- await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="", window_days=7)+ await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="", window=_test_window())props = _slo_completed(mock_capture)assert props["outcome"] == "success"assert props["rejected"] is True@@ -235,7 +245,7 @@ async def test_synthesis_prompt_carries_the_failure_marker()mock_chat.return_value.invoke.return_value = MagicMock(content="# Report")- await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window_days=7)+ await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window=_test_window())(messages,) = mock_chat.return_value.invoke.call_args[0]system_message = messages[0][1]diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline_integration.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline_integration.pyindex 0fbd35bc17e9..58196e14e302 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline_integration.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline_integration.py@@ -1,3 +1,5 @@+from datetime import UTC, datetime+from posthog.test.base import (ClickhouseTestMixin,NonAtomicBaseTest,@@ -13,23 +15,30 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.schemas impQueryPlan,QueryPlanStep,)+from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import (+ ReportWindow,+ compute_report_window,+)_RP = "products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline"+# Fixed event time + window anchor so the [start, end) filter brackets the events deterministically+# (no wall-clock race) — the events sit squarely inside the computed window.+_EVENT_TS = datetime(2026, 6, 20, 12, 0, tzinfo=UTC)+_WINDOW_NOW = datetime(2026, 6, 25, 12, 0, tzinfo=UTC)+# Anchor scenario: a prior successful delivery, with one event before it and one after. The window+# start must follow the delivery (not now - window_days), so the pre-delivery event is filtered out+# by the real ClickHouse query while the post-delivery one survives.+_ANCHOR_LAST_DELIVERY = datetime(2026, 6, 22, 12, 0, tzinfo=UTC)+_ANCHOR_NOW = datetime(2026, 6, 25, 12, 0, tzinfo=UTC)+_PRE_ANCHOR_TS = datetime(2026, 6, 20, 12, 0, tzinfo=UTC)+_POST_ANCHOR_TS = datetime(2026, 6, 23, 12, 0, tzinfo=UTC)-class TestAIReportPipelineIntegration(ClickhouseTestMixin, NonAtomicBaseTest):- """Exercises the real plan -> execute -> synthesize wiring: only the two LLM boundaries (planner,- synthesis) are mocked; the planned HogQL runs against the test ClickHouse for real."""-- CLASS_DATA_LEVEL_SETUP = False- def setUp(self) -> None:- super().setUp()- _create_person(team=self.team, distinct_ids=["u1"])- for _ in range(3):- _create_event(team=self.team, event="$pageview", distinct_id="u1")- _create_event(team=self.team, event="signed_up", distinct_id="u1")- flush_persons_and_events()+class _WindowPipelineHelpers:+ """Shared spec/synthesis-capture helpers for the window integration tests. Distinct scenarios live+ in distinct classes rather than methods: NonAtomicBaseTest doesn't roll back Postgres between+ methods in a class, so per-method org/membership creates collide."""def _spec(self, hogql: str) -> EnrichedPromptSpec:return EnrichedPromptSpec(@@ -51,6 +60,28 @@ class TestAIReportPipelineIntegration(ClickhouseTestMixin, NonAtomicBaseTest):mock_chat.return_value.invoke.side_effect = _invokereturn captured++class TestAIReportPipelineIntegration(_WindowPipelineHelpers, ClickhouseTestMixin, NonAtomicBaseTest):+ """Exercises the real plan -> execute -> synthesize wiring: only the two LLM boundaries (planner,+ synthesis) are mocked; the planned HogQL runs against the test ClickHouse for real."""++ CLASS_DATA_LEVEL_SETUP = False++ def setUp(self) -> None:+ super().setUp()+ # Non-UTC project: proves the project-tz wall-clock window literal resolves to the right instant+ # when it flows through HogQL (which anchors a bare datetime to the project timezone).+ self.team.timezone = "Australia/Sydney"+ self.team.save()+ _create_person(team=self.team, distinct_ids=["u1"])+ for _ in range(3):+ _create_event(team=self.team, event="$pageview", distinct_id="u1", timestamp=_EVENT_TS)+ _create_event(team=self.team, event="signed_up", distinct_id="u1", timestamp=_EVENT_TS)+ flush_persons_and_events()++ def _window(self) -> ReportWindow:+ return compute_report_window(self.team, last_scheduled_cutoff=None, now=_WINDOW_NOW, window_days=7)+# Combined into a single test method: NonAtomicBaseTest doesn't roll back Postgres state# between test methods in the same class, so per-method org/membership creates collide.# Three scenarios in one test keep that isolation while covering the happy, degrade, and@@ -60,11 +91,19 @@ class TestAIReportPipelineIntegration(ClickhouseTestMixin, NonAtomicBaseTest):async def test_real_hogql_flows_into_synthesis_and_invalid_hogql_degrades(self, mock_bep: MagicMock, mock_chat: MagicMock) -> None:- # --- happy path: planned HogQL runs for real, results reach synthesis ---- mock_bep.return_value = self._spec("SELECT event, count() AS c FROM events GROUP BY event ORDER BY c DESC")+ # --- happy path: planned HogQL (with the real window-filter literals) runs for real ---+ # The query copies the project-tz wall-clock bounds the way the planner is instructed to. If the+ # literal failed to parse or resolved to the wrong instant, the in-window events would drop out+ # and the assertions below would fail — this is the regression guard for the window filter itself.+ window = self._window()+ mock_bep.return_value = self._spec(+ f"SELECT event, count() AS c FROM events "+ f"WHERE timestamp >= toDateTime('{window.start_literal}') AND timestamp < toDateTime('{window.end_literal}') "+ f"GROUP BY event ORDER BY c DESC"+ )captured = self._capture_synthesis(mock_chat, "# Report")- report = await generate_ai_report(team=self.team, user=self.user, prompt="how many events", window_days=7)+ report = await generate_ai_report(team=self.team, user=self.user, prompt="how many events", window=window)assert report.markdown == "# Report"assert "$pageview" in captured["human"]@@ -76,7 +115,7 @@ class TestAIReportPipelineIntegration(ClickhouseTestMixin, NonAtomicBaseTest):mock_bep.return_value = self._spec("SELECT count() FROM a_table_that_does_not_exist")captured = self._capture_synthesis(mock_chat, "# Degraded report")- report = await generate_ai_report(team=self.team, user=self.user, prompt="x", window_days=7)+ report = await generate_ai_report(team=self.team, user=self.user, prompt="x", window=self._window())assert "Query failed to run" in captured["human"]assert "could not be generated" in report.markdown@@ -87,16 +126,65 @@ class TestAIReportPipelineIntegration(ClickhouseTestMixin, NonAtomicBaseTest):# --- first-ever-per-user subquery (the planner's first-occurrence recipe) runs for real ---# Guards that the FROM-subquery + min/argMin pattern we instruct the planner to emit for# "first-ever per user" is valid, executable HogQL — if it ever stops parsing, this fails- # instead of silently degrading every such metric to a placeholder in production.+ # instead of silently degrading every such metric to a placeholder in production. The outer+ # filter uses the window literals (not now() - INTERVAL) to match what the planner now emits+ # and to keep the assertion deterministic against the fixed-timestamp events.mock_bep.return_value = self._spec("SELECT first_event AS first_event, count() AS first_time_users ""FROM (SELECT distinct_id, min(timestamp) AS first_seen, argMin(event, timestamp) AS first_event ""FROM events GROUP BY distinct_id) "- "WHERE first_seen >= now() - INTERVAL 30 DAY GROUP BY first_event ORDER BY first_time_users DESC LIMIT 50"+ f"WHERE first_seen >= toDateTime('{window.start_literal}') AND first_seen < toDateTime('{window.end_literal}') "+ "GROUP BY first_event ORDER BY first_time_users DESC LIMIT 50")captured = self._capture_synthesis(mock_chat, "# First occurrence report")- report = await generate_ai_report(team=self.team, user=self.user, prompt="first ever", window_days=7)+ report = await generate_ai_report(team=self.team, user=self.user, prompt="first ever", window=window)assert report.markdown == "# First occurrence report"assert report.diagnostics and all(d.ok for d in report.diagnostics)+++class TestAIReportWindowAnchor(_WindowPipelineHelpers, ClickhouseTestMixin, NonAtomicBaseTest):+ """The gap-free "since last send" anchor, proven end-to-end through real ClickHouse: with a prior+ delivery set, the window is [last_delivery, now), so a query copying those literals excludes events+ that fired before the delivery and includes those after. A regression that ignored the anchor (or+ resolved the literal to the wrong instant) would leak the pre-delivery event into the report."""++ CLASS_DATA_LEVEL_SETUP = False++ def setUp(self) -> None:+ super().setUp()+ # Non-UTC project, same as the sibling class: the anchor literal is project-tz wall clock, so+ # this also proves the anchor instant survives the tz round-trip through HogQL.+ self.team.timezone = "Australia/Sydney"+ self.team.save()+ _create_person(team=self.team, distinct_ids=["u1"])+ _create_event(team=self.team, event="pre_delivery", distinct_id="u1", timestamp=_PRE_ANCHOR_TS)+ _create_event(team=self.team, event="post_delivery", distinct_id="u1", timestamp=_POST_ANCHOR_TS)+ flush_persons_and_events()++ @patch(f"{_RP}.MaxChatOpenAI")+ @patch(f"{_RP}.build_enriched_prompt")+ async def test_window_start_anchors_to_last_delivery_and_excludes_earlier_events(+ self, mock_bep: MagicMock, mock_chat: MagicMock+ ) -> None:+ window = compute_report_window(+ self.team, last_scheduled_cutoff=_ANCHOR_LAST_DELIVERY, now=_ANCHOR_NOW, window_days=7+ )+ # Window follows the delivery gap (3 days), not the 7-day cadence — the anchor, not window_days.+ assert window.start == _ANCHOR_LAST_DELIVERY++ mock_bep.return_value = self._spec(+ f"SELECT event, count() AS c FROM events "+ f"WHERE timestamp >= toDateTime('{window.start_literal}') AND timestamp < toDateTime('{window.end_literal}') "+ f"GROUP BY event ORDER BY c DESC"+ )+ captured = self._capture_synthesis(mock_chat, "# Report")++ report = await generate_ai_report(team=self.team, user=self.user, prompt="how many events", window=window)++ assert report.markdown == "# Report"+ # post_delivery fired inside [last_delivery, now); pre_delivery fired before the anchor and the+ # real filter drops it — the proof the anchor is applied and the literal resolves to the right instant.+ assert "post_delivery" in captured["human"]+ assert "pre_delivery" not in captured["human"]diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.pyindex 8b47c0f04c59..620be8128092 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py@@ -1,4 +1,5 @@from datetime import UTC, datetime, timedelta+from zoneinfo import ZoneInfoimport pytestfrom posthog.test.base import APIBaseTest@@ -8,6 +9,7 @@ from parameterized import parameterizedfrom posthog.models import EventDefinition, EventProperty, PropertyDefinition, Team+from products.exports.backend.models.subscription import Subscriptionfrom products.exports.backend.temporal.subscriptions.ai_subscription.schemas import (QueryPlan,QueryPlanStep,@@ -16,12 +18,14 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.schemas impfrom products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import (PROMPT_MAX_LENGTH,PromptRejectedError,+ ReportWindow,_event_property_names,_group_type_labels,_no_data_event_names,_person_property_names,_select_relevant_events,build_context_blob,+ compute_report_window,generate_query_plan,sanitize_prompt,)@@ -29,6 +33,11 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.spec_genera_SG = "products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator"+def _window(days: int = 7) -> ReportWindow:+ end = datetime.now(tz=UTC)+ return ReportWindow(start=end - timedelta(days=days), end=end)++class TestSanitizePrompt:"""`sanitize_prompt` is the public input-validation gate, so its three reject branches and thetag-stripping behaviour are pinned explicitly — a dropped branch would silently admit bad input."""@@ -56,12 +65,14 @@ class TestSanitizePrompt:class TestNoDataEventNames(APIBaseTest):def test_returns_dormant_and_never_seen_events_excluding_recent(self) -> None:+ # Dormancy is a fixed NO_DATA_LOOKBACK_DAYS (30) lookback: seen-recently is excluded, older-than+ # the cutoff or never-seen is included. Guards the filter direction and the fixed-lookback choice.now = datetime.now(tz=UTC)EventDefinition.objects.create(team=self.team, name="recent_event", last_seen_at=now - timedelta(days=1))- EventDefinition.objects.create(team=self.team, name="dormant_event", last_seen_at=now - timedelta(days=30))+ EventDefinition.objects.create(team=self.team, name="dormant_event", last_seen_at=now - timedelta(days=45))EventDefinition.objects.create(team=self.team, name="never_seen_event", last_seen_at=None)- names = _no_data_event_names(self.team, window_days=7, limit=25)+ names = _no_data_event_names(self.team, limit=25)assert "recent_event" not in namesassert "dormant_event" in names@@ -70,9 +81,9 @@ class TestNoDataEventNames(APIBaseTest):def test_respects_limit(self) -> None:now = datetime.now(tz=UTC)for i in range(5):- EventDefinition.objects.create(team=self.team, name=f"dormant_{i}", last_seen_at=now - timedelta(days=30))+ EventDefinition.objects.create(team=self.team, name=f"dormant_{i}", last_seen_at=now - timedelta(days=45))- assert len(_no_data_event_names(self.team, window_days=7, limit=2)) == 2+ assert len(_no_data_event_names(self.team, limit=2)) == 2class TestPersonPropertyNames(APIBaseTest):@@ -189,17 +200,331 @@ class TestEventPropertyNames(APIBaseTest):assert _event_property_names(self.team, ["export created"], per_event_limit=15) == {"export created": ["mine"]}+class TestAIWindowConfigProperties:+ """The ai_prompt_config readers feed compute_report_window on every delivery run, and the column+ is a JSONField a row can carry in any shape — a non-defensive reader would crash the run."""++ @staticmethod+ def _sub(config: object) -> Subscription:+ # In-memory only — the properties are pure reads, but __init__ caches the rrule, so the+ # schedule fields must be valid.+ return Subscription(+ frequency="daily",+ interval=1,+ start_date=datetime(2026, 1, 1, tzinfo=UTC),+ ai_prompt_config=config,+ )++ @parameterized.expand(+ [+ ("empty", {}, "since_last_sent"),+ ("window_not_a_dict", {"window": "hi"}, "since_last_sent"),+ (+ "garbage_values",+ {"window": {"mode": "bogus", "start_days_ago": "seven", "end_days_ago": True}},+ "since_last_sent",+ ),+ ("none_config", None, "since_last_sent"),+ # Out-of-bounds day values must not survive either: a negative start would push the+ # window's start past its end (a future/inverted range handed to the planner). The valid+ # mode reads through; the day bounds are dropped, so compute degrades to the default window.+ (+ "negative_days",+ {"window": {"mode": "last_n_days", "start_days_ago": -5, "end_days_ago": -1}},+ "last_n_days",+ ),+ (+ # An inverted range would hand the planner a window that ends before it starts.+ "inverted_range",+ {"window": {"mode": "days_ago_range", "start_days_ago": 3, "end_days_ago": 5}},+ "days_ago_range",+ ),+ (+ # Equality is inverted too (>= boundary): a zero-length half-open window is empty.+ "range_zero_length",+ {"window": {"mode": "days_ago_range", "start_days_ago": 3, "end_days_ago": 3}},+ "days_ago_range",+ ),+ (+ "over_max_days",+ {"window": {"mode": "last_n_days", "start_days_ago": 9000, "end_days_ago": 400}},+ "last_n_days",+ ),+ ]+ )+ def test_garbage_config_degrades_to_defaults(self, _name: str, config: object, expected_mode: str) -> None:+ sub = self._sub(config)++ assert sub.ai_window_mode == expected_mode+ assert sub.ai_window_start_days_ago is None+ assert sub.ai_window_end_days_ago is None++ def test_valid_config_is_read_through(self) -> None:+ sub = self._sub({"window": {"mode": "days_ago_range", "start_days_ago": 10, "end_days_ago": 3}})++ assert sub.ai_window_mode == Subscription.AIWindowMode.DAYS_AGO_RANGE+ assert sub.ai_window_start_days_ago == 10+ assert sub.ai_window_end_days_ago == 3++ def test_last_n_days_keeps_start_despite_garbage_end(self) -> None:+ # Normalisation is per-mode: a garbage value in a field the mode ignores must not+ # collateral-null the field it uses.+ sub = self._sub({"window": {"mode": "last_n_days", "start_days_ago": 7, "end_days_ago": 10}})++ assert sub.ai_window_mode == Subscription.AIWindowMode.LAST_N_DAYS+ assert sub.ai_window_start_days_ago == 7+ assert sub.ai_window_end_days_ago is None+++class TestComputeReportWindow:+ """`compute_report_window` is the pure core of the timezone-aware window. It's the fix for the+ UTC-anchored, send-time→midnight gap, so its three behaviours are pinned: since-last-delivery+ anchoring, the no-prior-delivery fallback, and timezone correctness (a regression here is the+ exact customer bug)."""++ @staticmethod+ def _team(timezone: str = "UTC") -> Team:+ # In-memory only — compute_report_window is pure and timezone_info just wraps ZoneInfo(tz),+ # so no DB row is needed and the test stays at the cheapest rung.+ return Team(timezone=timezone)++ def test_anchors_start_to_last_scheduled_cutoff(self) -> None:+ now = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)+ last = datetime(2026, 6, 28, 16, 0, tzinfo=UTC)++ window = compute_report_window(+ self._team(),+ last_scheduled_cutoff=last,+ now=now,+ window_days=1,+ mode=Subscription.AIWindowMode.SINCE_LAST_SENT,+ )++ # Gap-free: start is exactly the previous cutoff, not now - window_days (which would be identical+ # here, but the next case proves they diverge when the prior send drifted).+ assert window.start == last.astimezone(ZoneInfo("UTC"))+ assert window.end == now.astimezone(ZoneInfo("UTC"))++ def test_since_last_delivery_can_exceed_window_days(self) -> None:+ # A weekly sub (window_days=7) whose prior delivery was 10 days ago must cover the whole gap,+ # not just the last 7 days — proving start follows the delivery, not the cadence default.+ now = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)+ last = datetime(2026, 6, 19, 16, 0, tzinfo=UTC)++ window = compute_report_window(+ self._team(),+ last_scheduled_cutoff=last,+ now=now,+ window_days=7,+ mode=Subscription.AIWindowMode.SINCE_LAST_SENT,+ )++ assert window.start == last+ assert (window.end - window.start) == timedelta(days=10)++ def test_compare_start_is_the_equal_length_prior_period(self) -> None:+ # Period-over-period reads back exactly the window's own length before start (not window_days),+ # so a weekly report compares to the prior week and a daily one to the prior day. A 10-day gap+ # against a 7-day cadence proves it tracks the real window, not the default; a sign/length+ # regression here silently compares growth against the wrong baseline.+ now = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)+ last = datetime(2026, 6, 19, 16, 0, tzinfo=UTC)++ window = compute_report_window(+ self._team(),+ last_scheduled_cutoff=last,+ now=now,+ window_days=7,+ mode=Subscription.AIWindowMode.SINCE_LAST_SENT,+ )++ assert (window.start - window.compare_start) == (window.end - window.start)+ assert window.compare_start == datetime(2026, 6, 9, 16, 0, tzinfo=UTC)+ assert window.compare_start_literal == "2026-06-09 16:00:00"++ def test_falls_back_to_window_days_without_prior_delivery(self) -> None:+ now = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)++ window = compute_report_window(+ self._team(),+ last_scheduled_cutoff=None,+ now=now,+ window_days=7,+ mode=Subscription.AIWindowMode.SINCE_LAST_SENT,+ )++ assert window.end == now+ assert window.start == now - timedelta(days=7)++ def test_last_n_days_is_a_fixed_trailing_window(self) -> None:+ # The day-based mode must ignore the delivery anchor entirely: a recent send must not shrink+ # the window (that send-timing dependence is what the mode exists to opt out of).+ now = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)+ recent_send = datetime(2026, 6, 29, 15, 0, tzinfo=UTC)++ window = compute_report_window(+ self._team(),+ last_scheduled_cutoff=recent_send,+ now=now,+ window_days=7,+ mode=Subscription.AIWindowMode.LAST_N_DAYS,+ start_days_ago=3,+ )++ assert window.start == now - timedelta(days=3)+ assert window.end == now++ def test_days_ago_range_is_an_explicit_historical_range(self) -> None:+ now = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)++ window = compute_report_window(+ self._team(),+ last_scheduled_cutoff=None,+ now=now,+ window_days=7,+ mode=Subscription.AIWindowMode.DAYS_AGO_RANGE,+ start_days_ago=10,+ end_days_ago=3,+ )++ assert window.start == now - timedelta(days=10)+ assert window.end == now - timedelta(days=3)+ # compare_start stays the equal-length prior period, so period-over-period works here too.+ assert window.compare_start == now - timedelta(days=17)++ def test_range_missing_end_is_treated_as_ending_now(self) -> None:+ # Documented degrade: a DAYS_AGO_RANGE row missing end_days_ago ends at "now" (0 = now per+ # the serializer help text) instead of falling back to a completely different window.+ now = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)++ window = compute_report_window(+ self._team(),+ last_scheduled_cutoff=None,+ now=now,+ window_days=7,+ mode=Subscription.AIWindowMode.DAYS_AGO_RANGE,+ start_days_ago=10,+ end_days_ago=None,+ )++ assert window.start == now - timedelta(days=10)+ assert window.end == now++ @parameterized.expand(+ [+ ("last_n_days_missing_start", Subscription.AIWindowMode.LAST_N_DAYS, None, None),+ ("range_missing_start", Subscription.AIWindowMode.DAYS_AGO_RANGE, None, 3),+ ]+ )+ def test_bad_day_mode_config_falls_back_to_trailing_window(+ self, _name: str, mode: str, start_days_ago: int | None, end_days_ago: int | None+ ) -> None:+ # normalize_ai_window nulls out bad day values, so what reaches compute is a day mode with+ # missing values; it must degrade to the cadence trailing window (anchor is None because+ # delivery.py skips the last-delivery lookup for day-based modes).+ now = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)++ window = compute_report_window(+ self._team(),+ last_scheduled_cutoff=None,+ now=now,+ window_days=7,+ mode=mode,+ start_days_ago=start_days_ago,+ end_days_ago=end_days_ago,+ )++ assert window.start == now - timedelta(days=7)+ assert window.end == now++ @parameterized.expand(+ [+ ("sydney", "Australia/Sydney"),+ ("la", "America/Los_Angeles"),+ ]+ )+ def test_bounds_are_in_team_timezone(self, _name: str, timezone: str) -> None:+ now = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)++ window = compute_report_window(self._team(timezone), last_scheduled_cutoff=None, now=now, window_days=1)++ # Same instant, rendered in the team's tz — utcoffset proves the bound carries the team's+ # offset (the UTC-anchored bug had a zero offset regardless of team timezone).+ assert window.end.tzinfo == ZoneInfo(timezone)+ assert window.end.utcoffset() == now.astimezone(ZoneInfo(timezone)).utcoffset()+ # The literal the planner sees is the project-tz wall clock (no offset), so the LLM never does+ # tz math — HogQL resolves a bare datetime against the project timezone.+ assert window.end_literal == now.astimezone(ZoneInfo(timezone)).strftime("%Y-%m-%d %H:%M:%S")++ def test_clamps_inverted_range_to_fallback(self) -> None:+ # A stale finished_at in the future would invert the range; clamp to the fallback window.+ now = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)+ last = datetime(2026, 6, 30, 16, 0, tzinfo=UTC)++ window = compute_report_window(+ self._team(),+ last_scheduled_cutoff=last,+ now=now,+ window_days=1,+ mode=Subscription.AIWindowMode.SINCE_LAST_SENT,+ )++ assert window.start == now - timedelta(days=1)+ assert window.end == now++ def test_naive_inputs_assumed_utc(self) -> None:+ now = datetime(2026, 6, 29, 16, 0)+ last = datetime(2026, 6, 28, 16, 0)++ window = compute_report_window(self._team("UTC"), last_scheduled_cutoff=last, now=now, window_days=1)++ assert window.start == datetime(2026, 6, 28, 16, 0, tzinfo=UTC)+ assert window.end == datetime(2026, 6, 29, 16, 0, tzinfo=UTC)++class TestContextBlob(APIBaseTest):+ @patch(f"{_SG}.get_group_types_for_project", return_value=[])+ @patch(f"{_SG}._top_event_names", return_value=[])+ def test_states_explicit_window_bounds_in_project_timezone(self, _mock_top: object, _mock_groups: object) -> None:+ # The window-text regression: the blob must hand the planner concrete `[start, end)` literals+ # (so it never writes `now() - INTERVAL`), not the old "last N day(s)" relative phrasing.+ self.team.timezone = "Australia/Sydney"+ self.team.save()+ window = compute_report_window(+ self.team,+ last_scheduled_cutoff=None,+ now=datetime(2026, 6, 29, 16, 0, tzinfo=UTC),+ window_days=1,+ )++ blob = build_context_blob(self.team, window)++ assert f"Analysis window start (inclusive, project timezone): {window.start_literal}" in blob+ assert f"Analysis window end (exclusive, project timezone): {window.end_literal}" in blob+ assert (+ f"timestamp >= toDateTime('{window.start_literal}') AND timestamp < toDateTime('{window.end_literal}')"+ in blob+ )+ # The prior-period anchor for period-over-period growth is injected as its own literal, so the+ # planner never reaches for `now() - INTERVAL` to build a "vs last week" baseline.+ assert (+ f"Previous-period start (for period-over-period comparisons only, project timezone): "+ f"{window.compare_start_literal}" in blob+ )+ # The relative "last N day(s)" phrasing the planner used to do tz math against is gone.+ assert "Suggested analysis window" not in blob+ assert "Current UTC time" not in blob+@patch(f"{_SG}.get_group_types_for_project", return_value=[{"group_type": "organization", "group_type_index": 0}])@patch(f"{_SG}._top_event_names", return_value=[])def test_includes_no_data_person_and_group_lines(self, _mock_top: object, _mock_groups: object) -> None:now = datetime.now(tz=UTC)- EventDefinition.objects.create(team=self.team, name="dormant_event", last_seen_at=now - timedelta(days=30))+ EventDefinition.objects.create(team=self.team, name="dormant_event", last_seen_at=now - timedelta(days=45))PropertyDefinition.objects.create(team=self.team, name="plan", type=PropertyDefinition.Type.PERSON)- blob = build_context_blob(self.team, window_days=7)+ blob = build_context_blob(self.team, _window(7))- assert "Events defined but with no data in the last 7 day(s):" in blob+ assert "Events defined but with no data in the last 30 day(s):" in blobassert "dormant_event" in blobassert "Person properties (reference as person.properties.<name>" in blobassert "plan" in blob@@ -220,7 +545,7 @@ class TestContextBlob(APIBaseTest):for prop in props:EventProperty.objects.create(team=self.team, event="export created", property=prop)- blob = build_context_blob(self.team, window_days=7, relevant_events=["export created"])+ blob = build_context_blob(self.team, _window(7), relevant_events=["export created"])assert "Events matching your request: export created" in blob# properties are listed alphabetically (the _event_property_names ordering)@@ -231,7 +556,7 @@ class TestContextBlob(APIBaseTest):def test_injects_property_schema_for_selected_top_event(self, _mock_top: object, _mock_groups: object) -> None:EventProperty.objects.create(team=self.team, event="$pageview", property="$browser")- blob = build_context_blob(self.team, window_days=7, relevant_events=["$pageview"])+ blob = build_context_blob(self.team, _window(7), relevant_events=["$pageview"])# $pageview is already under "Top events", so it's not repeated in the matched-names line...assert "Events matching your request" not in blob@@ -241,7 +566,7 @@ class TestContextBlob(APIBaseTest):@patch(f"{_SG}.get_group_types_for_project", return_value=[])@patch(f"{_SG}._top_event_names", return_value=[])def test_omits_relevant_section_without_selected_events(self, _mock_top: object, _mock_groups: object) -> None:- blob = build_context_blob(self.team, window_days=7)+ blob = build_context_blob(self.team, _window(7))assert "Events matching your request" not in blobdiff --git a/products/exports/backend/temporal/subscriptions/types.py b/products/exports/backend/temporal/subscriptions/types.pyindex e5ee833d5ab5..c191d7549948 100644--- a/products/exports/backend/temporal/subscriptions/types.py+++ b/products/exports/backend/temporal/subscriptions/types.py@@ -34,6 +34,9 @@ AI_REPORT_PROMPT_SNAPSHOT_KEY = "ai_report_prompt"# Per-step query diagnostics (generated HogQL + failure type) so a degraded report is debuggable# after the fact. Written alongside the markdown; never shipped to recipients.AI_REPORT_DIAGNOSTICS_KEY = "ai_report_diagnostics"+# The analysis window's end for this run, as a UTC ISO instant. The next run anchors its window here+# (exactly gap-free); rows written before this key existed fall back to finished_at.+AI_REPORT_WINDOW_END_KEY = "ai_report_window_end"class SubscriptionTriggerType:diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.tsindex 8618c8271d71..fe14bc25b021 100644--- a/products/subscriptions/frontend/generated/api.schemas.ts+++ b/products/subscriptions/frontend/generated/api.schemas.ts@@ -20,6 +20,50 @@ export const ResourceTypeEnumApi = {AiPrompt: 'ai_prompt',} as const+/**+ * * `since_last_sent` - Since last report+ * * `last_n_days` - Last N days+ * * `days_ago_range` - Between X and Y days ago+ */+export type AIWindowConfigModeEnumApi = (typeof AIWindowConfigModeEnumApi)[keyof typeof AIWindowConfigModeEnumApi]++export const AIWindowConfigModeEnumApi = {+ SinceLastSent: 'since_last_sent',+ LastNDays: 'last_n_days',+ DaysAgoRange: 'days_ago_range',+} as const++export interface AIWindowConfigApi {+ /** What the report analyzes each run:+ * * `since_last_sent` (default) — everything since the previous successful scheduled delivery (gap-free; test/manual sends don't move the anchor)+ * * `last_n_days` — a fixed trailing window of start_days_ago days+ * * `days_ago_range` — the explicit range from start_days_ago to end_days_ago days ago+ *+ * * `since_last_sent` - Since last report+ * * `last_n_days` - Last N days+ * * `days_ago_range` - Between X and Y days ago */+ mode?: AIWindowConfigModeEnumApi+ /**+ * Lower bound of the analysis window, in days before the run. Required for 'last_n_days' (the N) and 'days_ago_range'; ignored for 'since_last_sent'. 1-365.+ * @minimum 1+ * @maximum 365+ * @nullable+ */+ start_days_ago?: number | null+ /**+ * Upper bound of the analysis window, in days before the run (0 = now). Required for 'days_ago_range' and must be less than start_days_ago; ignored for other modes. 0-365.+ * @minimum 0+ * @maximum 365+ * @nullable+ */+ end_days_ago?: number | null+}++export interface AIPromptConfigApi {+ /** Analysis window for the report. Omitted = 'since_last_sent' (everything since the previous scheduled delivery). */+ window?: AIWindowConfigApi+}+/*** * `email` - Email* * `slack` - Slack@@ -155,6 +199,8 @@ export interface SubscriptionApi {* @nullable*/prompt?: string | null+ /** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */+ ai_prompt_config?: AIPromptConfigApi/** Delivery channel: email or slack.** * `email` - Email@@ -299,6 +345,8 @@ export interface PatchedSubscriptionApi {* @nullable*/prompt?: string | null+ /** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */+ ai_prompt_config?: AIPromptConfigApi/** Delivery channel: email or slack.** * `email` - Emaildiff --git a/products/subscriptions/frontend/generated/api.zod.ts b/products/subscriptions/frontend/generated/api.zod.tsindex 4471fba9a89f..c3835fe7bab8 100644--- a/products/subscriptions/frontend/generated/api.zod.ts+++ b/products/subscriptions/frontend/generated/api.zod.ts@@ -9,6 +9,12 @@*/import * as zod from 'zod'+export const subscriptionsCreateBodyAiPromptConfigOneWindowOneModeDefault = `since_last_sent`+export const subscriptionsCreateBodyAiPromptConfigOneWindowOneStartDaysAgoMax = 365++export const subscriptionsCreateBodyAiPromptConfigOneWindowOneEndDaysAgoMin = 0+export const subscriptionsCreateBodyAiPromptConfigOneWindowOneEndDaysAgoMax = 365+export const subscriptionsCreateBodyIntervalMax = 2147483647export const subscriptionsCreateBodyBysetposMin = -2147483648@@ -43,6 +49,45 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod.describe("Free-text prompt that drives the AI-generated report. Required when resource_type is 'ai_prompt'. Max 4000 characters."),+ ai_prompt_config: zod+ .object({+ window: zod+ .object({+ mode: zod+ .enum(['since_last_sent', 'last_n_days', 'days_ago_range'])+ .describe(+ '\* `since_last_sent` - Since last report\n\* `last_n_days` - Last N days\n\* `days_ago_range` - Between X and Y days ago'+ )+ .default(subscriptionsCreateBodyAiPromptConfigOneWindowOneModeDefault)+ .describe(+ "What the report analyzes each run:\n\* `since_last_sent` (default) — everything since the previous successful scheduled delivery (gap-free; test\/manual sends don't move the anchor)\n\* `last_n_days` — a fixed trailing window of start_days_ago days\n\* `days_ago_range` — the explicit range from start_days_ago to end_days_ago days ago\n\n\* `since_last_sent` - Since last report\n\* `last_n_days` - Last N days\n\* `days_ago_range` - Between X and Y days ago"+ ),+ start_days_ago: zod+ .number()+ .min(1)+ .max(subscriptionsCreateBodyAiPromptConfigOneWindowOneStartDaysAgoMax)+ .nullish()+ .describe(+ "Lower bound of the analysis window, in days before the run. Required for 'last_n_days' (the N) and 'days_ago_range'; ignored for 'since_last_sent'. 1-365."+ ),+ end_days_ago: zod+ .number()+ .min(subscriptionsCreateBodyAiPromptConfigOneWindowOneEndDaysAgoMin)+ .max(subscriptionsCreateBodyAiPromptConfigOneWindowOneEndDaysAgoMax)+ .nullish()+ .describe(+ "Upper bound of the analysis window, in days before the run (0 = now). Required for 'days_ago_range' and must be less than start_days_ago; ignored for other modes. 0-365."+ ),+ })+ .optional()+ .describe(+ "Analysis window for the report. Omitted = 'since_last_sent' (everything since the previous scheduled delivery)."+ ),+ })+ .optional()+ .describe(+ "Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."+ ),target_type: zod.enum(['email', 'slack']).describe('\* `email` - Email\n\* `slack` - Slack')@@ -128,6 +173,12 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod}).describe('Standard Subscription serializer.')+export const subscriptionsUpdateBodyAiPromptConfigOneWindowOneModeDefault = `since_last_sent`+export const subscriptionsUpdateBodyAiPromptConfigOneWindowOneStartDaysAgoMax = 365++export const subscriptionsUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMin = 0+export const subscriptionsUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMax = 365+export const subscriptionsUpdateBodyIntervalMax = 2147483647export const subscriptionsUpdateBodyBysetposMin = -2147483648@@ -162,6 +213,45 @@ export const SubscriptionsUpdateBody = /* @__PURE__ */ zod.describe("Free-text prompt that drives the AI-generated report. Required when resource_type is 'ai_prompt'. Max 4000 characters."),+ ai_prompt_config: zod+ .object({+ window: zod+ .object({+ mode: zod+ .enum(['since_last_sent', 'last_n_days', 'days_ago_range'])+ .describe(+ '\* `since_last_sent` - Since last report\n\* `last_n_days` - Last N days\n\* `days_ago_range` - Between X and Y days ago'+ )+ .default(subscriptionsUpdateBodyAiPromptConfigOneWindowOneModeDefault)+ .describe(+ "What the report analyzes each run:\n\* `since_last_sent` (default) — everything since the previous successful scheduled delivery (gap-free; test\/manual sends don't move the anchor)\n\* `last_n_days` — a fixed trailing window of start_days_ago days\n\* `days_ago_range` — the explicit range from start_days_ago to end_days_ago days ago\n\n\* `since_last_sent` - Since last report\n\* `last_n_days` - Last N days\n\* `days_ago_range` - Between X and Y days ago"+ ),+ start_days_ago: zod+ .number()+ .min(1)+ .max(subscriptionsUpdateBodyAiPromptConfigOneWindowOneStartDaysAgoMax)+ .nullish()+ .describe(+ "Lower bound of the analysis window, in days before the run. Required for 'last_n_days' (the N) and 'days_ago_range'; ignored for 'since_last_sent'. 1-365."+ ),+ end_days_ago: zod+ .number()+ .min(subscriptionsUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMin)+ .max(subscriptionsUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMax)+ .nullish()+ .describe(+ "Upper bound of the analysis window, in days before the run (0 = now). Required for 'days_ago_range' and must be less than start_days_ago; ignored for other modes. 0-365."+ ),+ })+ .optional()+ .describe(+ "Analysis window for the report. Omitted = 'since_last_sent' (everything since the previous scheduled delivery)."+ ),+ })+ .optional()+ .describe(+ "Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."+ ),target_type: zod.enum(['email', 'slack']).describe('\* `email` - Email\n\* `slack` - Slack')@@ -247,6 +337,12 @@ export const SubscriptionsUpdateBody = /* @__PURE__ */ zod}).describe('Standard Subscription serializer.')+export const subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneModeDefault = `since_last_sent`+export const subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneStartDaysAgoMax = 365++export const subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMin = 0+export const subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMax = 365+export const subscriptionsPartialUpdateBodyIntervalMax = 2147483647export const subscriptionsPartialUpdateBodyBysetposMin = -2147483648@@ -281,6 +377,45 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod.describe("Free-text prompt that drives the AI-generated report. Required when resource_type is 'ai_prompt'. Max 4000 characters."),+ ai_prompt_config: zod+ .object({+ window: zod+ .object({+ mode: zod+ .enum(['since_last_sent', 'last_n_days', 'days_ago_range'])+ .describe(+ '\* `since_last_sent` - Since last report\n\* `last_n_days` - Last N days\n\* `days_ago_range` - Between X and Y days ago'+ )+ .default(subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneModeDefault)+ .describe(+ "What the report analyzes each run:\n\* `since_last_sent` (default) — everything since the previous successful scheduled delivery (gap-free; test\/manual sends don't move the anchor)\n\* `last_n_days` — a fixed trailing window of start_days_ago days\n\* `days_ago_range` — the explicit range from start_days_ago to end_days_ago days ago\n\n\* `since_last_sent` - Since last report\n\* `last_n_days` - Last N days\n\* `days_ago_range` - Between X and Y days ago"+ ),+ start_days_ago: zod+ .number()+ .min(1)+ .max(subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneStartDaysAgoMax)+ .nullish()+ .describe(+ "Lower bound of the analysis window, in days before the run. Required for 'last_n_days' (the N) and 'days_ago_range'; ignored for 'since_last_sent'. 1-365."+ ),+ end_days_ago: zod+ .number()+ .min(subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMin)+ .max(subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMax)+ .nullish()+ .describe(+ "Upper bound of the analysis window, in days before the run (0 = now). Required for 'days_ago_range' and must be less than start_days_ago; ignored for other modes. 0-365."+ ),+ })+ .optional()+ .describe(+ "Analysis window for the report. Omitted = 'since_last_sent' (everything since the previous scheduled delivery)."+ ),+ })+ .optional()+ .describe(+ "Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."+ ),target_type: zod.enum(['email', 'slack']).describe('\* `email` - Email\n\* `slack` - Slack')diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cf628f7abdb5..0ef9500f4826 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -31,6 +31,51 @@ export namespace Schemas {AiGenerationClusters: '$ai_generation_clusters',} as const;+ /**+ * * `since_last_sent` - Since last report+ * * `last_n_days` - Last N days+ * * `days_ago_range` - Between X and Y days ago+ */+ export type AIWindowConfigModeEnum = typeof AIWindowConfigModeEnum[keyof typeof AIWindowConfigModeEnum];+++ export const AIWindowConfigModeEnum = {+ SinceLastSent: 'since_last_sent',+ LastNDays: 'last_n_days',+ DaysAgoRange: 'days_ago_range',+ } as const;++ export interface AIWindowConfig {+ /** What the report analyzes each run:+ * * `since_last_sent` (default) — everything since the previous successful scheduled delivery (gap-free; test/manual sends don't move the anchor)+ * * `last_n_days` — a fixed trailing window of start_days_ago days+ * * `days_ago_range` — the explicit range from start_days_ago to end_days_ago days ago+ *+ * * `since_last_sent` - Since last report+ * * `last_n_days` - Last N days+ * * `days_ago_range` - Between X and Y days ago */+ mode?: AIWindowConfigModeEnum;+ /**+ * Lower bound of the analysis window, in days before the run. Required for 'last_n_days' (the N) and 'days_ago_range'; ignored for 'since_last_sent'. 1-365.+ * @minimum 1+ * @maximum 365+ * @nullable+ */+ start_days_ago?: number | null;+ /**+ * Upper bound of the analysis window, in days before the run (0 = now). Required for 'days_ago_range' and must be less than start_days_ago; ignored for other modes. 0-365.+ * @minimum 0+ * @maximum 365+ * @nullable+ */+ end_days_ago?: number | null;+ }++ export interface AIPromptConfig {+ /** Analysis window for the report. Omitted = 'since_last_sent' (everything since the previous scheduled delivery). */+ window?: AIWindowConfig;+ }+export interface AIReportQueryDiagnostic {/** What this query step was meant to compute. */description: string;@@ -34925,6 +34970,8 @@ export namespace Schemas {* @nullable*/prompt?: string | null;+ /** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */+ ai_prompt_config?: AIPromptConfig;/** Delivery channel: email or slack.** * `email` - Email@@ -42088,6 +42135,8 @@ export namespace Schemas {* @nullable*/prompt?: string | null;+ /** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */+ ai_prompt_config?: AIPromptConfig;/** Delivery channel: email or slack.** * `email` - Emaildiff --git a/services/mcp/src/generated/subscriptions/api.ts b/services/mcp/src/generated/subscriptions/api.tsindex 132efb34d3f8..98640e6b148f 100644--- a/services/mcp/src/generated/subscriptions/api.ts+++ b/services/mcp/src/generated/subscriptions/api.ts@@ -39,6 +39,12 @@ export const SubscriptionsCreateParams = /* @__PURE__ */ zod.object({),})+export const subscriptionsCreateBodyAiPromptConfigOneWindowOneModeDefault = `since_last_sent`+export const subscriptionsCreateBodyAiPromptConfigOneWindowOneStartDaysAgoMax = 365++export const subscriptionsCreateBodyAiPromptConfigOneWindowOneEndDaysAgoMin = 0+export const subscriptionsCreateBodyAiPromptConfigOneWindowOneEndDaysAgoMax = 365+export const subscriptionsCreateBodyIntervalMax = 2147483647export const subscriptionsCreateBodyBysetposMin = -2147483648@@ -73,6 +79,45 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod.describe("Free-text prompt that drives the AI-generated report. Required when resource_type is 'ai_prompt'. Max 4000 characters."),+ ai_prompt_config: zod+ .object({+ window: zod+ .object({+ mode: zod+ .enum(['since_last_sent', 'last_n_days', 'days_ago_range'])+ .describe(+ '* `since_last_sent` - Since last report\n* `last_n_days` - Last N days\n* `days_ago_range` - Between X and Y days ago'+ )+ .default(subscriptionsCreateBodyAiPromptConfigOneWindowOneModeDefault)+ .describe(+ "What the report analyzes each run:\n* `since_last_sent` (default) — everything since the previous successful scheduled delivery (gap-free; test/manual sends don't move the anchor)\n* `last_n_days` — a fixed trailing window of start_days_ago days\n* `days_ago_range` — the explicit range from start_days_ago to end_days_ago days ago\n\n* `since_last_sent` - Since last report\n* `last_n_days` - Last N days\n* `days_ago_range` - Between X and Y days ago"+ ),+ start_days_ago: zod+ .number()+ .min(1)+ .max(subscriptionsCreateBodyAiPromptConfigOneWindowOneStartDaysAgoMax)+ .nullish()+ .describe(+ "Lower bound of the analysis window, in days before the run. Required for 'last_n_days' (the N) and 'days_ago_range'; ignored for 'since_last_sent'. 1-365."+ ),+ end_days_ago: zod+ .number()+ .min(subscriptionsCreateBodyAiPromptConfigOneWindowOneEndDaysAgoMin)+ .max(subscriptionsCreateBodyAiPromptConfigOneWindowOneEndDaysAgoMax)+ .nullish()+ .describe(+ "Upper bound of the analysis window, in days before the run (0 = now). Required for 'days_ago_range' and must be less than start_days_ago; ignored for other modes. 0-365."+ ),+ })+ .optional()+ .describe(+ "Analysis window for the report. Omitted = 'since_last_sent' (everything since the previous scheduled delivery)."+ ),+ })+ .optional()+ .describe(+ "Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."+ ),target_type: zod.enum(['email', 'slack']).describe('* `email` - Email\n* `slack` - Slack')@@ -171,6 +216,12 @@ export const SubscriptionsPartialUpdateParams = /* @__PURE__ */ zod.object({),})+export const subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneModeDefault = `since_last_sent`+export const subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneStartDaysAgoMax = 365++export const subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMin = 0+export const subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMax = 365+export const subscriptionsPartialUpdateBodyIntervalMax = 2147483647export const subscriptionsPartialUpdateBodyBysetposMin = -2147483648@@ -205,6 +256,45 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod.describe("Free-text prompt that drives the AI-generated report. Required when resource_type is 'ai_prompt'. Max 4000 characters."),+ ai_prompt_config: zod+ .object({+ window: zod+ .object({+ mode: zod+ .enum(['since_last_sent', 'last_n_days', 'days_ago_range'])+ .describe(+ '* `since_last_sent` - Since last report\n* `last_n_days` - Last N days\n* `days_ago_range` - Between X and Y days ago'+ )+ .default(subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneModeDefault)+ .describe(+ "What the report analyzes each run:\n* `since_last_sent` (default) — everything since the previous successful scheduled delivery (gap-free; test/manual sends don't move the anchor)\n* `last_n_days` — a fixed trailing window of start_days_ago days\n* `days_ago_range` — the explicit range from start_days_ago to end_days_ago days ago\n\n* `since_last_sent` - Since last report\n* `last_n_days` - Last N days\n* `days_ago_range` - Between X and Y days ago"+ ),+ start_days_ago: zod+ .number()+ .min(1)+ .max(subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneStartDaysAgoMax)+ .nullish()+ .describe(+ "Lower bound of the analysis window, in days before the run. Required for 'last_n_days' (the N) and 'days_ago_range'; ignored for 'since_last_sent'. 1-365."+ ),+ end_days_ago: zod+ .number()+ .min(subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMin)+ .max(subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMax)+ .nullish()+ .describe(+ "Upper bound of the analysis window, in days before the run (0 = now). Required for 'days_ago_range' and must be less than start_days_ago; ignored for other modes. 0-365."+ ),+ })+ .optional()+ .describe(+ "Analysis window for the report. Omitted = 'since_last_sent' (everything since the previous scheduled delivery)."+ ),+ })+ .optional()+ .describe(+ "Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."+ ),target_type: zod.enum(['email', 'slack']).describe('* `email` - Email\n* `slack` - Slack')diff --git a/services/mcp/src/tools/generated/subscriptions.ts b/services/mcp/src/tools/generated/subscriptions.tsindex 4f94483774f6..360ed7971c07 100644--- a/services/mcp/src/tools/generated/subscriptions.ts+++ b/services/mcp/src/tools/generated/subscriptions.ts@@ -38,6 +38,9 @@ const subscriptionsCreate = (): ToolBase<typeof SubscriptionsCreateSchema, Schemif (params.prompt !== undefined) {body['prompt'] = params.prompt}+ if (params.ai_prompt_config !== undefined) {+ body['ai_prompt_config'] = params.ai_prompt_config+ }if (params.target_type !== undefined) {body['target_type'] = params.target_type}@@ -223,6 +226,9 @@ const subscriptionsPartialUpdate = (): ToolBase<typeof SubscriptionsPartialUpdatif (params.prompt !== undefined) {body['prompt'] = params.prompt}+ if (params.ai_prompt_config !== undefined) {+ body['ai_prompt_config'] = params.ai_prompt_config+ }if (params.target_type !== undefined) {body['target_type'] = params.target_type}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.jsonindex befedc096fab..5f98195113a6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json@@ -2,6 +2,50 @@"$schema": "https://json-schema.org/draft/2020-12/schema","description": "Standard Subscription serializer.","properties": {+ "ai_prompt_config": {+ "description": "Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes.",+ "properties": {+ "window": {+ "description": "Analysis window for the report. Omitted = 'since_last_sent' (everything since the previous scheduled delivery).",+ "properties": {+ "end_days_ago": {+ "anyOf": [+ {+ "maximum": 365,+ "minimum": 0,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Upper bound of the analysis window, in days before the run (0 = now). Required for 'days_ago_range' and must be less than start_days_ago; ignored for other modes. 0-365."+ },+ "mode": {+ "default": "since_last_sent",+ "description": "What the report analyzes each run:\n* `since_last_sent` (default) — everything since the previous successful scheduled delivery (gap-free; test/manual sends don't move the anchor)\n* `last_n_days` — a fixed trailing window of start_days_ago days\n* `days_ago_range` — the explicit range from start_days_ago to end_days_ago days ago\n\n* `since_last_sent` - Since last report\n* `last_n_days` - Last N days\n* `days_ago_range` - Between X and Y days ago",+ "enum": ["since_last_sent", "last_n_days", "days_ago_range"],+ "type": "string"+ },+ "start_days_ago": {+ "anyOf": [+ {+ "maximum": 365,+ "minimum": 1,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Lower bound of the analysis window, in days before the run. Required for 'last_n_days' (the N) and 'days_ago_range'; ignored for 'since_last_sent'. 1-365."+ }+ },+ "type": "object"+ }+ },+ "type": "object"+ },"bysetpos": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-partial-update.jsonindex 41979e314d8f..68048c056b97 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-partial-update.json@@ -1,6 +1,50 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "ai_prompt_config": {+ "description": "Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes.",+ "properties": {+ "window": {+ "description": "Analysis window for the report. Omitted = 'since_last_sent' (everything since the previous scheduled delivery).",+ "properties": {+ "end_days_ago": {+ "anyOf": [+ {+ "maximum": 365,+ "minimum": 0,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Upper bound of the analysis window, in days before the run (0 = now). Required for 'days_ago_range' and must be less than start_days_ago; ignored for other modes. 0-365."+ },+ "mode": {+ "default": "since_last_sent",+ "description": "What the report analyzes each run:\n* `since_last_sent` (default) — everything since the previous successful scheduled delivery (gap-free; test/manual sends don't move the anchor)\n* `last_n_days` — a fixed trailing window of start_days_ago days\n* `days_ago_range` — the explicit range from start_days_ago to end_days_ago days ago\n\n* `since_last_sent` - Since last report\n* `last_n_days` - Last N days\n* `days_ago_range` - Between X and Y days ago",+ "enum": ["since_last_sent", "last_n_days", "days_ago_range"],+ "type": "string"+ },+ "start_days_ago": {+ "anyOf": [+ {+ "maximum": 365,+ "minimum": 1,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Lower bound of the analysis window, in days before the run. Required for 'last_n_days' (the N) and 'days_ago_range'; ignored for 'since_last_sent'. 1-365."+ }+ },+ "type": "object"+ }+ },+ "type": "object"+ },"bysetpos": {"anyOf": [{