: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(phai): add sandboxed SQL evals (#57293)
Chris Volzerae30199048da
diff --git a/ee/hogai/eval/sandboxed/conftest.py b/ee/hogai/eval/sandboxed/conftest.pyindex 81fe7842c38c..d5b27520a9a8 100644--- a/ee/hogai/eval/sandboxed/conftest.py+++ b/ee/hogai/eval/sandboxed/conftest.py@@ -16,6 +16,7 @@ import pytestfrom django.conf import settings+from posthog.models import OAuthApplicationfrom posthog.temporal.common.worker import create_workerfrom products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext@@ -52,6 +53,12 @@ def pytest_collection_modifyitems(config, items): # noqa: ARG001replicas. If a test ever needs a narrower whitelist it can set``databases=...`` on its own marker — explicit kwargs win.+ ``transaction=True`` is applied by default so ORM writes are committed and+ visible to Temporal activities, which run on worker threads with their own+ DB connections. Without this, ``get_task_processing_context`` raises+ ``TaskRun matching query does not exist`` while the test transaction is+ still open.+Prepended via ``append=False`` so it beats the function-level``@pytest.mark.django_db`` in pytest's ``iter_markers``/``get_closest_marker``resolution; otherwise the original (no-kwargs) marker is read first@@ -72,6 +79,8 @@ def pytest_collection_modifyitems(config, items): # noqa: ARG001continue # respect explicit per-test overrideargs = existing.args if existing is not None else ()kwargs = {**(existing.kwargs if existing is not None else {}), "databases": list(SANDBOXED_EVAL_DATABASES)}+ if "transaction" not in kwargs:+ kwargs["transaction"] = Trueitem.add_marker(pytest.mark.django_db(*args, **kwargs), append=False)@@ -215,6 +224,50 @@ def _cleanup_sandbox_containers(pytestconfig):_cleanup_eval_containers()[email protected](scope="session", autouse=True)+def _posthog_oauth_app(django_db_setup, django_db_blocker):+ """Seed the Array OAuth application required by sandbox MCP auth.++ The temporal workflow's ``provision_sandbox`` activity creates an OAuth+ access token so the sandbox can authenticate with the PostHog MCP server.+ Without this record the activity raises ``OAuthTokenError``.++ Uses ``get_array_app()`` first (succeeds if the app already exists in a+ reused DB), falling back to creating it with the client ID that+ ``get_array_app()`` would resolve for the current ``CLOUD_DEPLOYMENT``.+ """+ from posthog.temporal.oauth import (+ ARRAY_APP_CLIENT_ID_DEV,+ ARRAY_APP_CLIENT_ID_EU,+ ARRAY_APP_CLIENT_ID_US,+ get_array_app,+ )+ from posthog.utils import get_instance_region++ with django_db_blocker.unblock():+ try:+ app = get_array_app()+ except RuntimeError:+ region = get_instance_region()+ if region == "EU":+ client_id = ARRAY_APP_CLIENT_ID_EU+ elif region == "US":+ client_id = ARRAY_APP_CLIENT_ID_US+ else:+ client_id = ARRAY_APP_CLIENT_ID_DEV+ app, _ = OAuthApplication.objects.get_or_create(+ client_id=client_id,+ defaults={+ "name": "Array Test App",+ "client_type": OAuthApplication.CLIENT_PUBLIC,+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,+ "redirect_uris": "https://app.posthog.com/callback",+ "algorithm": "RS256",+ },+ )+ yield app++@pytest.fixture(scope="session", autouse=True)def _django_live_server(django_db_setup, django_db_blocker):"""Start an in-process Django HTTP server on the test database.@@ -268,7 +321,7 @@ def _sandboxed_local_skills(_sandbox_settings) -> Generator[Path, None, None]:@pytest.fixture(scope="session", autouse=True)-def _sandbox_settings(_django_live_server, _llm_gateway):+def _sandbox_settings(_django_live_server, _llm_gateway, _posthog_oauth_app):"""Configure Django settings required by the sandbox/temporal activities.All URLs use ``host.docker.internal`` so they're reachable from insidediff --git a/ee/hogai/eval/sandboxed/product_analytics/eval_funnel.py b/ee/hogai/eval/sandboxed/product_analytics/eval_funnel.pyindex afc373ff01e5..a6a588acdbb0 100644--- a/ee/hogai/eval/sandboxed/product_analytics/eval_funnel.py+++ b/ee/hogai/eval/sandboxed/product_analytics/eval_funnel.py@@ -47,9 +47,11 @@ def _funnel_case()[email protected]_db(transaction=True, databases="__all__")async def eval_funnel(sandboxed_demo_data, pytestconfig, posthog_client):- this_year = datetime.now().year+ now = datetime.now()+ this_year = now.year+ this_month_start = f"{now.year}-{now.month:02d}-01"cases = [_funnel_case(@@ -219,6 +221,40 @@ async def eval_funnel(sandboxed_demo_data, pytestconfig, posthog_client):],),),+ _funnel_case(+ name="funnel_pricing_page_to_paid_bill_this_month",+ prompt="what percentage of users who visited the pricing page completed the paid_bill event this month?",+ query=AssistantFunnelsQuery(+ aggregation_group_type_index=None,+ breakdownFilter=None,+ dateRange={"date_from": this_month_start, "date_to": None},+ filterTestAccounts=True,+ funnelsFilter=AssistantFunnelsFilter(+ binCount=None,+ exclusions=[],+ funnelOrderType="ordered",+ funnelStepReference="total",+ funnelVizType="steps",+ funnelWindowInterval=14,+ funnelWindowIntervalUnit="day",+ ),+ series=[+ AssistantFunnelsEventsNode(+ event="$pageview",+ math=None,+ properties=[+ {+ "key": "$pathname",+ "value": "/pricing/",+ "operator": "exact",+ "type": "event",+ }+ ],+ ),+ AssistantFunnelsEventsNode(event="paid_bill", math=None, properties=None),+ ],+ ),+ ),_funnel_case(name="funnel_signup_generic",prompt="What's our sign-up funnel?",diff --git a/ee/hogai/eval/sandboxed/product_analytics/scorers.py b/ee/hogai/eval/sandboxed/product_analytics/scorers.pyindex 6ac74dd40b41..b92036a239fc 100644--- a/ee/hogai/eval/sandboxed/product_analytics/scorers.py+++ b/ee/hogai/eval/sandboxed/product_analytics/scorers.py@@ -54,7 +54,7 @@ How would you rate the alignment of the generated query with the expected query?Details matter greatly here — including math types, property types, and filter direction — so be harsh.""".strip()-_JUDGE_MODEL = "gpt-5.4"+JUDGE_MODEL = "gpt-5.4"# PostHog MCP tools that persist saved-insight state. The sandbox is disposable# but these tools still hit real rows, so any successful call is a bug in the@@ -69,8 +69,8 @@ INSIGHT_WRITE_TOOLS = frozenset()-class _JudgedScorer(LLMClassifier):- """Shared wiring for product-analytics LLM judges.+class JudgedScorer(LLMClassifier):+ """Shared wiring for sandboxed LLM judges.Subclasses implement ``_prepare(output, expected)`` returning either a``Score`` to short-circuit, or a dict with ``output``/``expected`` to@@ -105,7 +105,7 @@ class _JudgedScorer(LLMClassifier):raise NotImplementedError-def _parser_for(output: dict[str, Any] | None) -> LogParser | None:+def parser_for(output: dict[str, Any] | None) -> LogParser | None:if not output:return Noneraw_log = output.get("raw_log")@@ -114,7 +114,7 @@ def _parser_for(output: dict[str, Any] | None) -> LogParser | None:return LogParser(raw_log, initial_prompt=output.get("prompt", "") or "")-def _extract_last_successful_input(+def extract_last_successful_input(parser: LogParser | None,tool_name: str,schema: type[BaseModel] | None = None,@@ -145,9 +145,9 @@ def _extract_last_successful_input(return raw-def _user_prompt(output: dict[str, Any] | None) -> str:+def user_prompt(output: dict[str, Any] | None) -> str:"""Return the original user prompt from the eval output dict."""- parser = _parser_for(output)+ parser = parser_for(output)if parser is not None:return parser.get_user_prompt()if output:@@ -164,10 +164,10 @@ def extract_last_query_retention_input(output: dict[str, Any] | None) -> dict[stthat depend on this should short-circuit with ``score=None`` in that caserather than counting it as an incorrect retention query."""- return _extract_last_successful_input(_parser_for(output), QUERY_RETENTION_TOOL_NAME, AssistantRetentionQuery)+ return extract_last_successful_input(parser_for(output), QUERY_RETENTION_TOOL_NAME, AssistantRetentionQuery)-class RetentionSchemaAlignment(_JudgedScorer):+class RetentionSchemaAlignment(JudgedScorer):"""Graded score: how well does the actual retention query match the expected one?Semantic comparison rather than strict field-by-field equality — multiple@@ -192,7 +192,7 @@ class RetentionSchemaAlignment(_JudgedScorer):metadata={"reason": "No expected.retention_query provided"},)return {- "output": {"retention_query": actual, "prompt": _user_prompt(output)},+ "output": {"retention_query": actual, "prompt": user_prompt(output)},"expected": {"retention_query": expected_query},}@@ -237,13 +237,13 @@ Penalize:+ "\n\n"+ GRADED_ALIGNMENT_RUBRIC,choice_scores=GRADED_ALIGNMENT_CHOICE_SCORES,- model=_JUDGE_MODEL,+ model=JUDGE_MODEL,max_completion_tokens=512,**kwargs,)-class RetentionTimeRangeRelevancy(_JudgedScorer):+class RetentionTimeRangeRelevancy(JudgedScorer):"""Binary yes/no: is the retention query's time range / period consistent with the user prompt?"""def _prepare(self, output, expected) -> dict[str, Any] | Score:@@ -254,7 +254,7 @@ class RetentionTimeRangeRelevancy(_JudgedScorer):score=0.0,metadata={"reason": "Agent never ran query-retention successfully"},)- prompt = _user_prompt(output)+ prompt = user_prompt(output)return {"output": {"retention_query": actual,@@ -287,7 +287,7 @@ Evaluation rules:Is the time range / period in the actual query consistent with the user's prompt? Answer `yes` or `no`.""".strip(),choice_scores=BINARY_CHOICE_SCORES,- model=_JUDGE_MODEL,+ model=JUDGE_MODEL,max_completion_tokens=512,**kwargs,)@@ -300,10 +300,10 @@ def extract_last_query_trends_input(output: dict[str, Any] | None) -> dict[str,that depend on this should short-circuit with ``score=None`` in that caserather than counting it as an incorrect trends query."""- return _extract_last_successful_input(_parser_for(output), QUERY_TRENDS_TOOL_NAME, AssistantTrendsQuery)+ return extract_last_successful_input(parser_for(output), QUERY_TRENDS_TOOL_NAME, AssistantTrendsQuery)-class TrendsSchemaAlignment(_JudgedScorer):+class TrendsSchemaAlignment(JudgedScorer):"""Graded score: how well does the actual trends query match the expected one?Semantic comparison rather than strict field-by-field equality — multiple@@ -330,7 +330,7 @@ class TrendsSchemaAlignment(_JudgedScorer):metadata={"reason": "No expected.trends_query provided"},)return {- "output": {"trends_query": actual, "prompt": _user_prompt(output)},+ "output": {"trends_query": actual, "prompt": user_prompt(output)},"expected": {"trends_query": expected_query},}@@ -381,13 +381,13 @@ Penalize:+ "\n\n"+ GRADED_ALIGNMENT_RUBRIC,choice_scores=GRADED_ALIGNMENT_CHOICE_SCORES,- model=_JUDGE_MODEL,+ model=JUDGE_MODEL,max_completion_tokens=512,**kwargs,)-class TrendsTimeRangeRelevancy(_JudgedScorer):+class TrendsTimeRangeRelevancy(JudgedScorer):"""Binary yes/no: is the trends query's time range / interval consistent with the user prompt?"""def _prepare(self, output, expected) -> dict[str, Any] | Score:@@ -398,7 +398,7 @@ class TrendsTimeRangeRelevancy(_JudgedScorer):score=0.0,metadata={"reason": "Agent never ran query-trends successfully"},)- prompt = _user_prompt(output)+ prompt = user_prompt(output)return {"output": {"trends_query": actual,@@ -430,7 +430,7 @@ Evaluation rules:Is the time range / interval in the actual query consistent with the user's prompt? Answer `yes` or `no`.""".strip(),choice_scores=BINARY_CHOICE_SCORES,- model=_JUDGE_MODEL,+ model=JUDGE_MODEL,max_completion_tokens=512,**kwargs,)@@ -445,10 +445,10 @@ def extract_last_query_funnel_input(output: dict[str, Any] | None) -> dict[str,legitimately answered via HogQL (``execute-sql``); that's covered by theexit-code scorer, not by these LLM judges."""- return _extract_last_successful_input(_parser_for(output), QUERY_FUNNEL_TOOL_NAME, AssistantFunnelsQuery)+ return extract_last_successful_input(parser_for(output), QUERY_FUNNEL_TOOL_NAME, AssistantFunnelsQuery)-class FunnelSchemaAlignment(_JudgedScorer):+class FunnelSchemaAlignment(JudgedScorer):"""Graded score: how well does the actual funnel query match the expected one?Semantic comparison rather than strict field-by-field equality — multiple@@ -473,7 +473,7 @@ class FunnelSchemaAlignment(_JudgedScorer):metadata={"reason": "No expected.funnel_query provided"},)return {- "output": {"funnel_query": actual, "prompt": _user_prompt(output)},+ "output": {"funnel_query": actual, "prompt": user_prompt(output)},"expected": {"funnel_query": expected_query},}@@ -520,13 +520,13 @@ Penalize:+ "\n\n"+ GRADED_ALIGNMENT_RUBRIC,choice_scores=GRADED_ALIGNMENT_CHOICE_SCORES,- model=_JUDGE_MODEL,+ model=JUDGE_MODEL,max_completion_tokens=512,**kwargs,)-class FunnelTimeRangeRelevancy(_JudgedScorer):+class FunnelTimeRangeRelevancy(JudgedScorer):"""Binary yes/no: is the funnel query's time range + conversion window consistent with the user prompt?"""def _prepare(self, output, expected) -> dict[str, Any] | Score:@@ -537,7 +537,7 @@ class FunnelTimeRangeRelevancy(_JudgedScorer):score=0.0,metadata={"reason": "Agent never ran query-funnel successfully"},)- prompt = _user_prompt(output)+ prompt = user_prompt(output)return {"output": {"funnel_query": actual,@@ -573,7 +573,7 @@ Other rules:Are the time range AND the conversion window in the actual query consistent with the user's prompt? Answer `yes` or `no`.""".strip(),choice_scores=BINARY_CHOICE_SCORES,- model=_JUDGE_MODEL,+ model=JUDGE_MODEL,max_completion_tokens=512,**kwargs,)@@ -618,7 +618,7 @@ class SchemaDiscoveryOrder(Scorer):def _evaluate(self, output: dict | None, expected: dict | None) -> Score:if not output:return Score(name=self._name(), score=None, metadata={"reason": "No output"})- parser = _parser_for(output)+ parser = parser_for(output)if parser is None:return Score(name=self._name(), score=None, metadata={"reason": "No raw log"})diff --git a/ee/hogai/eval/sandboxed/sql/__init__.py b/ee/hogai/eval/sandboxed/sql/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/ee/hogai/eval/sandboxed/sql/eval_sql.py b/ee/hogai/eval/sandboxed/sql/eval_sql.pynew file mode 100644index 000000000000..6fa9eb9a5de8--- /dev/null+++ b/ee/hogai/eval/sandboxed/sql/eval_sql.py@@ -0,0 +1,403 @@+"""SQL eval cases for the sandboxed coding agent.++Intent mirrors ``ee/hogai/eval/ci/eval_sql.py`` — the CI version drives the+LangGraph chat agent in ``AgentMode.SQL`` (which forces the SQL path), this+version exercises the same questions end-to-end through the sandboxed agent++ PostHog MCP tools and judges the HogQL the agent ran via the+``execute-sql`` MCP tool.++Prompts are rephrased from the CI dataset to explicitly request HogQL.+The CI flow forces SQL via ``AgentMode.SQL``; the sandboxed agent has no+equivalent mode and is free to answer with typed query tools+(``query-trends`` / ``query-funnel`` / ``query-retention``). Without the+``Write a HogQL query that…`` framing, several cases would route to a+typed query tool — perfectly valid for the user, but not what this eval+is testing. The framing is the forcing function in lieu of an agent mode.++To run:+ pytest ee/hogai/eval/sandboxed/sql/eval_sql.py+"""++from __future__ import annotations++import pytest++from ee.hogai.eval.sandboxed.base import SandboxedPublicEval+from ee.hogai.eval.sandboxed.config import SandboxedEvalCase+from ee.hogai.eval.sandboxed.product_analytics.scorers import INSIGHT_WRITE_TOOLS+from ee.hogai.eval.sandboxed.retrieval.scorers import SkillLoaded+from ee.hogai.eval.sandboxed.scorers import ExitCodeZero, LastToolCallNot, NoToolCall, RequiredToolCall+from ee.hogai.eval.sandboxed.sql.scorers import SQLResultMessageAlignment, SQLSchemaAlignment+++def _sql_case(*, name: str, prompt: str, expected_sql: str) -> SandboxedEvalCase:+ return SandboxedEvalCase(+ name=name,+ prompt=prompt,+ expected={"sql_query": expected_sql.strip()},+ )+++async def eval_sql(sandboxed_demo_data, pytestconfig, posthog_client, mcp_mode):+ cases = [+ # Straightforward breakdowns+ _sql_case(+ name="sql_pageviews_by_browser",+ prompt="How many pageviews did each browser have?",+ expected_sql="""+SELECT properties.$browser as browser, count(*) as pageview_count+FROM events+WHERE event = '$pageview'+GROUP BY browser+ORDER BY pageview_count DESC+LIMIT 100+""",+ ),+ _sql_case(+ name="sql_top_countries_by_users_7d",+ prompt="What are the top 10 countries by unique users in the last 7 days?",+ expected_sql="""+SELECT properties.$geoip_country_name as country, count(distinct person_id) as user_count+FROM events+WHERE timestamp >= now() - interval 7 day+GROUP BY country+ORDER BY user_count DESC+LIMIT 10+""",+ ),+ # Session duration+ _sql_case(+ name="sql_avg_session_duration_by_dow",+ prompt="give me the average session duration broken down by day of week",+ expected_sql="""+SELECT toDayOfWeek(timestamp) as day_of_week,+ avg(session.$session_duration) as avg_session_duration+FROM events+GROUP BY day_of_week+ORDER BY day_of_week+""",+ ),+ # Property math+ _sql_case(+ name="sql_distinct_browsers_per_day_14d",+ prompt=("give me the number of distinct values of property $browser seen in each of the last 14 days"),+ expected_sql="""+SELECT date_trunc('day', timestamp) as day, count(distinct properties.$browser) as distinct_browser_count+FROM events+WHERE event = '$pageview'+ AND timestamp >= now() - INTERVAL 14 DAY+GROUP BY day+ORDER BY day+""",+ ),+ _sql_case(+ name="sql_paid_bill_total_hedgebox_30d",+ prompt=("sum up the total amounts paid for the 'paid_bill' event over the past month for Hedgebox Inc."),+ expected_sql="""+SELECT sum(toFloat(properties.amount_usd)) AS total_amount_paid+FROM events+WHERE event = 'paid_bill'+ AND timestamp >= now() - INTERVAL 30 DAY+ AND organization.properties.name = 'Hedgebox Inc.'+""",+ ),+ # Open questions to list persons+ _sql_case(+ name="sql_5_users_to_interview_file_downloads",+ prompt=("return the 5 users I should interview around file download usage with their email and name"),+ expected_sql="""+SELECT+ person_id,+ person.properties.email as email,+ person.properties.name as name,+ count(*) as usage_count,+ max(timestamp) as last_used+FROM events+WHERE event = 'downloaded_file'+GROUP BY person_id, person.properties.email, person.properties.name+ORDER BY usage_count DESC, last_used DESC+LIMIT 5+""",+ ),+ _sql_case(+ name="sql_top_5_file_downloaders_recent",+ prompt=("the 5 users that have downloaded the most files in the past few weeks with their email and name"),+ expected_sql="""+SELECT+ person_id,+ person.properties.email as email,+ person.properties.name as name,+ count(*) as file_download_count,+ max(timestamp) as last_download+FROM events+WHERE event = 'downloaded_file'+ AND timestamp >= now() - INTERVAL 14 DAY+GROUP BY person_id, person.properties.email, person.properties.name+ORDER BY file_download_count DESC+LIMIT 5+""",+ ),+ _sql_case(+ name="sql_10_file_downloader_profiles",+ prompt=(+ "show me 10 example person profiles of file download users including email, name, company, role, created_at, and number of downloads"+ ),+ expected_sql="""+SELECT DISTINCT+ person_id,+ person.properties.email as email,+ person.properties.name as name,+ person.properties.company as company,+ person.properties.role as role,+ person.properties.created_at as user_created_at,+ count(*) as file_download_event_count+FROM events+WHERE event = 'downloaded_file'+GROUP BY person_id, person.properties.email, person.properties.name,+ person.properties.company, person.properties.role, person.properties.created_at+LIMIT 10+""",+ ),+ # Funnel trends+ _sql_case(+ name="sql_trial_to_paid_conversion_by_cohort_month",+ prompt=("the conversion rate from trial signup to paid subscription by cohort month"),+ expected_sql="""+WITH trial_signups AS (+ SELECT+ person_id,+ date_trunc('month', min(timestamp)) as cohort_month+ FROM events+ WHERE event = 'trial_signup'+ GROUP BY person_id+),+conversions AS (+ SELECT DISTINCT person_id+ FROM events+ WHERE event = 'subscription_started'+)+SELECT+ cohort_month,+ count(DISTINCT t.person_id) as trial_signups,+ count(DISTINCT c.person_id) as paid_conversions,+ (count(DISTINCT c.person_id) * 100.0 / count(DISTINCT t.person_id)) as conversion_rate+FROM trial_signups t+LEFT JOIN conversions c ON t.person_id = c.person_id+GROUP BY cohort_month+ORDER BY cohort_month+""",+ ),+ _sql_case(+ name="sql_median_time_between_pageviews_by_browser",+ prompt=("the median time between page views for each browser type excluding users with only 1 page view"),+ expected_sql="""+WITH pageview_times AS (+ SELECT+ person_id,+ properties.$browser as browser_type,+ timestamp,+ LAG(timestamp) OVER (PARTITION BY person_id ORDER BY timestamp) as prev_timestamp+ FROM events+ WHERE event = '$pageview'+),+time_diffs AS (+ SELECT+ person_id,+ browser_type,+ dateDiff('second', prev_timestamp, timestamp) as seconds_between_views+ FROM pageview_times+ WHERE prev_timestamp IS NOT NULL+),+user_pageview_counts AS (+ SELECT person_id, count(*) as pageview_count+ FROM events+ WHERE event = '$pageview'+ GROUP BY person_id+ HAVING pageview_count > 1+)+SELECT+ browser_type,+ median(seconds_between_views) as median_seconds_between_views+FROM time_diffs+WHERE person_id IN (SELECT person_id FROM user_pageview_counts)+GROUP BY browser_type+ORDER BY median_seconds_between_views DESC+""",+ ),+ # Correlation — CI version had a tuple-with-extra-context retry; inlined into a single prompt here.+ _sql_case(+ name="sql_feature_churn_correlation_120d",+ prompt=("shows which features are most predictive of churn"),+ expected_sql="""+WITH user_metrics AS (+ SELECT+ fu.person_id,+ fu.uploads_30d,+ fu.downloads_30d,+ fu.shares_30d,+ fu.invites_30d,+ fu.upgrades_30d,+ fu.downgrades_30d,+ fu.total_events_30d,+ cs.churned+ FROM (+ SELECT+ e.person_id,+ countIf(e.event = 'uploaded_file') AS uploads_30d,+ countIf(e.event = 'downloaded_file') AS downloads_30d,+ countIf(e.event = 'shared_file_link') AS shares_30d,+ countIf(e.event = 'invited_team_member') AS invites_30d,+ countIf(e.event = 'upgraded_plan') AS upgrades_30d,+ countIf(e.event = 'downgraded_plan') AS downgrades_30d,+ count() AS total_events_30d,+ MIN(e.timestamp) AS first_activity_date+ FROM events e+ WHERE e.timestamp >= now() - INTERVAL 120 DAY+ GROUP BY e.person_id+ HAVING first_activity_date <= now() - INTERVAL 90 DAY+ ) fu+ INNER JOIN (+ SELECT+ person_id,+ MIN(timestamp) AS first_activity_date,+ CASE+ WHEN MAX(activity_31_90) = 1 THEN 0 ELSE 1+ END AS churned+ FROM (+ SELECT+ person_id,+ timestamp,+ CASE WHEN timestamp >= min_timestamp + INTERVAL 30 DAY AND timestamp < min_timestamp + INTERVAL 90 DAY THEN 1 ELSE 0 END AS activity_31_90,+ min_timestamp+ FROM (+ SELECT+ person_id,+ timestamp,+ MIN(timestamp) OVER (PARTITION BY person_id) AS min_timestamp+ FROM events+ WHERE timestamp >= now() - INTERVAL 120 DAY+ )+ )+ GROUP BY person_id, min_timestamp+ HAVING min_timestamp <= now() - INTERVAL 90 DAY+ ) cs ON fu.person_id = cs.person_id+)++SELECT+ 'uploads' AS feature,+ AVG(CASE WHEN churned = 1 THEN uploads_30d ELSE 0 END) AS avg_usage_churned,+ AVG(CASE WHEN churned = 0 THEN uploads_30d ELSE 0 END) AS avg_usage_retained,+ AVG(churned) AS overall_churn_rate,+ AVG(CASE WHEN uploads_30d > 0 THEN churned ELSE NULL END) AS churn_rate_with_feature,+ AVG(CASE WHEN uploads_30d = 0 THEN churned ELSE NULL END) AS churn_rate_without_feature,+ corr(toFloat(uploads_30d), toFloat(churned)) AS correlation_coefficient+FROM user_metrics++UNION ALL++SELECT+ 'downloads' AS feature,+ AVG(CASE WHEN churned = 1 THEN downloads_30d ELSE 0 END),+ AVG(CASE WHEN churned = 0 THEN downloads_30d ELSE 0 END),+ AVG(churned),+ AVG(CASE WHEN downloads_30d > 0 THEN churned ELSE NULL END),+ AVG(CASE WHEN downloads_30d = 0 THEN churned ELSE NULL END),+ corr(toFloat(downloads_30d), toFloat(churned))+FROM user_metrics++UNION ALL++SELECT+ 'shares' AS feature,+ AVG(CASE WHEN churned = 1 THEN shares_30d ELSE 0 END),+ AVG(CASE WHEN churned = 0 THEN shares_30d ELSE 0 END),+ AVG(churned),+ AVG(CASE WHEN shares_30d > 0 THEN churned ELSE NULL END),+ AVG(CASE WHEN shares_30d = 0 THEN churned ELSE NULL END),+ corr(toFloat(shares_30d), toFloat(churned))+FROM user_metrics++UNION ALL++SELECT+ 'invites' AS feature,+ AVG(CASE WHEN churned = 1 THEN invites_30d ELSE 0 END),+ AVG(CASE WHEN churned = 0 THEN invites_30d ELSE 0 END),+ AVG(churned),+ AVG(CASE WHEN invites_30d > 0 THEN churned ELSE NULL END),+ AVG(CASE WHEN invites_30d = 0 THEN churned ELSE NULL END),+ corr(toFloat(invites_30d), toFloat(churned))+FROM user_metrics++UNION ALL++SELECT+ 'upgrades' AS feature,+ AVG(CASE WHEN churned = 1 THEN upgrades_30d ELSE 0 END),+ AVG(CASE WHEN churned = 0 THEN upgrades_30d ELSE 0 END),+ AVG(churned),+ AVG(CASE WHEN upgrades_30d > 0 THEN churned ELSE NULL END),+ AVG(CASE WHEN upgrades_30d = 0 THEN churned ELSE NULL END),+ corr(toFloat(upgrades_30d), toFloat(churned))+FROM user_metrics++ORDER BY ABS(corr(toFloat(uploads_30d), toFloat(churned))) DESC+""",+ ),+ _sql_case(+ name="sql_weekly_pageviews_monday_start_4w",+ prompt=("shows weekly pageview counts with Monday as the start of week for the last 4 weeks"),+ expected_sql="""+SELECT toStartOfWeek(timestamp, 1) as week_start, count(*) as pageview_count+FROM events+WHERE event = '$pageview'+ AND timestamp >= now() - INTERVAL 4 WEEK+GROUP BY week_start+ORDER BY week_start+""",+ ),+ _sql_case(+ name="sql_earliest_session_per_user_30d",+ prompt="what isthe earliest session date for each user in the last month",+ expected_sql="""+SELECT person_id, toDate(min(timestamp)) as first_session_date+FROM events+WHERE timestamp >= now() - INTERVAL 30 DAY+GROUP BY person_id+ORDER BY first_session_date+""",+ ),+ _sql_case(+ name="sql_split_interests_count_users",+ prompt=(+ "How many unique users have at least one interest set in the comma-separated `interests` property?"+ ),+ expected_sql="""+SELECT count(distinct person_id) as users_with_interests+FROM events+WHERE properties.interests IS NOT NULL+ AND length(splitByChar(',', coalesce(properties.interests, ''))) > 0+""",+ ),+ ]++ await SandboxedPublicEval(+ experiment_name=f"sandboxed-sql-{mcp_mode}",+ cases=cases,+ scorers=[+ ExitCodeZero(),+ NoToolCall(forbidden=INSIGHT_WRITE_TOOLS, name="no_persistent_insight_save"),+ RequiredToolCall(required={"execute-sql"}, name="execute_sql_called"),+ LastToolCallNot(+ forbidden={"query-trends", "query-funnel", "query-retention"},+ name="last_call_not_typed_query",+ ),+ SkillLoaded("querying-posthog-data", name="querying_posthog_data_skill_loaded"),+ SQLSchemaAlignment(),+ SQLResultMessageAlignment(),+ ],+ pytestconfig=pytestconfig,+ sandboxed_demo_data=sandboxed_demo_data,+ posthog_client=posthog_client,+ )diff --git a/ee/hogai/eval/sandboxed/sql/scorers.py b/ee/hogai/eval/sandboxed/sql/scorers.pynew file mode 100644index 000000000000..7adb32ed495e--- /dev/null+++ b/ee/hogai/eval/sandboxed/sql/scorers.py@@ -0,0 +1,258 @@+"""SQL scorers for the sandboxed coding-agent evals.++Extracts the final ``execute-sql`` MCP tool call the agent made and grades+the HogQL query against an expected reference query. Mirrors the trends /+funnel / retention judges in shape but lives outside ``product_analytics/``+because ``execute-sql`` is a general-purpose tool, not a product-analytics+one.++The judge prompt is forked from the CI ``SQL_SEMANTICS_CORRECTNESS_PROMPT``+in ``ee/hogai/eval/scorers/sql.py`` — same HogQL guidance, but graded on+the six-bucket ``GRADED_ALIGNMENT_*`` scale used by the rest of the+sandboxed evals instead of binary Pass/Fail. The ``database_schema``+placeholder is dropped: the sandboxed run doesn't surface a schema dump+to scorers, and the judge has the user prompt + reference SQL to anchor+on without it.++The shared judge plumbing (``JudgedScorer``, ``parser_for``,+``user_prompt``, alignment constants, ``JUDGE_MODEL``) is cross-imported+from ``product_analytics/scorers.py``.+That's a layering smell — they're general-purpose helpers tied to a+domain folder by accident — but with only this one new consumer, the+fix-up belongs in a follow-up refactor when a third general-purpose eval+(warehouse, system tables, persons CRUD) lands. Don't lift speculatively.+"""++from __future__ import annotations++from typing import Any++from braintrust import Score++from ee.hogai.eval.sandboxed.product_analytics.scorers import (+ GRADED_ALIGNMENT_CHOICE_SCORES,+ GRADED_ALIGNMENT_RUBRIC,+ JUDGE_MODEL,+ JudgedScorer,+ parser_for,+ user_prompt,+)++QUERY_SQL_TOOL_NAME = "execute-sql"+_MAX_RESULT_CHARS_FOR_JUDGE = 12_000+++def extract_last_execute_sql_call(output: dict[str, Any] | None) -> dict[str, str] | None:+ """Return the query and result from the most recent successful ``execute-sql`` call.++ Returns ``None`` when the agent never ran the tool successfully — scorers+ should short-circuit in that case rather than count it as an incorrect+ answer.+ """+ parser = parser_for(output)+ if parser is None:+ return None++ successful = [call for call in parser.get_tool_calls(QUERY_SQL_TOOL_NAME) if not call.is_error]+ if not successful:+ return None++ call = successful[-1]+ query = call.input.get("query")+ if not isinstance(query, str) or not query.strip():+ return None+ return {"query": query, "result": call.output}+++def extract_last_execute_sql_query(output: dict[str, Any] | None) -> str | None:+ """Return the query string from the most recent successful ``execute-sql`` call."""+ call = extract_last_execute_sql_call(output)+ if call is not None:+ return call["query"]+ return None+++def _truncate_result_for_judge(result: str) -> str:+ if len(result) <= _MAX_RESULT_CHARS_FOR_JUDGE:+ return result+ return f"{result[:_MAX_RESULT_CHARS_FOR_JUDGE]}\n\n...[truncated for judge]..."+++SQL_SCHEMA_ALIGNMENT_PROMPT = """+You are an expert ClickHouse SQL auditor judging whether an agent-produced HogQL query would equally answer the user's question, compared to a reference "ideal" query.++HogQL is an SQL flavor derived from ClickHouse SQL, with PostHog-specific syntax:+- JSON property access via `.`, like `SELECT properties.$browser FROM events`+- Nested table access, like `SELECT person.properties.foo FROM events`+- `sessions` table with session-level fields (`session.$session_duration` etc.)++The bar is **semantic equivalence**, not strict field equality. Multiple correct queries can answer the same prompt — accept the actual query if a reasonable analyst would consider it an equally valid way to answer the user's question. Reject only when a logical difference could yield different output under some valid database state.++User prompt:+<user_prompt>+{{output.prompt}}+</user_prompt>++Material aspects to compare:+1. **Result shape**: rows and columns the query returns. Column aliases, ordering, and trivial formatting differences are fine. Different result shape (e.g. one row vs many, missing aggregates the prompt asked for) is a miss.+2. **Filters**: WHERE / HAVING clauses must produce the same row set. Time predicates must be equivalent (e.g. `now() - INTERVAL 7 DAY` vs `timestamp >= today() - 7`). Event-name and property filters are case-sensitive.+3. **Aggregations**: same grouping keys, same aggregate functions, same handling of NULLs and duplicates. `count(distinct person_id)` and `count(distinct distinct_id)` are NOT equivalent for unique-user counts.+4. **Joins and subqueries**: same join keys, same join type (INNER vs LEFT), same conversion of correlated subqueries to joins. CTEs vs subqueries are equivalent when the join shape matches.+5. **Sequence / ordering logic**: when the prompt asks about an ordered sequence ("in this order", "before", "after"), the actual query must enforce ordering (window functions, timestamp comparisons). When the prompt asks for "regardless of order", a count-distinct of events is fine.+6. **Time-bucketing**: `toStartOfWeek(timestamp, 1)` (Monday-start) and `toStartOfWeek(timestamp)` (Sunday-start) are NOT equivalent when the prompt specifies a week start. `date_trunc('week', ...)` defaults vary by engine.+7. **Limits and ordering**: when the prompt asks for "top N" or "5 users", `LIMIT` and `ORDER BY` must be present and consistent. Missing them is a miss.++Penalize:+- Wrong identifier for unique users: must be `person_id` or `person.id`, NOT `distinct_id`.+- Wrong field for session duration: must be `session.$session_duration`, NOT `properties.$session_duration`.+- Missing time window when the prompt specifies one.+- Aggregating without the requested grouping (e.g. "by browser" but no `GROUP BY browser`).+- Subtle NULL-handling mistakes that change the count (e.g. `count(*)` vs `count(col)` when `col` can be NULL and the prompt asks "how many rows").++Ignore:+- Column aliases, output column ordering, whitespace, capitalization of keywords.+- Choice of CTE vs subquery vs derived table when the join shape is the same.+- LIMIT 100 added defensively when the prompt didn't ask for a limit.++<expected_query>+{{expected.sql_query}}+</expected_query>++<actual_query>+{{output.sql_query}}+</actual_query>+""".strip()+++class SQLSchemaAlignment(JudgedScorer):+ """Graded score: how well does the actual HogQL query match the expected one?++ Semantic comparison rather than strict text equality — multiple correct+ queries can answer the same prompt. Same six-bucket gradation as the+ typed-query alignment scorers in ``product_analytics/scorers.py``.+ """++ def _prepare(self, output, expected) -> dict[str, Any] | Score:+ actual = extract_last_execute_sql_query(output)+ if actual is None:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "Agent never ran execute-sql successfully"},+ )+ expected_query = (expected or {}).get("sql_query") if isinstance(expected, dict) else None+ if not isinstance(expected_query, str) or not expected_query.strip():+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "No expected.sql_query provided"},+ )+ return {+ "output": {"sql_query": actual, "prompt": user_prompt(output)},+ "expected": {"sql_query": expected_query},+ }++ def __init__(self, **kwargs):+ super().__init__(+ name="sql_schema_alignment",+ prompt_template=SQL_SCHEMA_ALIGNMENT_PROMPT + "\n\n" + GRADED_ALIGNMENT_RUBRIC,+ choice_scores=GRADED_ALIGNMENT_CHOICE_SCORES,+ model=JUDGE_MODEL,+ max_completion_tokens=512,+ **kwargs,+ )+++SQL_RESULT_MESSAGE_ALIGNMENT_RUBRIC = """+How would you rate the assistant's final answer? Choose one:+- perfect: Directly answers the user, faithfully summarizes the executed SQL result, and includes the important values or conclusion.+- near_perfect: Answers the user and is faithful to the result, with only small omissions or extra detail.+- slightly_off: Mostly answers the user, but misses a minor result detail or includes slightly confusing framing.+- somewhat_misaligned: Partly related, but omits important result information, over-focuses on SQL rather than the answer, or is hard for the user to act on.+- strongly_misaligned: Substantially contradicts the executed result, answers a different question, or only provides a query with no useful result interpretation.+- useless: No meaningful final answer, fabricated answer, or impossible to evaluate.++Be strict about factual faithfulness. Do not reward a fluent answer that invents values not present in the SQL result.+""".strip()+++SQL_RESULT_MESSAGE_ALIGNMENT_PROMPT = """+You are an expert analytics QA reviewer judging whether an agent's final response correctly answers the user's question after running HogQL.++The agent was required to execute SQL and then answer the user from the SQL result.+Judge only the final assistant message, using the user prompt, executed query, and SQL result as evidence.++Accept:+- A concise natural-language answer.+- A short table or bullet list when the user asked for grouped or ranked results.+- Including the executed SQL, as long as the message also answers the user.++Penalize:+- Only returning SQL or implementation details without interpreting the result.+- Omitting the key values or conclusion from the SQL result.+- Copying a large raw result table without a useful answer.+- Contradicting the SQL result or inventing values that are not supported by it.+- Saying the data is unavailable when the executed result contains relevant rows.++User prompt:+<user_prompt>+{{output.prompt}}+</user_prompt>++Executed HogQL:+<executed_query>+{{output.sql_query}}+</executed_query>++SQL result:+<sql_result>+{{output.sql_result}}+</sql_result>++Final assistant message:+<final_message>+{{output.final_message}}+</final_message>+""".strip()+++class SQLResultMessageAlignment(JudgedScorer):+ """Graded score: did the final message answer the user from the SQL result?"""++ def _prepare(self, output, expected) -> dict[str, Any] | Score: # noqa: ARG002+ executed = extract_last_execute_sql_call(output)+ if executed is None:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "Agent never ran execute-sql successfully"},+ )++ parser = parser_for(output)+ final_message = parser.get_final_agent_message() if parser is not None else None+ if not isinstance(final_message, str) or not final_message.strip():+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "No final assistant message found"},+ )++ return {+ "output": {+ "prompt": user_prompt(output),+ "sql_query": executed["query"],+ "sql_result": _truncate_result_for_judge(executed["result"]),+ "final_message": final_message,+ },+ "expected": {},+ }++ def __init__(self, **kwargs):+ super().__init__(+ name="sql_result_message_alignment",+ prompt_template=SQL_RESULT_MESSAGE_ALIGNMENT_PROMPT + "\n\n" + SQL_RESULT_MESSAGE_ALIGNMENT_RUBRIC,+ choice_scores=GRADED_ALIGNMENT_CHOICE_SCORES,+ model=JUDGE_MODEL,+ max_completion_tokens=512,+ **kwargs,+ )diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr b/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambrindex b8ad643c0e5a..cada6a45d5be 100644--- a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr+++ b/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr@@ -1223,6 +1223,98 @@use_hive_partitioning=0'''# ---+# name: TestWebStatsTableQueryRunner.test_bounce_rate_path_cleaning.2+ '''+ SELECT counts.breakdown_value AS `context.columns.breakdown_value`,+ tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,+ tuple(counts.views, counts.previous_views) AS `context.columns.views`,+ tuple(bounce.bounce_rate, bounce.previous_bounce_rate) AS `context.columns.bounce_rate`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT breakdown_value AS breakdown_value,+ uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,+ uniqIf(filtered_person_id, 0) AS previous_visitors,+ sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,+ sumIf(filtered_pageview_count, 0) AS previous_views+ FROM+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,+ count() AS filtered_pageview_count,+ replaceRegexpAll(replaceRegexpAll(replaceRegexpAll(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', ''), '\\/a\\/\\d+', '/a/:id'), '\\/b\\/\\d+', '/b/:id'), '\\/c\\/\\d+', '/c/:id') AS breakdown_value,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM+ (SELECT events.`$session_id_uuid`,+ events.distinct_id,+ events.event,+ events.person_id,+ events.properties,+ events.timestamp+ FROM events+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events+ LEFT JOIN+ (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)+ GROUP BY session_id,+ breakdown_value)+ GROUP BY breakdown_value) AS counts+ LEFT JOIN+ (SELECT breakdown_value AS breakdown_value,+ avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,+ avgIf(is_bounce, 0) AS previous_bounce_rate+ FROM+ (SELECT replaceRegexpAll(replaceRegexpAll(replaceRegexpAll(events__session.`$entry_pathname`, '\\/a\\/\\d+', '/a/:id'), '\\/b\\/\\d+', '/b/:id'), '\\/c\\/\\d+', '/c/:id') AS breakdown_value,+ any(events__session.`$is_bounce`) AS is_bounce,+ events__session.session_id AS session_id,+ min(events__session.`$start_timestamp`) AS start_timestamp+ FROM+ (SELECT events.`$session_id_uuid`,+ events.distinct_id,+ events.event,+ events.timestamp+ FROM events+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events+ LEFT JOIN+ (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,+ if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,+ toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,+ raw_sessions.session_id_v7 AS session_id_v7+ FROM raw_sessions+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)+ WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)+ GROUP BY session_id,+ breakdown_value)+ GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)+ WHERE isNotNull(counts.breakdown_value)+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 101+ OFFSET 0 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestWebStatsTableQueryRunner.test_bounce_rate_with_multiple_pathname_filters'''@@ -2086,8 +2178,6 @@use_hive_partitioning=0'''# ----<<<<<<< HEAD-=======# name: TestWebStatsTableQueryRunner.test_entry_bounce_rate.2'''SELECT breakdown_value AS `context.columns.breakdown_value`,@@ -2147,7 +2237,6 @@use_hive_partitioning=0'''# ---->>>>>>> master# name: TestWebStatsTableQueryRunner.test_entry_bounce_rate_one_user'''