Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(flags): add a learn more link to the flag called SQL warning (#114264)

Phil Haack66fd67f8bf1d
diff --git a/frontend/src/lib/monaco/codeEditorLogic.tsx b/frontend/src/lib/monaco/codeEditorLogic.tsx
index a8f84cfe793e..fb3d1f3db26c 100644
--- a/frontend/src/lib/monaco/codeEditorLogic.tsx
+++ b/frontend/src/lib/monaco/codeEditorLogic.tsx
@@ -26,6 +26,7 @@ import {
import { setLatestVersionsOnQuery } from '~/queries/utils'
import type { FeatureFlagsSet } from '../logic/featureFlagLogic'
+import { noticeLink } from './noticeLink'
import { characterOffsetToUtf16 } from './offsets'
import { getContextSourceQuery } from './sourceQueryUtils'
@@ -234,6 +235,7 @@ export const codeEditorLogic = kea<codeEditorLogicType>([
hogQLAIFixPrompt: error.fix?.startsWith('ai_prompt:')
? error.fix.slice('ai_prompt:'.length)
: undefined,
+ code: noticeLink(error.url, props.monaco),
}
}
diff --git a/frontend/src/lib/monaco/noticeLink.test.ts b/frontend/src/lib/monaco/noticeLink.test.ts
new file mode 100644
index 000000000000..f1425d8fb330
--- /dev/null
+++ b/frontend/src/lib/monaco/noticeLink.test.ts
@@ -0,0 +1,35 @@
+import type { Monaco } from '@monaco-editor/react'
+
+import { noticeLink } from './noticeLink'
+
+describe('noticeLink', () => {
+ const monaco = { Uri: { parse: (value: string) => ({ parsed: value }) } } as unknown as Pick<Monaco, 'Uri'>
+
+ it('links an https url with the surrounding whitespace removed', () => {
+ expect(noticeLink(' https://example.com/announcement ', monaco)).toEqual({
+ value: 'Learn more',
+ target: { parsed: 'https://example.com/announcement' },
+ })
+ })
+
+ it.each([
+ ['a command url', 'command:editor.action.deleteLines'],
+ ['a javascript url', 'javascript:alert(1)'],
+ ['an http url', 'http://example.com/announcement'],
+ ['no url', undefined],
+ ])('adds no link for %s', (_name: string, url: string | undefined) => {
+ expect(noticeLink(url, monaco)).toBeUndefined()
+ })
+
+ it('adds no link when Monaco rejects an https url', () => {
+ const rejectingMonaco = {
+ Uri: {
+ parse: () => {
+ throw new Error('[UriError]')
+ },
+ },
+ } as unknown as Pick<Monaco, 'Uri'>
+
+ expect(noticeLink('https:////x', rejectingMonaco)).toBeUndefined()
+ })
+})
diff --git a/frontend/src/lib/monaco/noticeLink.ts b/frontend/src/lib/monaco/noticeLink.ts
new file mode 100644
index 000000000000..4146f3e90b14
--- /dev/null
+++ b/frontend/src/lib/monaco/noticeLink.ts
@@ -0,0 +1,31 @@
+import type { Monaco } from '@monaco-editor/react'
+import type { editor } from 'monaco-editor'
+
+import { isHttpsUrl } from 'lib/utils/url'
+
+/**
+ * The "Learn more" link that a notice's url adds to its marker hover, or undefined for no link.
+ *
+ * Monaco renders the marker message as plain text.
+ * The `code` field is the only marker field that Monaco renders as a link.
+ * Monaco runs a `command:` link as an editor command.
+ * Monaco assigns any other non-http link to window.location.
+ * Only an https URL becomes a link for these reasons.
+ */
+export function noticeLink(
+ url: string | null | undefined,
+ monaco: Pick<Monaco, 'Uri'> | null | undefined
+): editor.IMarkerData['code'] {
+ const trimmed = url?.trim()
+ if (!trimmed || !monaco || !isHttpsUrl(trimmed)) {
+ return undefined
+ }
+ try {
+ return { value: 'Learn more', target: monaco.Uri.parse(trimmed) }
+ } catch {
+ // Uri.parse rejects some URLs that isHttpsUrl accepts, such as `https:////x`.
+ // An exception here would stop every marker for the query.
+ // The catch drops only the link.
+ return undefined
+ }
+}
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index d249ca5f6652..c4f37cb41711 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -29966,6 +29966,10 @@
},
"start": {
"$ref": "#/definitions/integer"
+ },
+ "url": {
+ "description": "An https page with more detail about the notice. The editor links to it from the notice's hover.",
+ "type": "string"
}
},
"required": ["message"],
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index e9ae86194841..7e2ea2a1cb54 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -869,6 +869,8 @@ export interface HogQLNotice {
end?: integer
message: string
fix?: string
+ /** An https page with more detail about the notice. The editor links to it from the notice's hover. */
+ url?: string
}
export enum QueryIndexUsage {
diff --git a/posthog/hogql/metadata.py b/posthog/hogql/metadata.py
index 2dda0d78e4c5..abca856f1a2e 100644
--- a/posthog/hogql/metadata.py
+++ b/posthog/hogql/metadata.py
@@ -1,9 +1,12 @@
from dataclasses import replace
from typing import Literal, Optional, Union, cast
+from urllib.parse import urlparse
from django.conf import settings
import structlog
+import posthoganalytics
+from posthoganalytics import FeatureFlagResult
from pydantic import BaseModel
from posthog.schema import (
@@ -286,13 +289,13 @@ def _index_usage_enabled(team: Team) -> bool:
)
-def _flag_called_move_notices_enabled(team: Team) -> bool:
+def _flag_called_move_notices(team: Team) -> FeatureFlagResult | None:
"""Customers have not been told yet that $feature_flag_called is moving to posthog.flag_evaluations.
A warning about the move with no announcement behind it reads as a bug, so the flag stays off until the
- announcement goes out.
+ announcement goes out. The flag's payload holds the announcement's URL.
"""
- return feature_enabled_or_false(
+ return posthoganalytics.get_feature_flag_result(
"flag-called-move-notices",
str(team.uuid),
groups={"organization": str(team.organization_id), "project": str(team.id)},
@@ -303,13 +306,37 @@ def _flag_called_move_notices_enabled(team: Team) -> bool:
)
+def _flag_called_announcement_url(payload: object) -> str | None:
+ """The announcement URL from a flag payload of the shape `{"url": ...}`.
+
+ Clients of HogQL metadata, such as the SQL editor, turn `HogQLNotice.url` into a link.
+ Only an https URL with a host passes for this reason. The result has no surrounding whitespace.
+ """
+ url = payload.get("url") if isinstance(payload, dict) else None
+ if payload is None or (isinstance(payload, dict) and url is None):
+ return None
+ try:
+ parsed = urlparse(url.strip()) if isinstance(url, str) else None
+ except ValueError:
+ parsed = None
+ if parsed is not None and parsed.scheme == "https" and parsed.hostname:
+ return parsed.geturl()
+ logger.warning("hogql_flag_called_announcement_url_invalid", payload=repr(payload)[:200])
+ return None
+
+
def _flag_called_on_events_warnings(
hogql_ast: Union[ast.SelectQuery, ast.SelectSetQuery], context: HogQLContext, team: Team
) -> list[HogQLNotice]:
try:
- if not _flag_called_move_notices_enabled(team):
+ move_notices = _flag_called_move_notices(team)
+ if move_notices is None or not move_notices.enabled:
+ return []
+ warnings = flag_called_on_events_warnings(hogql_ast, context)
+ if not warnings:
return []
- return flag_called_on_events_warnings(hogql_ast, context)
+ url = _flag_called_announcement_url(move_notices.payload)
+ return [warning.model_copy(update={"url": url}) for warning in warnings]
except Exception:
# The warning is advisory. A query that compiles must not be reported as invalid because this
# check failed, and the caller turns any exception here into an invalid query.
diff --git a/posthog/hogql/test/test_metadata.py b/posthog/hogql/test/test_metadata.py
index e1b0f942b3b4..c24db491ed46 100644
--- a/posthog/hogql/test/test_metadata.py
+++ b/posthog/hogql/test/test_metadata.py
@@ -9,6 +9,7 @@ from django.test import override_settings
from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
+from posthoganalytics import FeatureFlagResult
from posthog.schema import (
HogLanguage,
@@ -39,6 +40,17 @@ from products.product_analytics.backend.facade.models import InsightVariable
from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
+_FLAG_CALLED_QUERY = "SELECT count() FROM events WHERE event = '$feature_flag_called'"
+
+
+def _move_notices(url: str | None = None, enabled: bool = True) -> FeatureFlagResult:
+ return FeatureFlagResult(
+ key="flag-called-move-notices", enabled=enabled, variant=None, payload={"url": url}, reason=None
+ )
+
+
+_MOVE_NOTICES_WITHOUT_URL = _move_notices()
+
class TestMetadata(ClickhouseTestMixin, APIBaseTest):
maxDiff = None
@@ -213,6 +225,7 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
"start": 7,
"end": 8,
"fix": None,
+ "url": None,
}
],
},
@@ -253,6 +266,7 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
"start": 0,
"end": 9,
"fix": None,
+ "url": None,
}
],
},
@@ -272,6 +286,7 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
"start": 0,
"end": 9,
"fix": None,
+ "url": None,
}
],
},
@@ -291,6 +306,7 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
"start": 4,
"end": 12,
"fix": None,
+ "url": None,
}
],
},
@@ -361,12 +377,12 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand(
[
- ("equals", "SELECT count() FROM events WHERE event = '$feature_flag_called'", True, 1),
+ ("equals", _FLAG_CALLED_QUERY, True, 1),
("in_list", "SELECT count() FROM events WHERE event IN ('$pageview', '$feature_flag_called')", True, 1),
("namespaced_table", "SELECT count() FROM posthog.events WHERE event = '$feature_flag_called'", True, 1),
("aliased_table", "SELECT count() FROM events AS e WHERE e.event = '$feature_flag_called'", True, 1),
("aliased_column", "SELECT event AS name FROM events WHERE name = '$feature_flag_called'", True, 1),
- ("table_not_available", "SELECT count() FROM events WHERE event = '$feature_flag_called'", False, 1),
+ ("table_not_available", _FLAG_CALLED_QUERY, False, 1),
(
"flag_evaluations_table",
"SELECT count() FROM posthog.flag_evaluations WHERE event = '$feature_flag_called'",
@@ -387,7 +403,32 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
True,
0,
),
- ("move_notices_off", "SELECT count() FROM events WHERE event = '$feature_flag_called'", True, 0, False),
+ ("move_notices_off", _FLAG_CALLED_QUERY, True, 0, _move_notices(enabled=False)),
+ ("move_notices_missing", _FLAG_CALLED_QUERY, True, 0, None),
+ (
+ "announcement_url",
+ _FLAG_CALLED_QUERY,
+ True,
+ 1,
+ _move_notices("https://example.com/announcement"),
+ "https://example.com/announcement",
+ ),
+ (
+ "padded_announcement_url",
+ _FLAG_CALLED_QUERY,
+ True,
+ 1,
+ _move_notices(" https://example.com/announcement "),
+ "https://example.com/announcement",
+ ),
+ (
+ "command_announcement_url",
+ _FLAG_CALLED_QUERY,
+ True,
+ 1,
+ _move_notices("command:editor.action.deleteLines"),
+ ),
+ ("malformed_announcement_url", _FLAG_CALLED_QUERY, True, 1, _move_notices("https://[broken")),
]
)
def test_metadata_warns_for_flag_called_read_from_events(
@@ -396,7 +437,8 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
query: str,
flag_evaluations_enabled: bool,
expected: int,
- move_notices_enabled: bool = True,
+ move_notices: FeatureFlagResult | None = _MOVE_NOTICES_WITHOUT_URL,
+ expected_url: str | None = None,
) -> None:
DataWarehouseSavedQuery.objects.create(
team=self.team,
@@ -417,7 +459,7 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
"products.feature_flags.backend.facade.flags.is_flag_evaluations_table_enabled",
return_value=flag_evaluations_enabled,
),
- patch("posthog.hogql.metadata.feature_enabled_or_false", return_value=move_notices_enabled),
+ patch("posthoganalytics.get_feature_flag_result", return_value=move_notices),
):
metadata = self._select(query)
@@ -425,10 +467,24 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
warnings = [w for w in metadata.warnings if w.message == FLAG_CALLED_ON_EVENTS_WARNING]
literal_start = query.rindex("'$feature_flag_called'")
self.assertEqual(
- [(w.start, w.end, w.fix) for w in warnings],
- [(literal_start, literal_start + len("'$feature_flag_called'"), None)] * expected,
+ [(w.start, w.end, w.fix, w.url) for w in warnings],
+ [(literal_start, literal_start + len("'$feature_flag_called'"), None, expected_url)] * expected,
)
+ def test_metadata_does_not_log_invalid_announcement_url_without_a_flag_called_literal(self) -> None:
+ with (
+ patch(
+ "products.feature_flags.backend.facade.flags.is_flag_evaluations_table_enabled",
+ return_value=True,
+ ),
+ patch("posthoganalytics.get_feature_flag_result", return_value=_move_notices("http://example.com")),
+ patch("posthog.hogql.metadata.logger") as mock_logger,
+ ):
+ metadata = self._select("SELECT 1")
+
+ self.assertTrue(metadata.isValid, metadata.errors)
+ mock_logger.warning.assert_not_called()
+
def test_metadata_warns_for_unknown_event_in_literal(self):
EventDefinition.objects.create(team=self.team, name="signed_up")
@@ -999,30 +1055,35 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
"start": 7,
"end": 16,
"fix": None,
+ "url": None,
},
{
"message": f"Cohort #{cohort.pk} can also be specified as '{cohort.name}'",
"start": 55,
"end": 55 + len(str(cohort.pk)),
"fix": f"'{cohort.name}'",
+ "url": None,
},
{
"message": "Field 'person_id' is of type 'UUID'",
"start": 35,
"end": 44,
"fix": None,
+ "url": None,
},
{
"message": f"Searching for cohort by name. Replace with numeric ID {cohort.pk} to protect against renaming.",
"start": 79 + len(str(cohort.pk)),
"end": 92 + len(str(cohort.pk)),
"fix": str(cohort.pk),
+ "url": None,
},
{
"message": "Field 'person_id' is of type 'UUID'",
"start": 59 + len(str(cohort.pk)),
"end": 68 + len(str(cohort.pk)),
"fix": None,
+ "url": None,
},
],
},
@@ -1055,12 +1116,14 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
"start": 11,
"end": 17,
"fix": None,
+ "url": None,
},
{
"message": f"Event property 'number' is of type 'Float'. This property is {materialized_notice}",
"start": 32,
"end": 38,
"fix": None,
+ "url": None,
},
],
},
@@ -1118,12 +1181,14 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
"start": 11,
"end": 17,
"fix": None,
+ "url": None,
},
{
"message": "Event property 'number' is of type 'Float'.",
"start": 32,
"end": 38,
"fix": None,
+ "url": None,
},
],
},
@@ -1198,7 +1263,15 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
"isValid": False,
"notices": [],
"warnings": [],
- "errors": [{"end": 15, "fix": None, "message": "Hog function `NONO` is not implemented", "start": 9}],
+ "errors": [
+ {
+ "end": 15,
+ "fix": None,
+ "message": "Hog function `NONO` is not implemented",
+ "start": 9,
+ "url": None,
+ }
+ ],
},
)
@@ -1210,8 +1283,10 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
| {
"query": "print(event, region)",
"isValid": True,
- "notices": [{"end": 11, "fix": None, "message": "Global variable: event", "start": 6}],
- "warnings": [{"end": 19, "fix": None, "message": "Unknown global variable: region", "start": 13}],
+ "notices": [{"end": 11, "fix": None, "message": "Global variable: event", "start": 6, "url": None}],
+ "warnings": [
+ {"end": 19, "fix": None, "message": "Unknown global variable: region", "start": 13, "url": None}
+ ],
"errors": [],
},
)
@@ -1234,7 +1309,15 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
metadata.dict()
| {
"isValid": False,
- "errors": [{"end": 17, "fix": None, "message": "Hog function `NONO` is not implemented", "start": 11}],
+ "errors": [
+ {
+ "end": 17,
+ "fix": None,
+ "message": "Hog function `NONO` is not implemented",
+ "start": 11,
+ "url": None,
+ }
+ ],
},
)
diff --git a/posthog/schema.py b/posthog/schema.py
index 4458d0647884..cd61ba7ce893 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -6129,6 +6129,12 @@ class HogQLNotice(BaseModel):
fix: str | None = None
message: str
start: int | None = None
+ url: str | None = Field(
+ default=None,
+ description=(
+ "An https page with more detail about the notice. The editor links to it from the notice's hover."
+ ),
+ )
class HogQLPropertyFilter(BaseModel):
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 04f963f9d642..092b02873bca 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -4915,6 +4915,8 @@ export interface HogQLNoticeApi {
fix?: string | null
message: string
start?: number | null
+ /** An https page with more detail about the notice. The editor links to it from the notice's hover. */
+ url?: string | null
}
export type PredicateFixActionApi = (typeof PredicateFixActionApi)[keyof typeof PredicateFixActionApi]
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 2cd405816e19..9287e901b56f 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -3841,6 +3841,8 @@ export interface HogQLNoticeApi {
fix?: string | null
message: string
start?: number | null
+ /** An https page with more detail about the notice. The editor links to it from the notice's hover. */
+ url?: string | null
}
export type PredicateFixActionApi = (typeof PredicateFixActionApi)[keyof typeof PredicateFixActionApi]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 68297353db28..cb1338bf8c8e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7268,6 +7268,8 @@ export namespace Schemas {
fix?: string | null;
message: string;
start?: number | null;
+ /** An https page with more detail about the notice. The editor links to it from the notice's hover. */
+ url?: string | null;
}
export type PredicateFixAction = typeof PredicateFixAction[keyof typeof PredicateFixAction];