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.

fix(warming): keep customer SQL query errors out of error tracking (#97568)

posthog[bot]60f6571863e6
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryFiltersMenu.tsx b/frontend/src/scenes/data-warehouse/editor/QueryFiltersMenu.tsx
index 33188b6c05aa..bb4072fcb881 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryFiltersMenu.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryFiltersMenu.tsx
@@ -12,7 +12,7 @@ import { EventPropertyFilters } from '~/queries/nodes/EventsNode/EventPropertyFi
import type { HogQLFilters, HogQLQuery } from '~/queries/schema/schema-general'
import { isHogQLQuery } from '~/queries/utils'
-import { queryUsesFiltersPlaceholder } from './sql-utils'
+import { filtersPlaceholderBindings, queryUsesFiltersPlaceholder } from './sql-utils'
import { sqlEditorLogic } from './sqlEditorLogic'
const hasDateRange = (filters?: HogQLFilters): boolean => {
@@ -27,6 +27,27 @@ const hasActiveFilters = (filters?: HogQLFilters): boolean => {
return hasDateRange(filters) || hasPropertyFilters(filters) || !!filters?.filterTestAccounts
}
+const filtersTooltip = ({
+ filtersMissingPlaceholder,
+ bindingsMissingTimestamp,
+ usesFiltersPlaceholder,
+}: {
+ filtersMissingPlaceholder: boolean
+ bindingsMissingTimestamp: boolean
+ usesFiltersPlaceholder: boolean
+}): string | undefined => {
+ if (filtersMissingPlaceholder) {
+ return "Filters are present, but this SQL query doesn't include a {filters} tag"
+ }
+ if (bindingsMissingTimestamp) {
+ return "This query's {filters(...)} bindings have no timestamp key, so it can't take a date filter"
+ }
+ if (!usesFiltersPlaceholder) {
+ return 'Insert {filters} into your SQL query to apply filters'
+ }
+ return undefined
+}
+
export function QueryFiltersMenu(): JSX.Element | null {
const { sourceQuery, queryInput } = useValues(sqlEditorLogic)
const { setSourceQuery, runQuery, insertTextAtCursor } = useActions(sqlEditorLogic)
@@ -39,8 +60,11 @@ export function QueryFiltersMenu(): JSX.Element | null {
const source = sourceQuery.source
const filters = source.filters
const hasFilters = hasActiveFilters(filters)
- const usesFiltersPlaceholder = queryUsesFiltersPlaceholder(queryInput ?? source.query)
+ const queryText = queryInput ?? source.query
+ const usesFiltersPlaceholder = queryUsesFiltersPlaceholder(queryText)
const filtersMissingPlaceholder = hasFilters && !usesFiltersPlaceholder
+ const bindings = filtersPlaceholderBindings(queryText)
+ const bindingsMissingTimestamp = bindings !== null && !bindings.includes('timestamp')
const setHogQLQuery = (query: HogQLQuery): void => {
const nextSourceQuery = {
@@ -70,7 +94,21 @@ export function QueryFiltersMenu(): JSX.Element | null {
className={`${CLICK_OUTSIDE_BLOCK_CLASS} w-[360px] max-w-[calc(100vw-2rem)] p-2 space-y-3`}
onClick={(event) => event.stopPropagation()}
>
- {filtersMissingPlaceholder ? (
+ {bindingsMissingTimestamp ? (
+ <div className="text-xs text-warning">
+ This query binds its own columns with <code>{'{filters(...)}'}</code> but has no{' '}
+ <code>timestamp</code> key, so it can't take a date filter. A dashboard applies its date
+ range to every tile, so the query fails once you add it to one. Bind your time column, for
+ example <code>{'{filters(created_at AS timestamp)}'}</code>, or write{' '}
+ <code>null AS timestamp</code> to exempt the query from date filtering.{' '}
+ <Link
+ to="https://posthog.com/docs/data-warehouse/sql/variables#applying-dashboard-filters"
+ target="_blank"
+ >
+ Learn more
+ </Link>
+ </div>
+ ) : filtersMissingPlaceholder ? (
<div className="text-xs text-warning">
Filters are set, but this SQL query doesn't include a <code>{'{filters}'}</code>{' '}
placeholder, so they aren't applied. Add <code>{'{filters}'}</code> to your{' '}
@@ -147,14 +185,16 @@ export function QueryFiltersMenu(): JSX.Element | null {
</span>
}
data-attr="sql-editor-filters-button"
- sideIcon={filtersMissingPlaceholder ? <IconWarning className="text-warning" /> : undefined}
- tooltip={
- filtersMissingPlaceholder
- ? "Filters are present, but this SQL query doesn't include a {filters} tag"
- : usesFiltersPlaceholder
- ? undefined
- : 'Insert {filters} into your SQL query to apply filters'
+ sideIcon={
+ filtersMissingPlaceholder || bindingsMissingTimestamp ? (
+ <IconWarning className="text-warning" />
+ ) : undefined
}
+ tooltip={filtersTooltip({
+ filtersMissingPlaceholder,
+ bindingsMissingTimestamp,
+ usesFiltersPlaceholder,
+ })}
>
Filters
</LemonButton>
diff --git a/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts b/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts
index d5761d5fe721..a93832ae807b 100644
--- a/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts
@@ -1,4 +1,9 @@
-import { normalizeIdentifier, parseQueryTablesAndColumns, queryUsesFiltersPlaceholder } from './sql-utils'
+import {
+ filtersPlaceholderBindings,
+ normalizeIdentifier,
+ parseQueryTablesAndColumns,
+ queryUsesFiltersPlaceholder,
+} from './sql-utils'
describe('sql-utils', () => {
describe('normalizeIdentifier', () => {
@@ -32,6 +37,30 @@ describe('sql-utils', () => {
})
})
+ describe('filtersPlaceholderBindings', () => {
+ test.each([
+ ['no placeholder', 'SELECT * FROM v', null],
+ ['plain placeholder is not column-bound', 'SELECT * FROM events WHERE {filters}', null],
+ ['single binding', 'SELECT * FROM v WHERE {filters(day AS timestamp)}', ['timestamp']],
+ [
+ 'several bindings, one quoted',
+ "SELECT * FROM v WHERE {filters(created_at AS timestamp, plan AS 'plan')}",
+ ['timestamp', 'plan'],
+ ],
+ ['null opt-out still binds the key', 'SELECT * FROM v WHERE {filters(null AS timestamp)}', ['timestamp']],
+ [
+ 'binding over a function call keeps the outer key',
+ 'SELECT * FROM v WHERE {filters(toDateTime(day, 0) AS timestamp)}',
+ ['timestamp'],
+ ],
+ ['no timestamp binding', "SELECT * FROM v WHERE {filters(plan AS 'plan')}", ['plan']],
+ ['commented-out placeholder', 'SELECT * FROM v -- {filters(day AS timestamp)}', null],
+ ['key case is kept', 'SELECT * FROM v WHERE {filters(day AS Timestamp)}', ['Timestamp']],
+ ])('%s', (_name, query, expected) => {
+ expect(filtersPlaceholderBindings(query)).toEqual(expected)
+ })
+ })
+
describe('parseQueryTablesAndColumns', () => {
it('returns empty object for null queryInput', async () => {
expect(await parseQueryTablesAndColumns(null)).toEqual({})
diff --git a/frontend/src/scenes/data-warehouse/editor/sql-utils.ts b/frontend/src/scenes/data-warehouse/editor/sql-utils.ts
index 165b7c146f7d..f60f607530e2 100644
--- a/frontend/src/scenes/data-warehouse/editor/sql-utils.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sql-utils.ts
@@ -2,6 +2,54 @@ import { analyzeTablesAndColumns } from './hogqlParserWorkerManager'
export { normalizeIdentifier } from './hogqlAst'
+const FILTERS_BOUND_PREFIX = '{filters('
+
+// Returns the index after the string literal or comment starting at `i`, or null when neither starts there.
+const skipNonCode = (query: string, i: number): number | null => {
+ const ch = query[i]
+
+ if (ch === "'" || ch === '"' || ch === '`') {
+ const quote = ch
+ let j = i + 1
+ while (j < query.length) {
+ if (query[j] === '\\') {
+ j += 2
+ continue
+ }
+ if (query[j] === quote && query[j + 1] === quote) {
+ j += 2
+ continue
+ }
+ if (query[j] === quote) {
+ return j + 1
+ }
+ j++
+ }
+ return j
+ }
+
+ if (ch === '-' && query[i + 1] === '-') {
+ let j = i + 2
+ while (j < query.length && query[j] !== '\n') {
+ j++
+ }
+ return j
+ }
+
+ if (ch === '/' && query[i + 1] === '*') {
+ let j = i + 2
+ while (j < query.length) {
+ if (query[j] === '*' && query[j + 1] === '/') {
+ return j + 2
+ }
+ j++
+ }
+ return j
+ }
+
+ return null
+}
+
export const queryUsesFiltersPlaceholder = (query: string | null): boolean => {
if (!query) {
return false
@@ -9,57 +57,109 @@ export const queryUsesFiltersPlaceholder = (query: string | null): boolean => {
let i = 0
while (i < query.length) {
- const ch = query[i]
+ const skipped = skipNonCode(query, i)
+ if (skipped !== null) {
+ i = skipped
+ continue
+ }
+
+ if (
+ query.startsWith('{filters}', i) ||
+ query.startsWith('{filters.', i) ||
+ query.startsWith(FILTERS_BOUND_PREFIX, i)
+ ) {
+ return true
+ }
+
+ i++
+ }
+
+ return false
+}
+
+const readBindingArgs = (query: string, start: number): { args: string[]; end: number } => {
+ const args: string[] = []
+ let current = ''
+ let depth = 0
+ let i = start
- if (ch === "'" || ch === '"' || ch === '`') {
- const quote = ch
+ while (i < query.length) {
+ const skipped = skipNonCode(query, i)
+ if (skipped !== null) {
+ current += query.slice(i, skipped)
+ i = skipped
+ continue
+ }
+
+ const ch = query[i]
+ if (ch === ')' && depth === 0) {
+ args.push(current)
+ return { args, end: i + 1 }
+ }
+ if (ch === ',' && depth === 0) {
+ args.push(current)
+ current = ''
i++
- while (i < query.length) {
- if (query[i] === '\\') {
- i += 2
- continue
- }
- if (query[i] === quote && query[i + 1] === quote) {
- i += 2
- continue
- }
- if (query[i] === quote) {
- i++
- break
- }
- i++
- }
continue
}
+ if (ch === '(') {
+ depth++
+ } else if (ch === ')') {
+ depth--
+ }
+ current += ch
+ i++
+ }
- if (ch === '-' && query[i + 1] === '-') {
- i += 2
- while (i < query.length && query[i] !== '\n') {
- i++
- }
+ args.push(current)
+ return { args, end: i }
+}
+
+const BINDING_KEY_REGEX = /\bas\s+(?:`([^`]+)`|"([^"]+)"|'([^']+)'|([A-Za-z_]\w*))\s*$/i
+
+const bindingKey = (arg: string): string | null => {
+ const match = BINDING_KEY_REGEX.exec(arg.trim())
+ if (!match) {
+ return null
+ }
+ return match[1] ?? match[2] ?? match[3] ?? match[4]
+}
+
+/**
+ * Keys bound by the column-bound `{filters(expr AS key, ...)}` placeholder, or null when the query
+ * uses no such placeholder. Keys keep their case, because the query runner matches them literally.
+ */
+export const filtersPlaceholderBindings = (query: string | null): string[] | null => {
+ if (!query) {
+ return null
+ }
+
+ let keys: string[] | null = null
+ let i = 0
+ while (i < query.length) {
+ const skipped = skipNonCode(query, i)
+ if (skipped !== null) {
+ i = skipped
continue
}
- if (ch === '/' && query[i + 1] === '*') {
- i += 2
- while (i < query.length) {
- if (query[i] === '*' && query[i + 1] === '/') {
- i += 2
- break
+ if (query.startsWith(FILTERS_BOUND_PREFIX, i)) {
+ const { args, end } = readBindingArgs(query, i + FILTERS_BOUND_PREFIX.length)
+ keys = keys ?? []
+ for (const arg of args) {
+ const key = bindingKey(arg)
+ if (key !== null) {
+ keys.push(key)
}
- i++
}
+ i = end
continue
}
- if (query.startsWith('{filters}', i) || query.startsWith('{filters.', i) || query.startsWith('{filters(', i)) {
- return true
- }
-
i++
}
- return false
+ return keys
}
export const parseQueryTablesAndColumns = async (
diff --git a/posthog/caching/test/test_warming.py b/posthog/caching/test/test_warming.py
index 2336b2d5ec33..b0e971e0f43f 100644
--- a/posthog/caching/test/test_warming.py
+++ b/posthog/caching/test/test_warming.py
@@ -3,6 +3,8 @@ from datetime import UTC, datetime, timedelta
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from posthog.hogql.errors import QueryError
+
from posthog.caching.warming import insights_to_keep_fresh, schedule_warming_for_teams_task, warm_insight_cache_task
from posthog.exceptions import ClickHouseAtCapacity
@@ -171,3 +173,20 @@ class TestWarmInsightCacheTask(APIBaseTest):
warm_insight_cache_task(insight.pk, None)
mock_capture_exception.assert_not_called()
+
+ @patch("posthog.caching.warming.capture_exception")
+ @patch("posthog.caching.warming.ph_scoped_capture")
+ @patch("posthog.caching.warming.process_query_dict", side_effect=QueryError("no timestamp binding"))
+ def test_query_errors_are_reported_as_an_event_instead_of_being_captured(
+ self, mock_process_query_dict, mock_ph_scoped_capture, mock_capture_exception
+ ):
+ insight = Insight.objects.create(team=self.team, query={"kind": "HogQLQuery", "query": "select 1"})
+ capture_ph_event = mock_ph_scoped_capture.return_value.__enter__.return_value
+
+ warm_insight_cache_task(insight.pk, None)
+
+ mock_capture_exception.assert_not_called()
+ capture_ph_event.assert_called_once()
+ assert capture_ph_event.call_args.kwargs["event"] == "cache warming - insight query error"
+ assert capture_ph_event.call_args.kwargs["properties"]["insight_id"] == insight.pk
+ assert capture_ph_event.call_args.kwargs["properties"]["error_code"] == "hogql_query_error"
diff --git a/posthog/caching/warming.py b/posthog/caching/warming.py
index 369eaed9d61d..ad8fa707fd4f 100644
--- a/posthog/caching/warming.py
+++ b/posthog/caching/warming.py
@@ -12,7 +12,7 @@ from celery.canvas import chain
from prometheus_client import Counter, Gauge
from posthog.hogql.constants import LimitContext
-from posthog.hogql.errors import TableAccessDeniedError
+from posthog.hogql.errors import ExposedHogQLError, TableAccessDeniedError
from posthog.api.services.query import process_query_dict
from posthog.caching.utils import largest_teams
@@ -297,5 +297,22 @@ def warm_insight_cache_task(insight_id: int, dashboard_id: Optional[int]):
error=e,
properties={"insight_id": insight.pk, "dashboard_id": dashboard_id},
)
+ elif isinstance(e, ExposedHogQLError):
+ # The query itself is wrong, and only its author can correct it. Report it as an
+ # event so it stays with the team instead of becoming an issue in our error tracking.
+ with ph_scoped_capture() as capture_ph_event:
+ capture_ph_event(
+ distinct_id=str(insight.team.uuid),
+ event="cache warming - insight query error",
+ properties={
+ "insight_id": insight.pk,
+ "insight_short_id": insight.short_id,
+ "dashboard_id": dashboard_id,
+ "team_id": insight.team_id,
+ "organization_id": str(insight.team.organization_id),
+ "error_code": e.code_name,
+ "error": str(e),
+ },
+ )
else:
capture_exception(e)