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(hogql): resolve SQL insight date filters like other insights (#73833)

Thomas Obermüller76f2905222ad
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index abde6d38f30a..c2642c6e3fd8 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -481,6 +481,7 @@ export const FEATURE_FLAGS = {
SIGNUP_AA_TEST_4_WAY: 'signup-aa-test-4-way', // owner: @andehen #team-experiments multivariate=control,test-1,test-2,test-3
SLACK_DWH: 'slack-dwh', // owner: @MarconLP #team-warehouse-sources
SQL_EDITOR_VIM_MODE: 'sql-editor-vim-mode', // owner: @arthurdedeus
+ SQL_INSIGHT_DATE_FILTER_NOTICE: 'sql-insight-date-filter-notice', // owner: #team-product-analytics, gates the notice on SQL insights affected by the date filter resolution fix
SSE_DASHBOARDS: 'sse-dashboards', // owner: @aspicer #team-analytics-platform
STREAMLIT_APPS: 'streamlit-apps', // owner: @sakce
SUBSCRIPTION_AI_PROMPT: 'ai-subscriptions', // owner: #team-analytics-platform, gates AI prompt-based subscriptions
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/SqlInsightDateFilterNotice.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/SqlInsightDateFilterNotice.test.ts
new file mode 100644
index 000000000000..3291f5b787a1
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/SqlInsightDateFilterNotice.test.ts
@@ -0,0 +1,50 @@
+import { DateRange, HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
+
+import { isAffectedByDateFilterResolutionChange } from './SqlInsightDateFilterNotice'
+
+function hogQLQuery(query: string, filters?: HogQLQuery['filters']): HogQLQuery {
+ return { kind: NodeKind.HogQLQuery, query, filters }
+}
+
+const FILTERED_SQL = 'SELECT count() FROM demo WHERE ts >= {filters.dateRange.from} AND ts <= {filters.dateRange.to}'
+
+describe('isAffectedByDateFilterResolutionChange', () => {
+ it.each<[string, DateRange, boolean]>([
+ // affected: relative day-or-coarser date_from snaps to midnight
+ ['relative month start', { date_from: 'mStart', date_to: null }, true],
+ ['relative days with explicit datetime end', { date_from: '-7d', date_to: '2026-07-24T23:59:59' }, true],
+ ['relative week start', { date_from: 'wStart', date_to: null }, true],
+ // affected: open-ended ranges gain an end-of-today upper bound
+ ['absolute start with no end', { date_from: '2026-07-01', date_to: null }, true],
+ // affected: date-only or relative date_to now covers the whole day
+ ['date-only end', { date_from: '2026-07-01', date_to: '2026-07-24' }, true],
+ ['relative end', { date_from: '2026-07-01', date_to: '-3d' }, true],
+ // unaffected: "all" and sub-day rolling windows are exempt from the fix
+ ['all time with no end', { date_from: 'all', date_to: null }, false],
+ ['rolling hour window', { date_from: '-1h', date_to: null }, false],
+ ['rolling minute window', { date_from: '-30M', date_to: null }, false],
+ // unaffected: explicit datetimes are used verbatim
+ ['absolute start and datetime end', { date_from: '2026-07-01', date_to: '2026-07-24T23:59:59' }, false],
+ // unaffected: no date filter in use
+ ['empty date range', { date_from: null, date_to: null }, false],
+ // explicitDate disables the end-of-day snapping of date_to only; date_from still snaps
+ [
+ 'explicit date with date-only end',
+ { date_from: '2026-07-01', date_to: '2026-07-24', explicitDate: true },
+ false,
+ ],
+ ['explicit date with no end', { date_from: '2026-07-01', date_to: null, explicitDate: true }, true],
+ ['explicit date with relative preset', { date_from: '-1mStart', date_to: '-1mEnd', explicitDate: true }, true],
+ ])('%s -> %s', (_name, dateRange, expected) => {
+ expect(isAffectedByDateFilterResolutionChange(hogQLQuery(FILTERED_SQL, { dateRange }))).toBe(expected)
+ })
+
+ it('is unaffected without a filters placeholder or date range', () => {
+ expect(
+ isAffectedByDateFilterResolutionChange(
+ hogQLQuery('SELECT count() FROM demo', { dateRange: { date_from: 'mStart' } })
+ )
+ ).toBe(false)
+ expect(isAffectedByDateFilterResolutionChange(hogQLQuery(FILTERED_SQL))).toBe(false)
+ })
+})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/SqlInsightDateFilterNotice.tsx b/frontend/src/queries/nodes/DataVisualization/Components/SqlInsightDateFilterNotice.tsx
new file mode 100644
index 000000000000..5c58e230fa0c
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/SqlInsightDateFilterNotice.tsx
@@ -0,0 +1,62 @@
+import { useValues } from 'kea'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { HogQLQuery } from '~/queries/schema/schema-general'
+
+// Relative ranges in day-or-coarser units ("mStart", "-7d") now snap to the start of the day,
+// and open-ended ranges gain an end-of-today upper bound. Sub-day rolling windows ("-1h")
+// were exempted from both, so they are not part of the affected shape.
+const DAY_OR_COARSER_RELATIVE_REGEX = /^-?\d*[dwmqy](Start|End)?$/
+const SUB_DAY_RELATIVE_REGEX = /^-?\d*[hMs](Start|End)?$/
+const DATE_ONLY_REGEX = /^\d{4}-\d{1,2}-\d{1,2}$/
+
+/** Whether the SQL date filter resolution fix can produce different results for this query.
+ * Mirrors the affected shapes of ReplaceFilters in posthog/hogql/filters.py. */
+export function isAffectedByDateFilterResolutionChange(source: HogQLQuery): boolean {
+ if (!source.query?.includes('{filters')) {
+ return false
+ }
+ const dateRange = source.filters?.dateRange
+ if (!dateRange || (dateRange.date_from == null && dateRange.date_to == null)) {
+ return false
+ }
+ // "all" stays fully unbounded (no lower bound and no end-of-today cap), so it is unaffected
+ const openEndedWithBoundedStart =
+ dateRange.date_to == null &&
+ dateRange.date_from != null &&
+ dateRange.date_from !== 'all' &&
+ !SUB_DAY_RELATIVE_REGEX.test(dateRange.date_from)
+ const snappedDateFrom = dateRange.date_from != null && DAY_OR_COARSER_RELATIVE_REGEX.test(dateRange.date_from)
+ if (dateRange.explicitDate) {
+ // explicitDate disables end-of-day snapping of date_to only; date_from still snaps to midnight
+ return openEndedWithBoundedStart || snappedDateFrom
+ }
+ return (
+ openEndedWithBoundedStart ||
+ snappedDateFrom ||
+ (dateRange.date_to != null &&
+ (DATE_ONLY_REGEX.test(dateRange.date_to) || DAY_OR_COARSER_RELATIVE_REGEX.test(dateRange.date_to)))
+ )
+}
+
+export function SqlInsightDateFilterNotice({ source }: { source: HogQLQuery }): JSX.Element | null {
+ const { featureFlags } = useValues(featureFlagLogic)
+
+ if (
+ !featureFlags[FEATURE_FLAGS.SQL_INSIGHT_DATE_FILTER_NOTICE] ||
+ !isAffectedByDateFilterResolutionChange(source)
+ ) {
+ return null
+ }
+
+ return (
+ <LemonBanner type="info" dismissKey="sql-insight-date-filter-notice">
+ Date filters on SQL insights now match other insights: relative ranges start at midnight, and open-ended
+ ranges include all of today but nothing after. Results may differ slightly from before.
+ </LemonBanner>
+ )
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index 33dfa347c4af..feeaf008e739 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -39,6 +39,7 @@ import { SqlChart } from './Components/Charts/SqlChart'
import { TwoDimensionalHeatmap } from './Components/Heatmap/TwoDimensionalHeatmap'
import { seriesBreakdownLogic } from './Components/seriesBreakdownLogic'
import { SideBar } from './Components/SideBar'
+import { SqlInsightDateFilterNotice } from './Components/SqlInsightDateFilterNotice'
import { Table } from './Components/Table'
import { TableDisplay } from './Components/TableDisplay'
import { AddVariableButton } from './Components/Variables/AddVariableButton'
@@ -362,6 +363,8 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
</>
)}
+ <SqlInsightDateFilterNotice source={query.source} />
+
{!props.embedded && <VariablesForInsight />}
<div className="flex flex-1 flex-row gap-4">
diff --git a/posthog/hogql/filters.py b/posthog/hogql/filters.py
index cb300603b2e9..d5a38446bb53 100644
--- a/posthog/hogql/filters.py
+++ b/posthog/hogql/filters.py
@@ -1,4 +1,6 @@
+import re
import dataclasses
+from datetime import datetime
from typing import Optional, TypeVar, cast
from dateutil.parser import isoparse
@@ -21,11 +23,16 @@ from posthog.hogql.property import property_to_expr
from posthog.hogql.visitor import CloningVisitor
from posthog.models import Team
-from posthog.utils import relative_date_parse
+from posthog.utils import relative_date_parse_with_delta_mapping
T = TypeVar("T", bound=ast.Expr)
DEFAULT_TEAM = cast(Team, None)
+DATE_ONLY_REGEX = re.compile(r"^\d{4}-\d{1,2}-\d{1,2}$")
+# Relative units below one day ("-1h", "-30M") describe rolling windows (e.g. the logs and traces
+# live views) where snapping to calendar boundaries would change the window's meaning.
+SUB_DAY_DELTA_KEYS = frozenset(["hours", "minutes", "seconds"])
+
@dataclasses.dataclass
class CompareOperationWrapper:
@@ -52,6 +59,92 @@ class ReplaceFilters(CloningVisitor):
self.database = database
self.selects: list[ast.SelectQuery] = []
self.compare_operations: list[CompareOperationWrapper] = []
+ self._now: Optional[datetime] = None
+
+ def _current_time(self) -> datetime:
+ # One shared "now" so both bounds of the range resolve against the same instant
+ if self._now is None:
+ self._now = datetime.now(tz=self.team.timezone_info)
+ return self._now
+
+ def _parse_date_from(self) -> tuple[Optional[datetime], Optional[dict[str, int]]]:
+ date_from = self.filters.dateRange.date_from if self.filters and self.filters.dateRange else None
+ if date_from is None or date_from == "all":
+ return None, None
+ parsed_date, delta_mapping, _position = relative_date_parse_with_delta_mapping(
+ date_from,
+ self.team.timezone_info,
+ now=self._current_time(),
+ team_week_start_day=self.team.week_start_day,
+ )
+ return parsed_date, delta_mapping
+
+ def _resolve_date_from(self) -> Optional[datetime]:
+ """Lower bound of the date range, resolved the way QueryDateRange resolves it for insights:
+ relative values in day-or-coarser units ("mStart", "-7d") snap to the start of the day instead
+ of keeping the current time of day. Sub-day units ("-1h") stay exact rolling windows, explicit
+ datetimes are used verbatim, and "all" means no lower bound."""
+ parsed_date, delta_mapping = self._parse_date_from()
+ if parsed_date is None:
+ return None
+ if delta_mapping is None or SUB_DAY_DELTA_KEYS & delta_mapping.keys():
+ return parsed_date
+ return parsed_date.replace(hour=0, minute=0, second=0, microsecond=0)
+
+ def _open_ended_date_to(self) -> Optional[datetime]:
+ """A missing date_to means "up to now" when a date filter is in use — matching how insights
+ resolve the same range instead of leaving the query unbounded (which would include
+ future-dated rows). With no date filter at all, with date_from="all" (which promises the
+ whole table, including future-dated warehouse rows), or with a sub-day rolling date_from
+ ("-1h"), the range stays open-ended."""
+ date_range = self.filters.dateRange if self.filters else None
+ if date_range is None or date_range.date_from is None or date_range.date_from == "all":
+ return None
+ _parsed_date, delta_mapping = self._parse_date_from()
+ if delta_mapping is not None and SUB_DAY_DELTA_KEYS & delta_mapping.keys():
+ return None
+ return self._current_time()
+
+ def _resolve_date_to(self) -> tuple[Optional[datetime], bool]:
+ """Upper bound of the date range, resolved the way QueryDateRange resolves it for
+ day-interval insights: relative and date-only values snap to the end of the day, and a
+ missing date_to resolves to the end of today, so ranges like "This month" include all of
+ today but nothing from the future. Explicit datetimes are used verbatim, relative sub-day
+ values ("-1h") stay exact, and explicitDate disables the end-of-day snapping.
+
+ Also returns whether the bound was snapped to an end-of-day instant. Snapped bounds land
+ on 23:59:59.999999 and must be compared inclusively to cover the whole day; exact bounds
+ keep the strict comparison so half-open windows (like the logs count-ranges bucket ends,
+ documented as exclusive) don't gain their boundary row."""
+ date_range = self.filters.dateRange if self.filters else None
+ date_to = date_range.date_to if date_range else None
+ explicit_date = bool(date_range.explicitDate) if date_range else False
+
+ parsed_date: Optional[datetime]
+ if date_to is None:
+ parsed_date = self._open_ended_date_to()
+ else:
+ if not DATE_ONLY_REGEX.match(date_to):
+ try:
+ verbatim_date = isoparse(date_to)
+ if verbatim_date.tzinfo is None:
+ verbatim_date = verbatim_date.replace(tzinfo=self.team.timezone_info)
+ return verbatim_date, False
+ except ValueError:
+ pass
+ parsed_date, delta_mapping, _position = relative_date_parse_with_delta_mapping(
+ date_to,
+ self.team.timezone_info,
+ now=self._current_time(),
+ team_week_start_day=self.team.week_start_day,
+ )
+ if delta_mapping is not None and SUB_DAY_DELTA_KEYS & delta_mapping.keys():
+ return parsed_date, False
+ if parsed_date is None:
+ return None, False
+ if explicit_date:
+ return parsed_date, False
+ return parsed_date.replace(hour=23, minute=59, second=59, microsecond=999999), True
def _resolve_table(self, chain: list) -> Optional[Table]:
"""Resolve an AST field chain to the underlying database table, or None if not found."""
@@ -142,36 +235,23 @@ class ReplaceFilters(CloningVisitor):
if found_groups:
timestamp_field = ast.Field(chain=["created_at"])
- dateTo = self.filters.dateRange.date_to if self.filters.dateRange else None
- if dateTo is not None:
- try:
- parsed_date = isoparse(dateTo)
- if parsed_date.tzinfo is None:
- parsed_date = parsed_date.replace(tzinfo=self.team.timezone_info)
- except ValueError:
- parsed_date = relative_date_parse(dateTo, self.team.timezone_info)
+ date_to, date_to_inclusive = self._resolve_date_to()
+ if date_to is not None:
exprs.append(
ast.CompareOperation(
- op=ast.CompareOperationOp.Lt,
+ op=ast.CompareOperationOp.LtEq if date_to_inclusive else ast.CompareOperationOp.Lt,
left=timestamp_field,
- right=ast.Constant(value=parsed_date),
+ right=ast.Constant(value=date_to),
)
)
- # limit to the last 30d by default
- dateFrom = self.filters.dateRange.date_from if self.filters.dateRange else None
- if dateFrom is not None and dateFrom != "all":
- try:
- parsed_date = isoparse(dateFrom)
- if parsed_date.tzinfo is None:
- parsed_date = parsed_date.replace(tzinfo=self.team.timezone_info)
- except ValueError:
- parsed_date = relative_date_parse(dateFrom, self.team.timezone_info)
+ date_from = self._resolve_date_from()
+ if date_from is not None:
exprs.append(
ast.CompareOperation(
op=ast.CompareOperationOp.GtEq,
left=timestamp_field,
- right=ast.Constant(value=parsed_date),
+ right=ast.Constant(value=date_from),
)
)
@@ -193,16 +273,9 @@ class ReplaceFilters(CloningVisitor):
assert self.filters is not None
- dateFrom = self.filters.dateRange.date_from if self.filters.dateRange else None
- if dateFrom is not None and dateFrom != "all":
- try:
- parsed_date = isoparse(dateFrom)
- if parsed_date.tzinfo is None:
- parsed_date = parsed_date.replace(tzinfo=self.team.timezone_info)
- except ValueError:
- parsed_date = relative_date_parse(dateFrom, self.team.timezone_info)
-
- return ast.Constant(value=parsed_date)
+ date_from = self._resolve_date_from()
+ if date_from is not None:
+ return ast.Constant(value=date_from)
else:
compare_op_wrapper.skip = True
return ast.Constant(value=True)
@@ -215,15 +288,9 @@ class ReplaceFilters(CloningVisitor):
assert self.filters is not None
- dateTo = self.filters.dateRange.date_to if self.filters.dateRange else None
- if dateTo is not None:
- try:
- parsed_date = isoparse(dateTo)
- if parsed_date.tzinfo is None:
- parsed_date = parsed_date.replace(tzinfo=self.team.timezone_info)
- except ValueError:
- parsed_date = relative_date_parse(dateTo, self.team.timezone_info)
- return ast.Constant(value=parsed_date)
+ date_to, _date_to_inclusive = self._resolve_date_to()
+ if date_to is not None:
+ return ast.Constant(value=date_to)
else:
compare_op_wrapper.skip = True
return ast.Constant(value=True)
diff --git a/posthog/hogql/test/__snapshots__/test_query.ambr b/posthog/hogql/test/__snapshots__/test_query.ambr
index 83ed5c630854..4d0760e72085 100644
--- a/posthog/hogql/test/__snapshots__/test_query.ambr
+++ b/posthog/hogql/test/__snapshots__/test_query.ambr
@@ -217,14 +217,14 @@
-- ClickHouse
SELECT events.event AS event, events.distinct_id AS distinct_id
FROM events
- WHERE and(equals(events.team_id, 99999), equals(events.distinct_id, %(hogql_val_0)s), and(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_1)s), ''), 'null'), '^"|"$', ''), %(hogql_val_2)s), 0), less(events.timestamp, toDateTime64('2020-01-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC'))))
+ WHERE and(equals(events.team_id, 99999), equals(events.distinct_id, %(hogql_val_0)s), and(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_1)s), ''), 'null'), '^"|"$', ''), %(hogql_val_2)s), 0), lessOrEquals(events.timestamp, toDateTime64('2020-01-02 23:59:59.999999', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC'))))
LIMIT 100
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, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0
-- HogQL
SELECT event, distinct_id
FROM events
- WHERE and(equals(distinct_id, 'RANDOM_TEST_ID::UUID'), and(equals(properties.index, '4'), less(timestamp, toDateTime('2020-01-02 00:00:00.000000')), greaterOrEquals(timestamp, toDateTime('2020-01-01 00:00:00.000000'))))
+ WHERE and(equals(distinct_id, 'RANDOM_TEST_ID::UUID'), and(equals(properties.index, '4'), lessOrEquals(timestamp, toDateTime('2020-01-02 23:59:59.999999')), greaterOrEquals(timestamp, toDateTime('2020-01-01 00:00:00.000000'))))
LIMIT 100
'''
# ---
@@ -233,7 +233,7 @@
SELECT event, distinct_id
FROM events
- WHERE and(equals(distinct_id, 'RANDOM_TEST_ID::UUID'), and(equals(properties.index, '4'), less(timestamp, toDateTime('2020-01-02 00:00:00.000000')), greaterOrEquals(timestamp, toDateTime('2020-01-01 00:00:00.000000'))))
+ WHERE and(equals(distinct_id, 'RANDOM_TEST_ID::UUID'), and(equals(properties.index, '4'), lessOrEquals(timestamp, toDateTime('2020-01-02 23:59:59.999999')), greaterOrEquals(timestamp, toDateTime('2020-01-01 00:00:00.000000'))))
LIMIT 100
'''
# ---
@@ -251,14 +251,14 @@
-- ClickHouse
SELECT events.event AS event, events.distinct_id AS distinct_id
FROM events_json AS events
- WHERE and(equals(events.team_id, 99999), equals(events.distinct_id, %(hogql_val_0)s), and(ifNull(equals(if(notEquals(toJSONString(events.properties.^index), '{}'), toJSONString(events.properties.^index), if(isNull(events.properties.index), NULL, if(startsWith(dynamicType(events.properties.index), 'DateTime'), replaceOne(toString(events.properties.index), ' ', 'T'), if(or(startsWith(dynamicType(events.properties.index), 'Array'), startsWith(dynamicType(events.properties.index), 'Map'), startsWith(dynamicType(events.properties.index), 'Tuple')), toJSONString(events.properties.index), toString(events.properties.index))))), %(hogql_val_1)s), 0), less(events.timestamp, toDateTime64('2020-01-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC'))))
+ WHERE and(equals(events.team_id, 99999), equals(events.distinct_id, %(hogql_val_0)s), and(ifNull(equals(if(notEquals(toJSONString(events.properties.^index), '{}'), toJSONString(events.properties.^index), if(isNull(events.properties.index), NULL, if(startsWith(dynamicType(events.properties.index), 'DateTime'), replaceOne(toString(events.properties.index), ' ', 'T'), if(or(startsWith(dynamicType(events.properties.index), 'Array'), startsWith(dynamicType(events.properties.index), 'Map'), startsWith(dynamicType(events.properties.index), 'Tuple')), toJSONString(events.properties.index), toString(events.properties.index))))), %(hogql_val_1)s), 0), lessOrEquals(events.timestamp, toDateTime64('2020-01-02 23:59:59.999999', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC'))))
LIMIT 100
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, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0
-- HogQL
SELECT event, distinct_id
FROM events
- WHERE and(equals(distinct_id, 'RANDOM_TEST_ID::UUID'), and(equals(properties.index, '4'), less(timestamp, toDateTime('2020-01-02 00:00:00.000000')), greaterOrEquals(timestamp, toDateTime('2020-01-01 00:00:00.000000'))))
+ WHERE and(equals(distinct_id, 'RANDOM_TEST_ID::UUID'), and(equals(properties.index, '4'), lessOrEquals(timestamp, toDateTime('2020-01-02 23:59:59.999999')), greaterOrEquals(timestamp, toDateTime('2020-01-01 00:00:00.000000'))))
LIMIT 100
'''
# ---
@@ -267,7 +267,7 @@
SELECT event, distinct_id
FROM events
- WHERE and(equals(distinct_id, 'RANDOM_TEST_ID::UUID'), and(equals(properties.index, '4'), less(timestamp, toDateTime('2020-01-02 00:00:00.000000')), greaterOrEquals(timestamp, toDateTime('2020-01-01 00:00:00.000000'))))
+ WHERE and(equals(distinct_id, 'RANDOM_TEST_ID::UUID'), and(equals(properties.index, '4'), lessOrEquals(timestamp, toDateTime('2020-01-02 23:59:59.999999')), greaterOrEquals(timestamp, toDateTime('2020-01-01 00:00:00.000000'))))
LIMIT 100
'''
# ---
@@ -328,14 +328,14 @@
FROM raw_sessions
WHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('today', 6, 'UTC'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('today', 6, 'UTC'), toIntervalDay(3))))
GROUP BY raw_sessions.session_id_v7) AS sessions
- WHERE and(less(sessions.`$start_timestamp`, toDateTime64('today', 6, 'UTC')), greaterOrEquals(sessions.`$start_timestamp`, toDateTime64('today', 6, 'UTC')))
+ WHERE and(lessOrEquals(sessions.`$start_timestamp`, toDateTime64('today', 6, 'UTC')), greaterOrEquals(sessions.`$start_timestamp`, toDateTime64('today', 6, 'UTC')))
LIMIT 100
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, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0
-- HogQL
SELECT session_id, $entry_current_url
FROM sessions
- WHERE and(less($start_timestamp, toDateTime('2024-07-06 00:00:00.000000')), greaterOrEquals($start_timestamp, toDateTime('2024-07-04 00:00:00.000000')))
+ WHERE and(lessOrEquals($start_timestamp, toDateTime('2024-07-06 23:59:59.999999')), greaterOrEquals($start_timestamp, toDateTime('2024-07-04 00:00:00.000000')))
LIMIT 100
'''
# ---
@@ -344,7 +344,7 @@
SELECT session_id, $entry_current_url
FROM sessions
- WHERE and(less($start_timestamp, toDateTime('2024-07-06 00:00:00.000000')), greaterOrEquals($start_timestamp, toDateTime('2024-07-04 00:00:00.000000')))
+ WHERE and(lessOrEquals($start_timestamp, toDateTime('2024-07-06 23:59:59.999999')), greaterOrEquals($start_timestamp, toDateTime('2024-07-04 00:00:00.000000')))
LIMIT 100
'''
# ---
diff --git a/posthog/hogql/test/test_filters.py b/posthog/hogql/test/test_filters.py
index 8ab06706d56b..5bee69d14068 100644
--- a/posthog/hogql/test/test_filters.py
+++ b/posthog/hogql/test/test_filters.py
@@ -1,7 +1,10 @@
from typing import Any, Optional
+from freezegun import freeze_time
from posthog.test.base import BaseTest
+from parameterized import parameterized
+
from posthog.schema import DateRange, EventPropertyFilter, GroupPropertyFilter, HogQLFilters, PersonPropertyFilter
from posthog.hogql import ast
@@ -77,16 +80,21 @@ class TestFilters(BaseTest):
replace_filters(select, HogQLFilters(dateRange=DateRange(date_from="2020-02-02")), self.team)
def test_replace_filters_date_range(self):
- select = replace_filters(
- self._parse_select("SELECT event FROM events where {filters}"),
- HogQLFilters(dateRange=DateRange(date_from="2020-02-02")),
- self.team,
- )
- self.assertEqual(
- self._print_ast(select),
- f"SELECT event FROM events WHERE greaterOrEquals(timestamp, toDateTime('2020-02-02 00:00:00.000000')) LIMIT {MAX_SELECT_RETURNED_ROWS}",
- )
-
+ with freeze_time("2020-02-15T13:37:42Z"):
+ # open-ended range: bounded at the end of today instead of including future-dated rows
+ select = replace_filters(
+ self._parse_select("SELECT event FROM events where {filters}"),
+ HogQLFilters(dateRange=DateRange(date_from="2020-02-02")),
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ "SELECT event FROM events WHERE "
+ "and(lessOrEquals(timestamp, toDateTime('2020-02-15 23:59:59.999999')), "
+ f"greaterOrEquals(timestamp, toDateTime('2020-02-02 00:00:00.000000'))) LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ # a date-only upper bound covers that whole day
select = replace_filters(
self._parse_select("SELECT event FROM events where {filters}"),
HogQLFilters(dateRange=DateRange(date_to="2020-02-02")),
@@ -94,9 +102,10 @@ class TestFilters(BaseTest):
)
self.assertEqual(
self._print_ast(select),
- f"SELECT event FROM events WHERE less(timestamp, toDateTime('2020-02-02 00:00:00.000000')) LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ f"SELECT event FROM events WHERE lessOrEquals(timestamp, toDateTime('2020-02-02 23:59:59.999999')) LIMIT {MAX_SELECT_RETURNED_ROWS}",
)
+ # an explicit datetime upper bound is used verbatim and compared exclusively
select = replace_filters(
self._parse_select("SELECT event FROM events where {filters}"),
HogQLFilters(dateRange=DateRange(date_from="2020-02-02", date_to="2020-02-03 23:59:59")),
@@ -142,6 +151,160 @@ class TestFilters(BaseTest):
f"greaterOrEquals(timestamp, toDateTime('2020-02-02 00:00:00.000000'))) LIMIT {MAX_SELECT_RETURNED_ROWS}",
)
+ @parameterized.expand(
+ [
+ ("mStart", "2020-02-01 00:00:00.000000"),
+ ("-7d", "2020-02-08 00:00:00.000000"),
+ ("yStart", "2020-01-01 00:00:00.000000"),
+ ("wStart", "2020-02-09 00:00:00.000000"), # frozen date is a Saturday; weeks start on Sunday by default
+ ]
+ )
+ def test_replace_filters_relative_date_from_snaps_to_start_of_day(self, date_from: str, expected: str):
+ # Regression: relative presets used to keep the wall-clock time of day, so "This month" on a
+ # dashboard silently dropped rows between midnight and the current time on the first day
+ with freeze_time("2020-02-15T13:37:42Z"):
+ select = replace_filters(
+ self._parse_select("SELECT event FROM events WHERE timestamp >= {filters.dateRange.from}"),
+ HogQLFilters(dateRange=DateRange(date_from=date_from)),
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ f"SELECT event FROM events WHERE greaterOrEquals(timestamp, toDateTime('{expected}')) LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ def test_replace_filters_date_from_respects_week_start_day(self):
+ self.team.week_start_day = 1
+ self.team.save()
+ with freeze_time("2020-02-15T13:37:42Z"): # a Saturday
+ select = replace_filters(
+ self._parse_select("SELECT event FROM events WHERE timestamp >= {filters.dateRange.from}"),
+ HogQLFilters(dateRange=DateRange(date_from="wStart")),
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ f"SELECT event FROM events WHERE greaterOrEquals(timestamp, toDateTime('2020-02-10 00:00:00.000000')) LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ def test_replace_filters_sub_day_date_from_stays_rolling(self):
+ # Sub-day ranges ("last 1 hour" in logs/traces) must keep their exact lower bound and stay
+ # open-ended — snapping them to calendar boundaries would change the window's meaning
+ with freeze_time("2020-02-15T13:37:42Z"):
+ select = replace_filters(
+ self._parse_select("SELECT event FROM events where {filters}"),
+ HogQLFilters(dateRange=DateRange(date_from="-1h")),
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ f"SELECT event FROM events WHERE greaterOrEquals(timestamp, toDateTime('2020-02-15 12:37:42.000000')) LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ @parameterized.expand(
+ [
+ (None, "2020-02-15 23:59:59.999999"), # open-ended → end of today
+ ("-1mEnd", "2020-01-31 23:59:59.999999"), # relative → end of that day
+ ("2020-02-10", "2020-02-10 23:59:59.999999"), # date-only → end of that day
+ ("2020-02-10 12:34:56", "2020-02-10 12:34:56.000000"), # explicit datetime → verbatim
+ ("-30M", "2020-02-15 13:07:42.000000"), # sub-day relative → exact rolling bound, no snapping
+ ]
+ )
+ def test_replace_filters_date_to_resolution(self, date_to: Optional[str], expected: str):
+ # Regression: an unset date_to used to drop the upper bound entirely, so "This month" and
+ # "Last 7 days" included future-dated rows
+ with freeze_time("2020-02-15T13:37:42Z"):
+ select = replace_filters(
+ self._parse_select("SELECT event FROM events WHERE timestamp <= {filters.dateRange.to}"),
+ HogQLFilters(dateRange=DateRange(date_from="-7d", date_to=date_to)),
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ f"SELECT event FROM events WHERE lessOrEquals(timestamp, toDateTime('{expected}')) LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ def test_replace_filters_open_ended_date_to_uses_team_timezone(self):
+ self.team.timezone = "America/New_York"
+ self.team.save()
+ with freeze_time("2020-02-15T03:00:00Z"): # still Feb 14 in New York
+ select = replace_filters(
+ self._parse_select("SELECT event FROM events WHERE timestamp <= {filters.dateRange.to}"),
+ HogQLFilters(dateRange=DateRange(date_from="-7d")),
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ f"SELECT event FROM events WHERE lessOrEquals(timestamp, toDateTime('2020-02-14 23:59:59.999999')) LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ @parameterized.expand(
+ [
+ ("2020-02-10", "2020-02-10 00:00:00.000000"), # date-only stays at midnight
+ (None, "2020-02-15 13:37:42.000000"), # open-ended resolves to now verbatim
+ ]
+ )
+ def test_replace_filters_date_to_with_explicit_date(self, date_to: Optional[str], expected: str):
+ with freeze_time("2020-02-15T13:37:42Z"):
+ select = replace_filters(
+ self._parse_select("SELECT event FROM events WHERE timestamp <= {filters.dateRange.to}"),
+ HogQLFilters(dateRange=DateRange(date_from="2020-02-01", date_to=date_to, explicitDate=True)),
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ f"SELECT event FROM events WHERE lessOrEquals(timestamp, toDateTime('{expected}')) LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ @parameterized.expand(
+ [
+ ("no_date_range", HogQLFilters(properties=[])),
+ ("empty_date_range", HogQLFilters(dateRange=DateRange())),
+ ("rolling_date_from", HogQLFilters(dateRange=DateRange(date_from="-1h"))),
+ ("all_time_date_from", HogQLFilters(dateRange=DateRange(date_from="all"))),
+ ]
+ )
+ def test_replace_filters_date_to_placeholder_skipped_when_open_ended(self, _name: str, filters: HogQLFilters):
+ select = replace_filters(
+ self._parse_select("SELECT event FROM events WHERE timestamp <= {filters.dateRange.to}"),
+ filters,
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ f"SELECT event FROM events WHERE equals(true, true) LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ def test_replace_filters_all_time_stays_unbounded(self):
+ # "All time" must not gain an end-of-today cap: unlike QueryDateRange (where "all" means
+ # "since the first event"), here it promises the whole table, including future-dated
+ # warehouse rows
+ with freeze_time("2020-02-15T13:37:42Z"):
+ select = replace_filters(
+ self._parse_select("SELECT event FROM events where {filters}"),
+ HogQLFilters(dateRange=DateRange(date_from="all")),
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ f"SELECT event FROM events WHERE true LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
+ def test_replace_filters_this_month_preset(self):
+ # The exact shape a dashboard's "This month" filter produces: date_from="mStart", no date_to
+ with freeze_time("2020-02-15T13:37:42Z"):
+ select = replace_filters(
+ self._parse_select("SELECT event FROM events where {filters}"),
+ HogQLFilters(dateRange=DateRange(date_from="mStart")),
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ "SELECT event FROM events WHERE "
+ "and(lessOrEquals(timestamp, toDateTime('2020-02-15 23:59:59.999999')), "
+ f"greaterOrEquals(timestamp, toDateTime('2020-02-01 00:00:00.000000'))) LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
+
def test_replace_filters_event_property(self):
select = replace_filters(
self._parse_select("SELECT event FROM events where {filters}"),
@@ -227,15 +390,18 @@ class TestFilters(BaseTest):
)
def test_replace_filters_groups_date_range(self):
- select = replace_filters(
- self._parse_select("SELECT group_key FROM groups where {filters}"),
- HogQLFilters(dateRange=DateRange(date_from="2020-02-02")),
- self.team,
- )
- self.assertEqual(
- self._print_ast(select),
- f"SELECT group_key FROM groups WHERE greaterOrEquals(created_at, toDateTime('2020-02-02 00:00:00.000000')) LIMIT {MAX_SELECT_RETURNED_ROWS}",
- )
+ with freeze_time("2020-02-15T13:37:42Z"):
+ select = replace_filters(
+ self._parse_select("SELECT group_key FROM groups where {filters}"),
+ HogQLFilters(dateRange=DateRange(date_from="2020-02-02")),
+ self.team,
+ )
+ self.assertEqual(
+ self._print_ast(select),
+ "SELECT group_key FROM groups WHERE "
+ "and(lessOrEquals(created_at, toDateTime('2020-02-15 23:59:59.999999')), "
+ f"greaterOrEquals(created_at, toDateTime('2020-02-02 00:00:00.000000'))) LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ )
select = replace_filters(
self._parse_select("SELECT group_key FROM groups where {filters}"),
@@ -244,9 +410,10 @@ class TestFilters(BaseTest):
)
self.assertEqual(
self._print_ast(select),
- f"SELECT group_key FROM groups WHERE less(created_at, toDateTime('2020-02-02 00:00:00.000000')) LIMIT {MAX_SELECT_RETURNED_ROWS}",
+ f"SELECT group_key FROM groups WHERE lessOrEquals(created_at, toDateTime('2020-02-02 23:59:59.999999')) LIMIT {MAX_SELECT_RETURNED_ROWS}",
)
+ # an explicit datetime upper bound is used verbatim and compared exclusively
select = replace_filters(
self._parse_select("SELECT group_key FROM groups where {filters}"),
HogQLFilters(dateRange=DateRange(date_from="2020-02-02", date_to="2020-02-03 23:59:59")),
@@ -297,22 +464,24 @@ class TestFilters(BaseTest):
)
def test_replace_filters_groups_date_and_properties(self):
- select = replace_filters(
- self._parse_select("SELECT group_key FROM groups where {filters}"),
- HogQLFilters(
- dateRange=DateRange(date_from="2020-02-02"),
- properties=[
- GroupPropertyFilter(
- key="company_name", operator="exact", value="PostHog", type="group", group_type_index=0
- )
- ],
- ),
- self.team,
- )
+ with freeze_time("2020-02-15T13:37:42Z"):
+ select = replace_filters(
+ self._parse_select("SELECT group_key FROM groups where {filters}"),
+ HogQLFilters(
+ dateRange=DateRange(date_from="2020-02-02"),
+ properties=[
+ GroupPropertyFilter(
+ key="company_name", operator="exact", value="PostHog", type="group", group_type_index=0
+ )
+ ],
+ ),
+ self.team,
+ )
self.assertEqual(
self._print_ast(select),
"SELECT group_key FROM groups WHERE "
"and(equals(properties.company_name, 'PostHog'), "
+ "lessOrEquals(created_at, toDateTime('2020-02-15 23:59:59.999999')), "
f"greaterOrEquals(created_at, toDateTime('2020-02-02 00:00:00.000000'))) LIMIT {MAX_SELECT_RETURNED_ROWS}",
)
diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.py
index 17711971a080..074f1b1048c9 100644
--- a/posthog/hogql_queries/hogql_query_runner.py
+++ b/posthog/hogql_queries/hogql_query_runner.py
@@ -178,6 +178,11 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
self.query.filters.dateRange = DateRange()
self.query.filters.dateRange.date_to = dashboard_filter.date_to
self.query.filters.dateRange.date_from = dashboard_filter.date_from
+ # The date range is one unit, so never pair the dashboard's bounds with the insight's own
+ # explicitDate (matching apply_dashboard_filters.py; the base QueryRunner still keeps the
+ # insight's flag when the dashboard's is None). Coerced to bool to keep the serialized
+ # value at false rather than null.
+ self.query.filters.dateRange.explicitDate = bool(dashboard_filter.explicitDate)
if dashboard_filter.properties:
self.query.filters.properties = (self.query.filters.properties or []) + dashboard_filter.properties
diff --git a/posthog/hogql_queries/utils/query_date_range.py b/posthog/hogql_queries/utils/query_date_range.py
index 0a628f6ffa2d..bda6b7c29e21 100644
--- a/posthog/hogql_queries/utils/query_date_range.py
+++ b/posthog/hogql_queries/utils/query_date_range.py
@@ -5,7 +5,7 @@ from zoneinfo import ZoneInfo
from dateutil.relativedelta import relativedelta
-from posthog.schema import DateRange, IntervalType
+from posthog.schema import DateRange, HogQLFilters, IntervalType
from posthog.hogql.parser import ast
@@ -409,6 +409,19 @@ class QueryDateRange:
),
}
+ def to_hogql_filters(self) -> HogQLFilters:
+ """HogQLFilters carrying this range's bounds as absolute datetimes. The {filters} resolver
+ (posthog.hogql.filters.ReplaceFilters) snaps day-level relative bounds like "-7d" to calendar
+ days to match insights, so a runner that wants this range's exact bounds (logs, tracing) must
+ resolve them here and pass datetimes the resolver uses verbatim."""
+ return HogQLFilters(
+ dateRange=DateRange(
+ date_from=self.date_from().isoformat(),
+ date_to=self.date_to().isoformat(),
+ explicitDate=True,
+ )
+ )
+
class QueryDateRangeWithIntervals(QueryDateRange):
"""
diff --git a/products/logs/backend/logs_query_runner.py b/products/logs/backend/logs_query_runner.py
index caf0a533caf5..3eff55849bd6 100644
--- a/products/logs/backend/logs_query_runner.py
+++ b/products/logs/backend/logs_query_runner.py
@@ -7,7 +7,6 @@ from zoneinfo import ZoneInfo
from posthog.schema import (
CachedLogsQueryResponse,
FilterLogicalOperator,
- HogQLFilters,
IntervalType,
LogPropertyFilter,
LogPropertyFilterType,
@@ -668,7 +667,7 @@ class LogsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMi
workload=Workload.LOGS,
timings=self.timings,
limit_context=self.limit_context,
- filters=HogQLFilters(dateRange=self.query.dateRange),
+ filters=self.query_date_range.to_hogql_filters(),
settings=self.settings,
)
results = []
diff --git a/products/logs/backend/services_query_runner.py b/products/logs/backend/services_query_runner.py
index f29cb6b01f2e..270a4ac8dac0 100644
--- a/products/logs/backend/services_query_runner.py
+++ b/products/logs/backend/services_query_runner.py
@@ -2,7 +2,7 @@ from typing import Any
import re2
-from posthog.schema import CachedLogsQueryResponse, HogQLFilters, LogsQuery
+from posthog.schema import CachedLogsQueryResponse, LogsQuery
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
@@ -178,7 +178,7 @@ class ServicesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn
workload=Workload.LOGS,
timings=self.timings,
limit_context=self.limit_context,
- filters=HogQLFilters(dateRange=self.query.dateRange),
+ filters=self.query_date_range.to_hogql_filters(),
settings=self.settings,
)
@@ -198,7 +198,7 @@ class ServicesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn
workload=Workload.LOGS,
timings=self.timings,
limit_context=self.limit_context,
- filters=HogQLFilters(dateRange=self.query.dateRange),
+ filters=self.query_date_range.to_hogql_filters(),
settings=self.settings,
)
sparkline_rows = sparkline_response.results
diff --git a/products/logs/backend/test/test_logs_query_runner.py b/products/logs/backend/test/test_logs_query_runner.py
index 0fad861b7c26..fc1886f05ac4 100644
--- a/products/logs/backend/test/test_logs_query_runner.py
+++ b/products/logs/backend/test/test_logs_query_runner.py
@@ -1122,6 +1122,17 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertIn("boundary-log-dec17-afternoon", bodies)
self.assertNotIn("boundary-log-dec18-early", bodies)
+ @freeze_time("2025-12-18T12:00:00Z")
+ def test_relative_date_from_keeps_exact_window(self):
+ # "-1d" must mean exactly 24 hours back, not "since midnight yesterday": the count and
+ # sparkline runners resolve day-level presets exactly, so a midnight-snapped list would
+ # show logs the sparkline and header count say don't exist
+ bodies = self._boundary_bodies(self._boundary_query("-1d"))
+ self.assertIn("boundary-log-dec17-afternoon", bodies)
+ self.assertIn("boundary-log-dec18-early", bodies)
+ self.assertNotIn("boundary-log-dec17-midnight-exact", bodies)
+ self.assertNotIn("boundary-log-dec17-midnight-plus1us", bodies)
+
# ── _normalize_filter_group tests ──────────────────────────────────
_FLAT_FILTERS = [
diff --git a/products/tracing/backend/aggregation_query_runner.py b/products/tracing/backend/aggregation_query_runner.py
index 565b31c2e989..481edfd0910f 100644
--- a/products/tracing/backend/aggregation_query_runner.py
+++ b/products/tracing/backend/aggregation_query_runner.py
@@ -26,8 +26,6 @@ from posthog.schema import (
AttributeBreakdownRow,
CachedTraceSpansAggregationQueryResponse,
CachedTraceSpansTreeQueryResponse,
- DateRange,
- HogQLFilters,
HogQLQueryModifiers,
IntervalType,
PropertyGroupsMode,
@@ -193,12 +191,7 @@ class _SpanAggregationMixin:
timings=self.timings,
limit_context=self.limit_context,
settings=self.settings,
- filters=HogQLFilters(
- dateRange=DateRange(
- date_from=query_date_range.date_from().isoformat(),
- date_to=query_date_range.date_to().isoformat(),
- )
- ),
+ filters=query_date_range.to_hogql_filters(),
)
return [self._row_from_clickhouse(row) for row in response.results]
diff --git a/products/tracing/backend/count_query_runner.py b/products/tracing/backend/count_query_runner.py
index 99ed3f5efd08..790c74f3ff50 100644
--- a/products/tracing/backend/count_query_runner.py
+++ b/products/tracing/backend/count_query_runner.py
@@ -4,7 +4,6 @@ from typing import TYPE_CHECKING
from posthog.schema import (
CachedTraceSpansQueryResponse,
DateRange,
- HogQLFilters,
PropertyGroupFilter,
TraceSpansQuery,
TraceSpansQueryResponse,
@@ -52,7 +51,7 @@ class TraceSpansCountQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunne
team=self.team,
workload=Workload.LOGS,
timings=self.timings,
- filters=HogQLFilters(dateRange=self.query.dateRange),
+ filters=self.query_date_range.to_hogql_filters(),
settings=self.settings,
)
count = response.results[0][0] if response.results else 0
diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.py
index 4d3f5e87967f..661bd9b1dcc7 100644
--- a/products/tracing/backend/logic.py
+++ b/products/tracing/backend/logic.py
@@ -18,7 +18,6 @@ from posthog.schema import (
CachedTraceSpansTreeQueryResponse,
CompareFilter,
DateRange,
- HogQLFilters,
HogQLQueryModifiers,
IntervalType,
PropertyGroupFilter,
@@ -425,7 +424,7 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
team=self.team,
workload=Workload.LOGS,
timings=self.timings,
- filters=HogQLFilters(dateRange=self.query.dateRange),
+ filters=self.query_date_range.to_hogql_filters(),
settings=self.settings,
)
results = []
@@ -793,7 +792,7 @@ def run_service_names_query(
query=query,
team=team,
workload=Workload.LOGS,
- filters=HogQLFilters(dateRange=date_range),
+ filters=query_date_range.to_hogql_filters(),
modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),
settings=HogQLGlobalSettings(
allow_experimental_object_type=False,
@@ -877,7 +876,7 @@ def run_attribute_names_query(
query=query,
team=team,
workload=Workload.LOGS,
- filters=HogQLFilters(dateRange=date_range),
+ filters=query_date_range.to_hogql_filters(),
modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),
settings=HogQLGlobalSettings(
read_overflow_mode="break",
@@ -977,7 +976,7 @@ def _run_attribute_names_value_search(
query=query,
team=team,
workload=Workload.LOGS,
- filters=HogQLFilters(dateRange=date_range),
+ filters=query_date_range.to_hogql_filters(),
modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),
settings=HogQLGlobalSettings(
read_overflow_mode="break",
@@ -1058,7 +1057,7 @@ def run_attribute_values_query(
query=query,
team=team,
workload=Workload.LOGS,
- filters=HogQLFilters(dateRange=date_range),
+ filters=query_date_range.to_hogql_filters(),
modifiers=HogQLQueryModifiers(convertToProjectTimezone=False),
settings=HogQLGlobalSettings(
read_overflow_mode="break",
diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.py
index df939f7ac7fe..792470af571b 100644
--- a/products/web_analytics/backend/api/heatmaps_api.py
+++ b/products/web_analytics/backend/api/heatmaps_api.py
@@ -610,9 +610,9 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def _build_test_accounts_filter(self, date_from: date, date_to: date | None) -> ast.CompareOperation:
# The heatmap predicate treats date_to as an inclusive day via `timestamp <= {date_to} + interval 1 day`.
- # HogQLFilters instead emits a strict `timestamp < date_to`, so when date_from and date_to land on the same
- # day this events subquery collapses to an impossible range and returns no sessions. Add a day so the
- # events subquery covers the same date window as the main heatmap query.
+ # Pass the same bound as an explicit next-day-midnight datetime, which HogQLFilters uses verbatim with a
+ # strict `<`, so the events subquery covers the same inclusive days as the main heatmap query. A date-only
+ # value would instead snap to the end of that next day and widen the window by a day.
events_date_to = (date_to or date.today()) + timedelta(days=1)
events_select = replace_filters(
parse_select(
@@ -622,7 +622,7 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
filterTestAccounts=True,
dateRange=DateRange(
date_from=date_from.strftime("%Y-%m-%d"),
- date_to=events_date_to.strftime("%Y-%m-%d"),
+ date_to=events_date_to.strftime("%Y-%m-%dT00:00:00"),
),
),
self.team,