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(web-analytics): add precompute flags to query completed event (#70045)

Lucas Ricoy6013d6a0ddcc
diff --git a/frontend/src/queries/query.test.ts b/frontend/src/queries/query.test.ts
index fde96eaac70b..98ea92e633f7 100644
--- a/frontend/src/queries/query.test.ts
+++ b/frontend/src/queries/query.test.ts
@@ -4,7 +4,7 @@ import api, { ApiError } from 'lib/api'
import { useMocks } from '~/mocks/jest'
import { performQuery, pollForResults, queryExportContext, waitForPageVisible } from '~/queries/query'
-import { EventsQuery, HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
+import { EventsQuery, HogQLQuery, NodeKind, WebStatsBreakdown } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { PropertyFilterType, PropertyOperator } from '~/types'
@@ -22,6 +22,17 @@ describe('query', () => {
{ results: [], clickhouse: 'clickhouse string', hogql: 'hogql string', is_cached: false },
]
}
+ if (data.query?.kind === 'WebStatsTableQuery') {
+ return [
+ 200,
+ {
+ results: [],
+ is_cached: false,
+ preComputeStrategy: 'lazy_precompute',
+ preComputeStale: true,
+ },
+ ]
+ }
if (data.query?.kind === 'EventsQuery' && data.query.select[0] === 'error') {
return [500, { detail: 'error' }]
}
@@ -110,6 +121,23 @@ describe('query', () => {
})
})
+ it('captures precompute strategy and staleness from web analytics responses', async () => {
+ const captureSpy = jest.spyOn(posthog, 'capture')
+ const q = setLatestVersionsOnQuery({
+ kind: NodeKind.WebStatsTableQuery,
+ breakdownBy: WebStatsBreakdown.Page,
+ properties: [],
+ }) as any
+ captureSpy.mockClear()
+ await performQuery(q)
+ const queryCompletedCalls = captureSpy.mock.calls.filter((call) => call[0] === 'query completed')
+ expect(queryCompletedCalls).toHaveLength(1)
+ expect(queryCompletedCalls[0][1]).toMatchObject({
+ precompute_strategy: 'lazy_precompute',
+ precompute_stale: true,
+ })
+ })
+
it('emits an event when a query errors', async () => {
const captureSpy = jest.spyOn(posthog, 'capture')
const q: EventsQuery = setLatestVersionsOnQuery({
diff --git a/frontend/src/queries/query.ts b/frontend/src/queries/query.ts
index cd2d9a60a10c..bbdea3f168f9 100644
--- a/frontend/src/queries/query.ts
+++ b/frontend/src/queries/query.ts
@@ -252,6 +252,17 @@ export async function performQuery<N extends DataNode>(
if (isHogQLQuery(queryNode) && response && typeof response === 'object') {
logParams.clickhouse_sql = (response as HogQLQueryResponse)?.clickhouse
}
+ if (response && typeof response === 'object') {
+ // Web analytics responses report which read path served them and whether
+ // a lazy-precompute read was served stale. Undefined elsewhere, so these
+ // props only land on events that carry them.
+ const { preComputeStrategy, preComputeStale } = response as {
+ preComputeStrategy?: string
+ preComputeStale?: boolean
+ }
+ logParams.precompute_strategy = preComputeStrategy
+ logParams.precompute_stale = preComputeStale
+ }
}
posthog.capture('query completed', {
query: queryNode,
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index c709301a72a4..50b368f58d80 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -12965,6 +12965,10 @@
"offset": {
"$ref": "#/definitions/integer"
},
+ "preComputeStale": {
+ "description": "Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline.",
+ "type": "boolean"
+ },
"preComputeStrategy": {
"$ref": "#/definitions/WebAnalyticsPreComputeStrategy"
},
@@ -14969,6 +14973,10 @@
"offset": {
"$ref": "#/definitions/integer"
},
+ "preComputeStale": {
+ "description": "Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline.",
+ "type": "boolean"
+ },
"preComputeStrategy": {
"$ref": "#/definitions/WebAnalyticsPreComputeStrategy"
},
@@ -35461,6 +35469,10 @@
"offset": {
"$ref": "#/definitions/integer"
},
+ "preComputeStale": {
+ "description": "Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline.",
+ "type": "boolean"
+ },
"preComputeStrategy": {
"$ref": "#/definitions/WebAnalyticsPreComputeStrategy"
},
@@ -36846,6 +36858,10 @@
"offset": {
"$ref": "#/definitions/integer"
},
+ "preComputeStale": {
+ "description": "Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline.",
+ "type": "boolean"
+ },
"preComputeStrategy": {
"$ref": "#/definitions/WebAnalyticsPreComputeStrategy"
},
@@ -49952,6 +49968,10 @@
"offset": {
"$ref": "#/definitions/integer"
},
+ "preComputeStale": {
+ "description": "Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline.",
+ "type": "boolean"
+ },
"preComputeStrategy": {
"$ref": "#/definitions/WebAnalyticsPreComputeStrategy"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index f85517665075..055dff7644a5 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -2845,6 +2845,8 @@ export interface WebStatsTableQueryResponse extends AnalyticsQueryResponseBase {
limit?: integer
offset?: integer
preComputeStrategy?: WebAnalyticsPreComputeStrategy
+ /** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
+ preComputeStale?: boolean
}
export type CachedWebStatsTableQueryResponse = CachedQueryResponse<WebStatsTableQueryResponse>
diff --git a/posthog/schema.py b/posthog/schema.py
index ced506b0ed97..9fa2f6ff314d 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -8011,6 +8011,13 @@ class WebStatsTableQueryResponse(BaseModel):
limit: int | None = None
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int | None = None
+ preComputeStale: bool | None = Field(
+ default=None,
+ description=(
+ "Whether a lazy-precompute read was served from expired-within-grace"
+ " (stale) jobs instead of recomputing inline."
+ ),
+ )
preComputeStrategy: WebAnalyticsPreComputeStrategy | None = None
query_status: QueryStatus | None = Field(
default=None,
@@ -13328,6 +13335,13 @@ class CachedWebStatsTableQueryResponse(BaseModel):
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
next_allowed_client_refresh: AwareDatetime
offset: int | None = None
+ preComputeStale: bool | None = Field(
+ default=None,
+ description=(
+ "Whether a lazy-precompute read was served from expired-within-grace"
+ " (stale) jobs instead of recomputing inline."
+ ),
+ )
preComputeStrategy: WebAnalyticsPreComputeStrategy | None = None
query_metadata: dict[str, Any] | None = None
query_status: QueryStatus | None = Field(
@@ -14038,6 +14052,13 @@ class Response5(BaseModel):
limit: int | None = None
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int | None = None
+ preComputeStale: bool | None = Field(
+ default=None,
+ description=(
+ "Whether a lazy-precompute read was served from expired-within-grace"
+ " (stale) jobs instead of recomputing inline."
+ ),
+ )
preComputeStrategy: WebAnalyticsPreComputeStrategy | None = None
query_status: QueryStatus | None = Field(
default=None,
@@ -18406,6 +18427,13 @@ class QueryResponseAlternative24(BaseModel):
limit: int | None = None
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int | None = None
+ preComputeStale: bool | None = Field(
+ default=None,
+ description=(
+ "Whether a lazy-precompute read was served from expired-within-grace"
+ " (stale) jobs instead of recomputing inline."
+ ),
+ )
preComputeStrategy: WebAnalyticsPreComputeStrategy | None = None
query_status: QueryStatus | None = Field(
default=None,
@@ -19294,6 +19322,13 @@ class QueryResponseAlternative44(BaseModel):
limit: int | None = None
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int | None = None
+ preComputeStale: bool | None = Field(
+ default=None,
+ description=(
+ "Whether a lazy-precompute read was served from expired-within-grace"
+ " (stale) jobs instead of recomputing inline."
+ ),
+ )
preComputeStrategy: WebAnalyticsPreComputeStrategy | None = None
query_status: QueryStatus | None = Field(
default=None,
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 305d158f2078..8462c5de01b0 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -3663,6 +3663,8 @@ export interface WebStatsTableQueryResponseApi {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset?: number | null
+ /** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
+ preComputeStale?: boolean | null
preComputeStrategy?: WebAnalyticsPreComputeStrategyApi | null
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
@@ -4044,6 +4046,8 @@ export interface Response5Api {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset?: number | null
+ /** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
+ preComputeStale?: boolean | null
preComputeStrategy?: WebAnalyticsPreComputeStrategyApi | null
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 1c83607a370e..f939f428b4f8 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -3016,6 +3016,8 @@ export interface WebStatsTableQueryResponseApi {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset?: number | null
+ /** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
+ preComputeStale?: boolean | null
preComputeStrategy?: WebAnalyticsPreComputeStrategyApi | null
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
@@ -3397,6 +3399,8 @@ export interface Response5Api {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
offset?: number | null
+ /** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
+ preComputeStale?: boolean | null
preComputeStrategy?: WebAnalyticsPreComputeStrategyApi | null
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatusApi | null
diff --git a/products/web_analytics/backend/hogql_queries/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.py
index be25823de0bc..ec54f664b8ca 100644
--- a/products/web_analytics/backend/hogql_queries/stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table.py
@@ -27,6 +27,7 @@ from posthog.hogql.property import (
property_to_expr,
)
+from posthog.clickhouse.query_tagging import clear_tag, get_query_tag_value
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.settings.data_stores import is_web_analytics_events_prefilter_team
@@ -375,6 +376,12 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
properties = self.query.properties + self._test_account_filters
return property_to_expr(properties, team=self.team)
+ def _lazy_precompute_stale(self) -> Optional[bool]:
+ # The lazy modules mark serve-stale reads via tag_queries(precompute_stale=True)
+ # before executing the read; surfacing it on the response lets clients (and the
+ # frontend's 'query completed' telemetry) see it too. None when served fresh.
+ return True if get_query_tag_value("precompute_stale") else None
+
def get_lazy_precomputed_result(self) -> Optional[LazyStatsResult]:
if not can_use_lazy_precompute(self):
return None
@@ -408,6 +415,7 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
results=results,
modifiers=self.modifiers,
preComputeStrategy=WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE,
+ preComputeStale=self._lazy_precompute_stale(),
hasMore=result.has_more,
limit=self.paginator.limit,
offset=self.paginator.offset,
@@ -434,6 +442,10 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
offset=offset,
)
if rows is None:
+ # The lazy module may have tagged precompute_stale before its read failed;
+ # clear it so the fallback response (and its query_log rows) are not
+ # mislabeled as stale-served.
+ clear_tag("precompute_stale")
return None
return self._build_response_from_lazy_rows(rows, limit=limit, offset=offset)
@@ -496,6 +508,7 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
results=results,
modifiers=self.modifiers,
preComputeStrategy=WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE,
+ preComputeStale=self._lazy_precompute_stale(),
hasMore=has_more,
limit=limit,
offset=offset,
@@ -554,6 +567,7 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
results=results,
modifiers=self.modifiers,
preComputeStrategy=WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE,
+ preComputeStale=self._lazy_precompute_stale(),
hasMore=has_more,
limit=limit,
offset=offset,
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
index f271c648697d..8fc04b6ae9a3 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
@@ -29,6 +29,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
+from posthog.clickhouse.query_tagging import reset_query_tags, tag_queries
from posthog.models.utils import uuid7
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
@@ -143,6 +144,42 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
def _run(self, query: WebStatsTableQuery):
return WebStatsTableQueryRunner(team=self.team, query=query).calculate()
+ def test_failed_lazy_read_clears_stale_tag(self):
+ from posthog.clickhouse.query_tagging import get_query_tag_value, reset_query_tags, tag_queries
+
+ from products.web_analytics.backend.hogql_queries import stats_table as stats_table_mod
+
+ runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query())
+ reset_query_tags()
+
+ def tag_then_fail(*args, **kwargs):
+ tag_queries(precompute_stale=True)
+ return None
+
+ try:
+ with (
+ patch.object(stats_table_mod, "can_use_paths_lazy_precompute", return_value=True),
+ patch.object(stats_table_mod, "execute_paths_lazy_precomputed_read", side_effect=tag_then_fail),
+ ):
+ assert runner._maybe_calculate_via_lazy_precompute() is None
+ assert get_query_tag_value("precompute_stale") is None, (
+ "a failed lazy read must not leave the stale tag to mislabel the fallback"
+ )
+ finally:
+ reset_query_tags()
+
+ @parameterized.expand([("stale_tagged", True, True), ("fresh", False, None)])
+ def test_lazy_response_stamps_precompute_stale(self, _name, tag_set, expected):
+ runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query())
+ reset_query_tags()
+ try:
+ if tag_set:
+ tag_queries(precompute_stale=True)
+ response = runner._build_response_from_lazy_rows([], limit=10, offset=0)
+ finally:
+ reset_query_tags()
+ assert response.preComputeStale is expected
+
@freeze_time("2024-01-15T12:00:00Z")
def test_unfiltered_round_trip_creates_precompute_job(self):
self._seed_two_sessions()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8543835ba6f8..387293583421 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -3632,6 +3632,8 @@ export namespace Schemas {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset?: number | null;
+ /** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
+ preComputeStale?: boolean | null;
preComputeStrategy?: WebAnalyticsPreComputeStrategy | null;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
@@ -5027,6 +5029,8 @@ export namespace Schemas {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset?: number | null;
+ /** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
+ preComputeStale?: boolean | null;
preComputeStrategy?: WebAnalyticsPreComputeStrategy | null;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
@@ -48271,6 +48275,8 @@ export namespace Schemas {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset?: number | null;
+ /** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
+ preComputeStale?: boolean | null;
preComputeStrategy?: WebAnalyticsPreComputeStrategy | null;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
@@ -48746,6 +48752,8 @@ export namespace Schemas {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset?: number | null;
+ /** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
+ preComputeStale?: boolean | null;
preComputeStrategy?: WebAnalyticsPreComputeStrategy | null;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;