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(marketing-analytics): bound conversion/touchpoint attribution read to request window (#66581)

Javier Bahamondes25fb39d0206e
diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_conversion_goals_aggregator.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_conversion_goals_aggregator.ambr
index 10977afed8d2..6bcd5104ff76 100644
--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_conversion_goals_aggregator.ambr
+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_conversion_goals_aggregator.ambr
@@ -113,7 +113,7 @@
FROM
marketing_conversions_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS c
LEFT JOIN (
@@ -146,7 +146,7 @@
FROM
marketing_touchpoints_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), greaterOrEquals(touchpoint_timestamp, toDateTime('2022-10-03 00:00:00.000000')), lessOrEquals(touchpoint_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS t ON equals(c.person_id, t.person_id))
ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
@@ -275,7 +275,7 @@
FROM
marketing_conversions_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS c
LEFT JOIN (
@@ -308,7 +308,7 @@
FROM
marketing_touchpoints_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), greaterOrEquals(touchpoint_timestamp, toDateTime('2022-10-03 00:00:00.000000')), lessOrEquals(touchpoint_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS t ON equals(c.person_id, t.person_id))
ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
@@ -437,7 +437,7 @@
FROM
marketing_conversions_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS c
LEFT JOIN (
@@ -470,7 +470,7 @@
FROM
marketing_touchpoints_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), greaterOrEquals(touchpoint_timestamp, toDateTime('2022-10-03 00:00:00.000000')), lessOrEquals(touchpoint_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS t ON equals(c.person_id, t.person_id))
ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
@@ -599,7 +599,7 @@
FROM
marketing_conversions_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS c
LEFT JOIN (
@@ -632,7 +632,7 @@
FROM
marketing_touchpoints_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), greaterOrEquals(touchpoint_timestamp, toDateTime('2022-10-03 00:00:00.000000')), lessOrEquals(touchpoint_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS t ON equals(c.person_id, t.person_id))
ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
@@ -765,7 +765,7 @@
FROM
marketing_conversions_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS c
LEFT JOIN (
@@ -798,7 +798,7 @@
FROM
marketing_touchpoints_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), greaterOrEquals(touchpoint_timestamp, toDateTime('2022-10-03 00:00:00.000000')), lessOrEquals(touchpoint_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS t ON equals(c.person_id, t.person_id))
ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
@@ -912,7 +912,7 @@
FROM
marketing_conversions_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000003')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000003')), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS c
LEFT JOIN (
@@ -945,7 +945,7 @@
FROM
marketing_touchpoints_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), greaterOrEquals(touchpoint_timestamp, toDateTime('2022-10-03 00:00:00.000000')), lessOrEquals(touchpoint_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS t ON equals(c.person_id, t.person_id))
ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
@@ -1059,7 +1059,7 @@
FROM
marketing_conversions_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000004')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000004')), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS c
LEFT JOIN (
@@ -1092,7 +1092,7 @@
FROM
marketing_touchpoints_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), greaterOrEquals(touchpoint_timestamp, toDateTime('2022-10-03 00:00:00.000000')), lessOrEquals(touchpoint_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS t ON equals(c.person_id, t.person_id))
ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
@@ -1223,7 +1223,7 @@
FROM
marketing_conversions_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS c
LEFT JOIN (
@@ -1256,7 +1256,7 @@
FROM
marketing_touchpoints_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), greaterOrEquals(touchpoint_timestamp, toDateTime('2022-10-03 00:00:00.000000')), lessOrEquals(touchpoint_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS t ON equals(c.person_id, t.person_id))
ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
@@ -1369,7 +1369,7 @@
FROM
marketing_conversions_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000003')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000003')), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS c
LEFT JOIN (
@@ -1402,7 +1402,7 @@
FROM
marketing_touchpoints_preaggregated
WHERE
- and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), equals(team_id, 420)))
+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), greaterOrEquals(touchpoint_timestamp, toDateTime('2022-10-03 00:00:00.000000')), lessOrEquals(touchpoint_timestamp, toDateTime('2023-01-31 23:59:59.999999')), equals(team_id, 420)))
GROUP BY
person_id) AS t ON equals(c.person_id, t.person_id))
ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
index 105437c36734..c7b0f8dd5afb 100644
--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
@@ -576,7 +576,7 @@ class ConversionGoalProcessor:
return None
array_collection = self._build_array_collection_from_precomputes(
- touchpoints_result.job_ids, conversions_result.job_ids
+ touchpoints_result.job_ids, conversions_result.job_ids, date_from, date_to, window
)
return self.build_attribution_pipeline(array_collection)
@@ -584,14 +584,22 @@ class ConversionGoalProcessor:
self,
touchpoint_job_ids: Sequence[str | uuid.UUID],
conversion_job_ids: Sequence[str | uuid.UUID],
+ date_from: datetime,
+ date_to: datetime,
+ window: timedelta,
) -> ast.SelectQuery:
"""Reusable-precompute analogue of build_array_collection_query: identical per-person array
contract, but conversion arrays come from the precomputed marketing_conversions table and
touchpoint arrays from the precomputed marketing_touchpoints table (joined on person_id),
instead of inline events scans. build_attribution_pipeline runs unchanged for every mode.
+
+ Each side is bounded to the same window it was materialized for (conversions span the query
+ range; touchpoints extend back by the attribution window), mirroring the ensure_precomputed
+ calls above — a reused job can cover a wider window than the request, so the job_id filter
+ alone would over-count out-of-range rows into the per-person arrays.
"""
- conversions = self._build_conversion_arrays_from_table(conversion_job_ids)
- touchpoints = self._build_touchpoint_arrays_from_table(touchpoint_job_ids)
+ conversions = self._build_conversion_arrays_from_table(conversion_job_ids, date_from, date_to)
+ touchpoints = self._build_touchpoint_arrays_from_table(touchpoint_job_ids, date_from - window, date_to)
select_columns: list[ast.Expr] = []
for col in ("person_id", "conversion_timestamps", "conversion_math_values"):
@@ -672,7 +680,9 @@ class ConversionGoalProcessor:
),
)
- def _build_conversion_arrays_from_table(self, job_ids: Sequence[str | uuid.UUID]) -> ast.SelectQuery:
+ def _build_conversion_arrays_from_table(
+ self, job_ids: Sequence[str | uuid.UUID], date_from: datetime, date_to: datetime
+ ) -> ast.SelectQuery:
"""Per-person conversion arrays read from the precomputed marketing_conversions table, matching
the array shape _build_conversion_only_arrays produces from a live events scan. Each table row is
already a single conversion (event filtered at INSERT time), so we just groupArray per person —
@@ -744,6 +754,9 @@ class ConversionGoalProcessor:
ast.Field(chain=["conversion_math_value"]),
*[ast.Field(chain=[field.attributed_name]) for field in TRACKED_FIELDS],
],
+ date_from=date_from,
+ date_to=date_to,
+ timestamp_column="conversion_timestamp",
)
return ast.SelectQuery(
@@ -752,7 +765,9 @@ class ConversionGoalProcessor:
group_by=[ast.Field(chain=["person_id"])],
)
- def _build_touchpoint_arrays_from_table(self, job_ids: Sequence[str | uuid.UUID]) -> ast.SelectQuery:
+ def _build_touchpoint_arrays_from_table(
+ self, job_ids: Sequence[str | uuid.UUID], date_from: datetime, date_to: datetime
+ ) -> ast.SelectQuery:
"""Per-person touchpoint arrays (utm_timestamps + per-field UTM arrays) read from the
precomputed marketing_touchpoints table, matching the array shape build_array_collection_query
produces from a UTM-pageview scan.
@@ -796,6 +811,9 @@ class ConversionGoalProcessor:
ast.Field(chain=["touchpoint_timestamp"]),
*[ast.Field(chain=[field.attributed_name]) for field in TRACKED_FIELDS],
],
+ date_from=date_from,
+ date_to=date_to,
+ timestamp_column="touchpoint_timestamp",
)
return ast.SelectQuery(
@@ -809,11 +827,20 @@ class ConversionGoalProcessor:
table: str,
job_ids: Sequence[str | uuid.UUID],
row_columns: list[ast.Expr],
+ date_from: datetime,
+ date_to: datetime,
+ timestamp_column: str,
) -> ast.SelectQuery:
"""SELECT DISTINCT over the full row identity (excluding job_id/computed_at) for one team across
the given job_ids. Collapses rows that are physically identical but materialized under different
job_ids, which the ReplacingMergeTree dedup key (which includes job_id) cannot merge away. The
downstream groupArray then sees each real touchpoint/conversion exactly once.
+
+ The job_id filter alone is not enough: the lazy framework reuses a job whose materialized window
+ can be wider than the request (TTL bands merge daily windows, compare-period reuse, …), so the
+ rows for those job_ids span more than the requested range. We bound `timestamp_column` to
+ [date_from, date_to] — matching the ensure_precomputed window and the live events scan
+ (`_build_conversion_only_arrays`) — so the per-person arrays don't pull in out-of-range rows.
"""
return ast.SelectQuery(
select=row_columns,
@@ -828,6 +855,16 @@ class ConversionGoalProcessor:
ast.Tuple(exprs=[ast.Constant(value=str(jid)) for jid in job_ids]),
],
),
+ ast.CompareOperation(
+ left=ast.Field(chain=[timestamp_column]),
+ op=ast.CompareOperationOp.GtEq,
+ right=ast.Constant(value=date_from),
+ ),
+ ast.CompareOperation(
+ left=ast.Field(chain=[timestamp_column]),
+ op=ast.CompareOperationOp.LtEq,
+ right=ast.Constant(value=date_to),
+ ),
ast.CompareOperation(
left=ast.Field(chain=["team_id"]),
op=ast.CompareOperationOp.Eq,
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py
index 6ce43e23d009..5c8c14f6e5e4 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py
@@ -249,6 +249,45 @@ class TestConversionGoalPrecomputeEquivalence(ClickhouseTestMixin, APIBaseTest):
assert preagg_rows, f"{attribution_mode}: precompute returned no rows for a non-UTC team"
assert _round_rows(direct_rows) == _round_rows(preagg_rows)
+ def test_reused_wide_job_excludes_out_of_range_conversions(self):
+ _create_person(distinct_ids=["user_dec"], team=self.team)
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="user_dec",
+ timestamp=datetime(2024, 12, 10, 10, 0, tzinfo=UTC),
+ properties={"utm_campaign": "december", "utm_source": "google", "utm_medium": "cpc"},
+ )
+ _create_event(
+ team=self.team,
+ event="purchase",
+ distinct_id="user_dec",
+ timestamp=datetime(2024, 12, 12, 10, 0, tzinfo=UTC),
+ properties={"value": 99},
+ )
+ self._seed_events()
+
+ processor = self._make_processor(precompute=True)
+ # Materialize a job spanning December — a wider prior request the lazy framework reuses for the
+ # narrow one below (find_existing_jobs matches the overlapping wider job).
+ processor.generate_cte_query(
+ additional_conditions=[],
+ date_from=datetime(2024, 12, 1, tzinfo=UTC),
+ date_to=datetime(2025, 1, 31, tzinfo=UTC),
+ )
+ narrow_rows = self._execute(
+ processor.generate_cte_query(
+ additional_conditions=[],
+ date_from=datetime(2025, 1, 1, tzinfo=UTC),
+ date_to=datetime(2025, 1, 31, tzinfo=UTC),
+ )
+ )
+
+ assert narrow_rows, "expected in-range conversions in the narrow window"
+ assert all("december" not in row for row in narrow_rows), (
+ f"out-of-range December conversion leaked from the reused wider job: {narrow_rows}"
+ )
+
def _round_rows(rows: list[tuple]) -> list[tuple]:
"""Round floats to avoid weight-multiplication rounding noise between paths."""