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(toolbar): shim relative imports and cut remaining app-graph chains (#69088)

Rafael Audibert6b770b3f69b4
diff --git a/.agents/toolbar-migration.md b/.agents/toolbar-migration.md
index fc5cefd33ad8..83a1c09906ee 100644
--- a/.agents/toolbar-migration.md
+++ b/.agents/toolbar-migration.md
@@ -4,15 +4,15 @@ This file is the committed source of truth for the toolbar bundle modernization
## Status
-- **Current step**: Step 3 (products split) — deliberately landing BEFORE Step 2, see reorder note below. Step 2 (loader + splitting) is implemented and stashed (`toolbar-step2-loader-esm-wip`), gated on the reorder.
+- **Current step**: Step 2 is UNBLOCKED — `src/products.tsx` (and the whole app scene graph) is out of the toolbar bundle graph as of the shim-leak fix below. Next: unstash `toolbar-step2-loader-esm-wip` (expect conflicts in `toolbar-config.mjs` — the working tree's `createToolbarModulePlugin` gained relative/`~/` shim matching that MUST be preserved) and apply the known adjustments in the Step 2 section.
- **Last updated**: 2026-07-07
-- **PRs**: Step 1 — `rafa/toolbar-migration-1-graph-guard` (#69045); Step 3 — `rafa/toolbar-migration-2-products-urls-split` (stacked on Step 1)
-- **Reorder note**: a trial Step 2 build emitted **487 dead chunks** — with `products.tsx` reachable, every product scene's dynamic import becomes a real chunk in `dist/toolbar/`, bloating dist, CI artifacts, and the posthog-js release (all uploaded at 3 CDN prefixes). So the graph cuts that disconnect `products.tsx` land first. After the products split, `products.tsx` is still reachable through exactly two chain families (verified from the metafile): `experimentsTabLogic → scenes/experiments/experimentsLogic → featureFlagsLogic → ProductSetup → products.tsx` (Step 5 cut) and `Elements → HeatmapCanvas → HeatmapEventsPanel → scenes/persons/PersonDisplay → PersonPreview → {personLogic → scenes.ts, NotebookSelectButton → notebooksModel → projectTreeLogic} → products.tsx` (Step 6 cut). Flip the format (Step 2) only once `check-toolbar-graph` shows `src/products.tsx` out of the graph.
+- **PRs**: Step 1 — `rafa/toolbar-migration-1-graph-guard` (#69045); Step 3 — `rafa/toolbar-migration-2-products-urls-split` (#69071, stacked on Step 1); chain cuts + shim-leak fix — `rafa/toolbar-migration-3-shim-leak-and-chain-cuts` (stacked on #69071)
+- **Reorder note (resolved)**: a trial Step 2 build emitted **487 dead chunks** — with `products.tsx` reachable, every product scene's dynamic import becomes a real chunk in `dist/toolbar/`. The gate was: flip the format only once `products.tsx` leaves the graph. That's now done via two moves in this PR. First, the remaining chains all funneled through one root cause: the kea shims only matched exact alias strings (`scenes/teamLogic`), so relative imports (`dataThemeLogic` → `./teamLogic`) and `~/`-prefixed imports pulled the REAL logics and their whole app graph — fixed with relative + `~/` matching in `createToolbarModulePlugin`, disconnecting `products.tsx`, `scenes.ts`, `teamLogic`, `PersonDisplay`, and `experimentsLogic` in one move. Second, `scenes/urls` itself (imported by lib components shared with the app) is shimmed to the toolbar's parity-tested `~/toolbar/urls` duplicate from Step 3, taking the last products-manifest path out. Bundle graph 8448 → ~1000 files (99 → ~13.5 MiB source), shipped `dist/toolbar.js` 9.95 MB → ~4 MB (was just under the 10 MB CloudFront cliff). Graph budget ratcheted 110 MB → 18 MB.
- **posthog-js prerequisite**: DONE — release pipeline is layout-agnostic and verified as a no-op against today's build. Nothing blocks any step. See Step 0 for the constraints it imposes on the build here.
## Why
-The toolbar (`frontend/src/toolbar/`, entry `frontend/src/toolbar/index.tsx`) is built as a single IIFE (`frontend/toolbar-config.mjs`), which force-inlines all 157 dynamic `import()`s in its graph, and it imports the main app — `scenes/urls.ts:5` pulls `~/products` (every product manifest), `~/types` has runtime imports (`lib/Chart`, `lib/api`, an `hls.js`-dragging re-export). Tree shaking can't rescue it (no `sideEffects` fields), so `toolbar-config.mjs` keeps hand-curated denylists + kea shims (`frontend/src/toolbar/shims/`) — which already leak (`scenes/dataThemeLogic.tsx` imports `./teamLogic` relatively, bypassing the exact-string shim). The bundle sits just under the 10MB CloudFront gzip cliff (`frontend/bin/check-toolbar-size.mjs`).
+The toolbar (`frontend/src/toolbar/`, entry `frontend/src/toolbar/index.tsx`) is built as a single IIFE (`frontend/toolbar-config.mjs`), which force-inlines all 157 dynamic `import()`s in its graph, and it imports the main app — `scenes/urls.ts:5` pulls `~/products` (every product manifest), `~/types` has runtime imports (`lib/Chart`, `lib/api`, an `hls.js`-dragging re-export). Tree shaking can't rescue it (no `sideEffects` fields), so `toolbar-config.mjs` keeps hand-curated denylists + kea shims (`frontend/src/toolbar/shims/`) — which leaked until the third PR (`scenes/dataThemeLogic.tsx` imports `./teamLogic` relatively, bypassing the then-exact-string shim; fixed by matching relative and `~/` imports too). Before that fix the bundle sat just under the 10MB CloudFront gzip cliff (`frontend/bin/check-toolbar-size.mjs`); it now ships at ~4.06 MB.
Measured from `frontend/toolbar-esbuild-meta.json` (dev bytes; prod ≈ dev × 0.42):
@@ -82,7 +82,8 @@ Approach (revised on review): rather than restructuring the generated products m
- [x] `frontend/src/toolbar/urls.ts`: the 12 helpers toolbar code uses (`action(s)`, `experiment(s)`, `featureFlag(s)`, `productTour`, `sessionProfile`, `settings`, `survey(s)`, `webAnalyticsWebVitals`), plus a documented `urlToResource` null stub (the real one walks a matcher tree built from every product manifest; its only toolbar-shipped consumer is Link's drag-to-notebook annotation, inert on customer pages)
- [x] `frontend/src/toolbar/urls.test.ts`: parity test asserting each helper matches `scenes/urls` byte-for-byte over sample args (the test deliberately crosses the boundary — that's its job); a helper without samples fails
- [x] All 11 toolbar files import `~/toolbar/urls`; their `-> src/scenes/urls.ts` baseline edges are deleted (47 → 36)
-- [ ] The 3 lib files shipped in the toolbar (`TZLabel`, `HeatmapEventsPanel`, `Link`) still import `scenes/urls` — they're shared with the app and can't be repointed; the shim added in the next PR resolves `scenes/urls` to the toolbar duplicate at build time, which removes their edges and takes the products manifest out of the toolbar graph entirely
+- [x] The 3 lib files shipped in the toolbar (`TZLabel`, `HeatmapEventsPanel`, `Link`) still import `scenes/urls` — they're shared with the app and can't be repointed; the third PR's `scenes/urls` shim resolves them to the toolbar duplicate at build time, removing their edges and taking `scenes/urls` + the products manifest out of the toolbar graph entirely
+- [ ] Verify the app/exporter eager-graph improvements with the `check-eager-graph` owners
### Step 4 — `~/types` hygiene
@@ -94,7 +95,7 @@ Approach (revised on review): rather than restructuring the generated products m
### Step 5 — toolbar-owned direct edges
-- [ ] `toolbar/experiments/experimentsTabLogic.tsx`: stop importing `scenes/experiments/experimentsLogic`; fetch via `toolbarFetch`
+- [x] `toolbar/experiments/experimentsTabLogic.tsx`: stopped importing `scenes/experiments/experimentsLogic` — the pure status helpers (`getExperimentStatus`/`isLaunched`/`isExperimentPaused`/`hasEnded`) moved to leaf module `scenes/experiments/experimentStatus.ts` (re-exported from experimentsLogic for app importers); data fetching already went via `toolbarApi`
- [ ] `toolbar/debug/EventDebugMenu.tsx`: move `PanelSettings` from `scenes/session-recordings/components/` to `lib/components/`
- [ ] `toolbar/debug/eventDebugMenuLogic.ts`: drop/trim the 339KB `core-filter-definitions-by-group.json` taxonomy import
- [ ] `toolbar/actions/StepField.tsx`: move `products/actions/frontend/utils/hints` to `lib/` (or allowlist — it's ~0KB)
@@ -102,9 +103,10 @@ Approach (revised on review): rather than restructuring the generated products m
### Step 6 — shared lib → scenes back-edges (each also helps the main app)
- [ ] `lib/lemon-ui/Link/Link.tsx` → `DraggableToNotebook` (drags notebooks → tiptap): invert with a registry/context seam (the flagship shim→DI replacement)
-- [ ] `lib/lemon-ui/LemonColor/*` → `scenes/dataThemeLogic` (bypasses the teamLogic shim today): theme via props/context
+- [ ] `lib/lemon-ui/LemonColor/*` → `scenes/dataThemeLogic` (its `./teamLogic` import is now shimmed, so this edge is boundary-only, not a leak): theme via props/context
- [ ] `lib/lemon-ui/LemonMarkdown/index.ts`: stop re-exporting `LemonMarkdownWithMermaid` from the barrel (retires the `mermaid` deny for both bundles)
-- [ ] `TZLabel` → teamLogic/urls; `HeatmapEventsPanel` → `PersonDisplay`; `eventUsageLogic` → preflight/web-analytics edges; move `KeyboardShortcut` out of `layout/navigation-3000` into `lib/`
+- [x] `HeatmapEventsPanel` → `PersonDisplay`: replaced with a plain span (PersonDisplay renders exactly that for a distinct_id-only person with `noPopover`); `TZLabel` → teamLogic edge now shimmed at resolve time (`~/scenes/teamLogic` matching)
+- [ ] `TZLabel` → urls; `eventUsageLogic` → preflight/web-analytics edges; move `KeyboardShortcut` out of `layout/navigation-3000` into `lib/`
### Step 7 — lazy boundaries in toolbar source
diff --git a/.oxlintrc.json b/.oxlintrc.json
index 2f4a110dd771..526e17de6c94 100644
--- a/.oxlintrc.json
+++ b/.oxlintrc.json
@@ -327,7 +327,7 @@
"!scenes/product-tours/stepUtils",
"!scenes/product-tours/constants",
"!scenes/product-tours/editor/generateStepHtml",
- "!scenes/experiments/experimentsLogic",
+ "!scenes/experiments/experimentStatus",
"!scenes/experiments/utils",
"!~/scenes/experiments/utils",
"!scenes/session-recordings/components/PanelSettings"
diff --git a/frontend/bin/check-toolbar-graph.mjs b/frontend/bin/check-toolbar-graph.mjs
index 312a3f8bbf3c..bfce42bb39cc 100644
--- a/frontend/bin/check-toolbar-graph.mjs
+++ b/frontend/bin/check-toolbar-graph.mjs
@@ -40,8 +40,10 @@ const FORBIDDEN_PACKAGES = [
// Ratchet policy: when a cut lands, lower the budget to lock it in; raise it only as a
// conscious, reviewed decision in the PR that needs it.
-// 2026-07-07: 99.74 MiB of source input reachable (8446 files); ~5% headroom for churn.
-const TOTAL_INPUT_BYTES_BUDGET = 110_000_000
+// 2026-07-07: 13.95 MiB of source input reachable (1042 files) after the shim-leak fix took
+// the app scene graph out of the bundle; headroom for churn, but any reintroduced leak
+// jumps back to ~100 MiB and fails loudly.
+const TOTAL_INPUT_BYTES_BUDGET = 18_000_000
function fail(message) {
console.error(`\n❌ ${message}`)
diff --git a/frontend/bin/toolbar-graph-baseline.json b/frontend/bin/toolbar-graph-baseline.json
index 810ab397c1e6..2384e4b45c65 100644
--- a/frontend/bin/toolbar-graph-baseline.json
+++ b/frontend/bin/toolbar-graph-baseline.json
@@ -8,10 +8,6 @@
"src/lib/components/PayGateMini/payGateMiniLogic.tsx -> src/scenes/PreflightCheck/preflightLogic.tsx",
"src/lib/components/PropertyKeyInfo.tsx -> src/scenes/surveys/surveyQuestionLabelsLogic.ts",
"src/lib/components/Superpowers/superpowersLogic.ts -> src/scenes/PreflightCheck/preflightLogic.tsx",
- "src/lib/components/TZLabel/index.tsx -> src/scenes/teamLogic.tsx",
- "src/lib/components/TZLabel/index.tsx -> src/scenes/urls.ts",
- "src/lib/components/heatmaps/HeatmapEventsPanel.tsx -> src/scenes/persons/PersonDisplay.tsx",
- "src/lib/components/heatmaps/HeatmapEventsPanel.tsx -> src/scenes/urls.ts",
"src/lib/lemon-ui/LemonColor/LemonColorButton.tsx -> src/scenes/dataThemeLogic.tsx",
"src/lib/lemon-ui/LemonColor/LemonColorGlyph.tsx -> src/layout/navigation-3000/themeLogic.ts",
"src/lib/lemon-ui/LemonColor/LemonColorGlyph.tsx -> src/scenes/dataThemeLogic.tsx",
@@ -21,7 +17,6 @@
"src/lib/lemon-ui/LemonMenu/LemonMenu.tsx -> src/layout/navigation-3000/components/KeyboardShortcut.tsx",
"src/lib/lemon-ui/LemonModal/LemonModal.tsx -> src/layout/navigation-3000/components/KeyboardShortcut.tsx",
"src/lib/lemon-ui/Link/Link.tsx -> src/scenes/notebooks/AddToNotebook/DraggableToNotebook.tsx",
- "src/lib/lemon-ui/Link/Link.tsx -> src/scenes/urls.ts",
"src/lib/utils/eventUsageLogic.ts -> ../products/web_analytics/frontend/generated/api.schemas.ts",
"src/lib/utils/eventUsageLogic.ts -> src/scenes/PreflightCheck/preflightLogic.tsx",
"src/lib/utils/eventUsageLogic.ts -> src/scenes/product-tours/constants.ts",
@@ -30,7 +25,7 @@
"src/taxonomy/taxonomy.tsx -> src/scenes/web-analytics/tabs/marketing-analytics/utils.ts",
"src/toolbar/actions/StepField.tsx -> ../products/actions/frontend/utils/hints.tsx",
"src/toolbar/debug/EventDebugMenu.tsx -> src/scenes/session-recordings/components/PanelSettings.tsx",
- "src/toolbar/experiments/experimentsTabLogic.tsx -> src/scenes/experiments/experimentsLogic.ts",
+ "src/toolbar/experiments/experimentsTabLogic.tsx -> src/scenes/experiments/experimentStatus.ts",
"src/toolbar/experiments/experimentsTabLogic.tsx -> src/scenes/experiments/utils.ts",
"src/toolbar/product-tours/ProductToursSidebar.tsx -> src/scenes/product-tours/stepUtils.tsx",
"src/toolbar/product-tours/StepCard.tsx -> src/scenes/product-tours/stepUtils.tsx",
diff --git a/frontend/src/lib/components/heatmaps/HeatmapEventsPanel.tsx b/frontend/src/lib/components/heatmaps/HeatmapEventsPanel.tsx
index 995d6bbed24b..df967ee846aa 100644
--- a/frontend/src/lib/components/heatmaps/HeatmapEventsPanel.tsx
+++ b/frontend/src/lib/components/heatmaps/HeatmapEventsPanel.tsx
@@ -7,7 +7,6 @@ import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
-import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { urls } from 'scenes/urls'
export function HeatmapEventsPanel({ context, exportToken }: HeatmapDataLogicProps): JSX.Element | null {
@@ -43,7 +42,9 @@ export function HeatmapEventsPanel({ context, exportToken }: HeatmapDataLogicPro
title: 'User',
dataIndex: 'distinct_id',
sorter: (a, b) => a.distinct_id.localeCompare(b.distinct_id),
- render: (_, event) => <PersonDisplay person={{ distinct_id: event.distinct_id }} noPopover />,
+ // Not PersonDisplay: this panel ships in the toolbar bundle, and PersonDisplay drags in
+ // the person preview/notebook graph. With only a distinct_id it would render this same span.
+ render: (_, event) => <span className="ph-no-capture truncate">{event.distinct_id}</span>,
},
{
title: '',
diff --git a/frontend/src/scenes/experiments/experimentStatus.ts b/frontend/src/scenes/experiments/experimentStatus.ts
new file mode 100644
index 000000000000..e8bd6d00be39
--- /dev/null
+++ b/frontend/src/scenes/experiments/experimentStatus.ts
@@ -0,0 +1,36 @@
+// Leaf module: the toolbar imports these helpers, so they must not live in
+// experimentsLogic (whose kea graph reaches the app's scene manifest).
+import { Experiment, ExperimentStatus } from '~/types'
+
+export type ExperimentStatusInput = Pick<Experiment, 'status' | 'start_date' | 'end_date'> | null | undefined
+
+export function getExperimentStatus(experiment: ExperimentStatusInput): ExperimentStatus {
+ if (!experiment) {
+ return ExperimentStatus.Draft
+ }
+
+ if (experiment.status) {
+ return experiment.status
+ }
+
+ // Fallback for stale fixtures and older mocked data without API-supplied status.
+ if (experiment.end_date) {
+ return ExperimentStatus.Stopped
+ }
+ if (experiment.start_date) {
+ return ExperimentStatus.Running
+ }
+ return ExperimentStatus.Draft
+}
+
+export function isExperimentPaused(experiment: ExperimentStatusInput): boolean {
+ return getExperimentStatus(experiment) === ExperimentStatus.Paused
+}
+
+export function isLaunched(experiment: ExperimentStatusInput): boolean {
+ return getExperimentStatus(experiment) !== ExperimentStatus.Draft
+}
+
+export function hasEnded(experiment: ExperimentStatusInput): boolean {
+ return getExperimentStatus(experiment) === ExperimentStatus.Stopped
+}
diff --git a/frontend/src/scenes/experiments/experimentsLogic.ts b/frontend/src/scenes/experiments/experimentsLogic.ts
index c254663136a9..e02fef293234 100644
--- a/frontend/src/scenes/experiments/experimentsLogic.ts
+++ b/frontend/src/scenes/experiments/experimentsLogic.ts
@@ -70,38 +70,7 @@ const DEFAULT_MODAL_FILTERS: FeatureFlagModalFilters = {
evaluation_runtime: undefined,
}
-type ExperimentStatusInput = Pick<Experiment, 'status' | 'start_date' | 'end_date'> | null | undefined
-
-export function getExperimentStatus(experiment: ExperimentStatusInput): ExperimentStatus {
- if (!experiment) {
- return ExperimentStatus.Draft
- }
-
- if (experiment.status) {
- return experiment.status
- }
-
- // Fallback for stale fixtures and older mocked data without API-supplied status.
- if (experiment.end_date) {
- return ExperimentStatus.Stopped
- }
- if (experiment.start_date) {
- return ExperimentStatus.Running
- }
- return ExperimentStatus.Draft
-}
-
-export function isExperimentPaused(experiment: ExperimentStatusInput): boolean {
- return getExperimentStatus(experiment) === ExperimentStatus.Paused
-}
-
-export function isLaunched(experiment: ExperimentStatusInput): boolean {
- return getExperimentStatus(experiment) !== ExperimentStatus.Draft
-}
-
-export function hasEnded(experiment: ExperimentStatusInput): boolean {
- return getExperimentStatus(experiment) === ExperimentStatus.Stopped
-}
+export { getExperimentStatus, hasEnded, isExperimentPaused, isLaunched } from './experimentStatus'
export function isSingleVariantShipped(experiment: Experiment): boolean {
const filters = experiment.feature_flag?.filters
diff --git a/frontend/src/toolbar/experiments/experimentsTabLogic.tsx b/frontend/src/toolbar/experiments/experimentsTabLogic.tsx
index 3749f556e698..ba0dae74be7d 100644
--- a/frontend/src/toolbar/experiments/experimentsTabLogic.tsx
+++ b/frontend/src/toolbar/experiments/experimentsTabLogic.tsx
@@ -4,7 +4,7 @@ import { subscriptions } from 'kea-subscriptions'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { EXPERIMENT_TARGET_SELECTOR } from 'lib/utils/actions'
-import { isLaunched } from 'scenes/experiments/experimentsLogic'
+import { isLaunched } from 'scenes/experiments/experimentStatus'
import { percentageDistribution } from '~/scenes/experiments/utils'
import { toolbarLogic } from '~/toolbar/bar/toolbarLogic'
diff --git a/frontend/toolbar-config.mjs b/frontend/toolbar-config.mjs
index dca2880b70f5..6ed0d8933ad5 100644
--- a/frontend/toolbar-config.mjs
+++ b/frontend/toolbar-config.mjs
@@ -28,6 +28,11 @@ const shimmedModules = {
// Hoggie illustrations are decorative; the shim renders null so no PNG assets or image
// requests reach the toolbar bundle that runs on customer sites (asset URLs are CSP-relevant).
'lib/brand/hoggies': 'src/toolbar/shims/hoggies.tsx',
+ // Not a kea shim: the toolbar's parity-tested urls duplicate (see src/toolbar/urls.ts).
+ // Toolbar code imports it directly; this entry covers lib/ components shared with the
+ // app (TZLabel, Link, HeatmapEventsPanel), whose scenes/urls import would otherwise pull
+ // every product manifest into the bundle.
+ 'scenes/urls': 'src/toolbar/urls.ts',
}
// Modules replaced with an inert proxy that logs access in debug mode
@@ -86,15 +91,34 @@ const deniedPatterns = [
* - Denied modules get replaced with an inert proxy
*/
function createToolbarModulePlugin(dirname) {
+ // Shims must also catch relative imports of the same modules (e.g. dataThemeLogic's
+ // `./teamLogic`), otherwise the real logic and its whole app graph leak into the bundle.
+ // Map each shimmed module's extensionless absolute path to its shim.
+ const shimsByAbsolutePath = new Map(
+ Object.entries(shimmedModules).map(([alias, shimFile]) => [
+ path.resolve(dirname, 'src', alias),
+ path.resolve(dirname, shimFile),
+ ])
+ )
return {
name: 'toolbar-module-replacements',
setup(build) {
build.onResolve({ filter: /.*/ }, (args) => {
- const shimFile = shimmedModules[args.path]
+ const shimFile = shimmedModules[args.path] ?? shimmedModules[args.path.replace(/^~\//, '')]
if (shimFile) {
return { path: path.resolve(dirname, shimFile) }
}
+ if (args.path.startsWith('.') && args.importer) {
+ const absolute = path
+ .resolve(path.dirname(args.importer), args.path)
+ .replace(/\.(tsx|ts|jsx|js)$/, '')
+ const shimPath = shimsByAbsolutePath.get(absolute)
+ if (shimPath) {
+ return { path: shimPath }
+ }
+ }
+
const shouldDeny =
deniedPaths.includes(args.path) || deniedPatterns.some((pattern) => pattern.test(args.path))
if (shouldDeny) {
diff --git a/products/demo/backend/logic/products/hedgebox/matrix.py b/products/demo/backend/logic/products/hedgebox/matrix.py
index faa0c58985c1..8a311ffdd2bc 100644
--- a/products/demo/backend/logic/products/hedgebox/matrix.py
+++ b/products/demo/backend/logic/products/hedgebox/matrix.py
@@ -1608,8 +1608,9 @@ class HedgeboxMatrix(Matrix):
def _set_up_file_engagement_experiment(self, team: "Team", user: "User", flag: FeatureFlag) -> None:
"""Create the "File engagement boost" experiment, its shared metrics, and its timeseries data.
- Dates derive from the flag rather than matrix state, so this can be re-run standalone against an
- already-seeded team (delete the experiment, then call this with the existing flag).
+ Experiment dates derive from the flag rather than matrix state, so this can be re-run standalone
+ against an already-seeded team (delete the experiment, then call this with the existing flag).
+ The timeseries backfill is bounded by the matrix clock, which is where the simulated data ends.
"""
# The flag is created 2h before the experiment starts — see create_experiment_flag call sites.
start_date = flag.created_at + dt.timedelta(hours=2)
@@ -1789,7 +1790,11 @@ class HedgeboxMatrix(Matrix):
status=ExperimentTimeseriesRecalculation.Status.PENDING,
)
try:
- backfill_experiment_timeseries(str(recalculation.id))
+ # Simulated data ends at the matrix clock. The experiment is running (no end_date),
+ # so without this bound the backfill runs one ClickHouse query per day between the
+ # simulated clock and the real today — empty results, and slow enough to hang demo
+ # generation when the clock is pinned to the past.
+ backfill_experiment_timeseries(str(recalculation.id), backfill_until=self.now.date())
except Exception as e:
# Timeseries are nice-to-have; never fail demo generation over them
capture_exception(e)
diff --git a/products/experiments/backend/test/test_timeseries_backfill.py b/products/experiments/backend/test/test_timeseries_backfill.py
index 700bc17a3f56..88e6b26192ad 100644
--- a/products/experiments/backend/test/test_timeseries_backfill.py
+++ b/products/experiments/backend/test/test_timeseries_backfill.py
@@ -92,3 +92,51 @@ class TestBackfillExperimentTimeseries(BaseTest):
assert result["days_processed"] == 3
assert result["start_date"] == "2024-12-25"
assert result["end_date"] == "2024-12-27"
+
+ def test_backfill_until_caps_running_experiment_at_given_date(self):
+ # A running experiment (no end_date) otherwise backfills through the real today —
+ # demo seeding passes its simulated clock so days without data are never queried.
+ org = Organization.objects.create(name="Test Org")
+ team = Team.objects.create(organization=org, name="Test Team", timezone="UTC")
+ user = User.objects.create(email="[email protected]")
+
+ flag = FeatureFlag.objects.create(team=team, key="test-cap-flag", created_by=user)
+ experiment = Experiment.objects.create(
+ name="Running Experiment",
+ team=team,
+ feature_flag=flag,
+ start_date=datetime.datetime(2024, 10, 25, 10, 0, 0, tzinfo=ZoneInfo("UTC")),
+ end_date=None,
+ )
+
+ recalculation_request = ExperimentTimeseriesRecalculation.objects.create(
+ team=team,
+ experiment=experiment,
+ metric={
+ "metric_type": "mean",
+ "uuid": "test-metric-uuid",
+ "source": {"kind": "EventsNode", "event": "test_event"},
+ },
+ fingerprint="test-fingerprint",
+ status=ExperimentTimeseriesRecalculation.Status.PENDING,
+ )
+
+ mock_result = ExperimentQueryResponse(
+ baseline=ExperimentStatsBaseValidated(key="control", number_of_samples=100, sum=1000, sum_squares=10000),
+ variant_results=[],
+ )
+
+ with patch("products.experiments.backend.timeseries_backfill.ExperimentQueryRunner") as mock_query_runner_class:
+ mock_query_runner = MagicMock()
+ mock_query_runner._calculate.return_value = mock_result
+ mock_query_runner_class.return_value = mock_query_runner
+
+ result = backfill_experiment_timeseries(
+ str(recalculation_request.id), backfill_until=datetime.date(2024, 10, 27)
+ )
+
+ assert result["days_processed"] == 3
+ assert result["end_date"] == "2024-10-27"
+ recalculation_request.refresh_from_db()
+ assert recalculation_request.status == ExperimentTimeseriesRecalculation.Status.COMPLETED
+ assert recalculation_request.last_successful_date == datetime.date(2024, 10, 27)
diff --git a/products/experiments/backend/timeseries_backfill.py b/products/experiments/backend/timeseries_backfill.py
index 99dd4f6bc77a..cf93f217396e 100644
--- a/products/experiments/backend/timeseries_backfill.py
+++ b/products/experiments/backend/timeseries_backfill.py
@@ -6,7 +6,7 @@ query with as_of pinned to each day's end. Normally invoked via the Temporal
dependencies, so it can also run in-process (e.g. from demo data seeding).
"""
-from datetime import datetime, time, timedelta
+from datetime import date, datetime, time, timedelta
from typing import Any
from zoneinfo import ZoneInfo
@@ -23,7 +23,14 @@ from products.experiments.backend.temporal.metric_resolution import build_metric
logger = structlog.get_logger(__name__)
-def backfill_experiment_timeseries(recalculation_id: str) -> dict[str, Any]:
+def backfill_experiment_timeseries(recalculation_id: str, *, backfill_until: date | None = None) -> dict[str, Any]:
+ """Backfill daily metric results for the recalculation request.
+
+ `backfill_until` caps the backfill window. A running experiment (no end_date) otherwise
+ backfills through the real today — callers whose data ends earlier (e.g. demo seeding
+ pinned to a simulated clock) must pass the last date that actually has data, or every
+ day in between costs a ClickHouse query that computes an empty result.
+ """
logger.info("Starting timeseries recalculation", recalculation_id=recalculation_id)
try:
@@ -50,6 +57,9 @@ def backfill_experiment_timeseries(recalculation_id: str) -> dict[str, Any]:
else:
end_date = datetime.now(team_tz).date()
+ if backfill_until is not None:
+ end_date = min(end_date, backfill_until)
+
if recalculation_request.last_successful_date:
current_date = recalculation_request.last_successful_date + timedelta(days=1)
logger.info("Resuming recalculation", current_date=str(current_date))