: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(growth): move product suggestions off UserProductList.reason (#90619)
Rafael Audibert295cc35a60fd
diff --git a/common/storybook/.storybook/app-context.ts b/common/storybook/.storybook/app-context.tsindex 7f585a2bc6df..10ac62b56a42 100644--- a/common/storybook/.storybook/app-context.ts+++ b/common/storybook/.storybook/app-context.ts@@ -1,6 +1,5 @@import { MOCK_DEFAULT_PROJECT, MOCK_DEFAULT_TEAM } from 'lib/api.mock'-import { UserProductListReason } from '~/queries/schema/schema-general'import { AppContext } from '~/types'export const getStorybookAppContext = (): AppContext => ({@@ -23,26 +22,20 @@ export const getStorybookAppContext = (): AppContext => ({id: 'product-1',product_path: 'Product analytics',enabled: true,- reason: UserProductListReason.USED_BY_COLLEAGUES,- reason_text: null,- created_at: new Date().toISOString(), // Recent, should show green dot+ created_at: new Date().toISOString(),updated_at: new Date().toISOString(),},{id: 'product-2',product_path: 'Session replay',enabled: true,- reason: UserProductListReason.NEW_PRODUCT,- reason_text: 'This is a brand new product we just launched!',- created_at: new Date().toISOString(), // Recent, should show green dot+ created_at: new Date().toISOString(),updated_at: new Date().toISOString(),},{id: 'product-3',product_path: 'Feature flags',enabled: true,- reason: UserProductListReason.USED_ON_SEPARATE_TEAM, // Should NOT show green dot- reason_text: null,created_at: new Date().toISOString(),updated_at: new Date().toISOString(),},@@ -50,18 +43,14 @@ export const getStorybookAppContext = (): AppContext => ({id: 'product-4',product_path: 'Dashboards',enabled: true,- reason: UserProductListReason.SALES_LED,- reason_text: null,- created_at: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(), // 10 days ago, should NOT show dot+ created_at: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(),updated_at: new Date().toISOString(),},{id: 'product-5',product_path: 'Experiments',enabled: true,- reason: UserProductListReason.USED_SIMILAR_PRODUCTS,- reason_text: null,- created_at: new Date().toISOString(), // Recent, should show green dot+ created_at: new Date().toISOString(),updated_at: new Date().toISOString(),},],diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 41d490981153..8d4883086df4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8193,37 +8193,37 @@ snapshots:scenes-app-settings-user--settings-user-reminders-modal--light:hash: v1.k794b7964.fbcf3f0f69a5b43c28ea7537ce6f1aab3c21e70f9c2cbb6fdfef4546dadba86c.yYIPurSofuNP1kZXYzNBOa3YU5Zy7VLaSegvGrNZ8Mwscenes-app-sidepanels--side-panel-access-control--dark:- hash: v1.k794b7964.37042b9da954cc41f47eff34210720962fdab019e932919e13f9a011dc4fc6f2.0-Th9zHrqbEY2pTAcjGjWiEGVCxr0QohCZq1Dz3-I6g+ hash: v1.k794b7964.824366f0feabd2509d5f666ed6bd186afc420782378bdfe39fd4aa7851165312.zfBmFPcNVMuGE7SYE7qCe5FIFrmB9JXpwAMTyn_8V9Ascenes-app-sidepanels--side-panel-access-control--light:- hash: v1.k794b7964.28e93dbc9a22050d943170fa36f161d6a3609c26786925cda482ae2bd2bcf090.ew0UyF55wPQN6wnuVp5Gwf5qX9hk-2Wrrn7-kgh3V2k+ hash: v1.k794b7964.0717db5e1a5eb935dbc91756a68a87d31e30561ad29457a1d03f3b37ac465c8d.aNPd3aKZYoeLCveQCVtrduabnIxHL2IAnpUc0AjBj1Ascenes-app-sidepanels--side-panel-activity--dark:- hash: v1.k794b7964.ebfccf7dea5f456bab7bcf09adfd596e027c67bcfd591ec5439bf95a720c0bff.rQrpt2FWuM0a_Mf9s9h5amOFZxOhlBKl9JaeYBu-Ct8+ hash: v1.k794b7964.76aacb80351cd1f4f08cf89b027058428c5d5e5135498d4eafde77e0b518fece.XkcWrLTRoIPSQWYjjUO5gYHP6kPC4LXlDCu6vkitrUsscenes-app-sidepanels--side-panel-activity--light:- hash: v1.k794b7964.3240283bc754a6a8d44094a513b971223351d32d79def8f42e7abe7b7671bc3b.8MfJItPbvyodK_q9OjV25G81usif0qKAnSUsqM5CEUY+ hash: v1.k794b7964.aa18428830e633706c14465e80761376eff0717c4c4a2ecd8c7de7108f04f7a4.FxR2N9Z4W39NxbIBAE4xhJgOHqOtjIiFpbdB9egfuq0scenes-app-sidepanels--side-panel-discussion--dark:- hash: v1.k794b7964.2dc8266893913ca09ace1b989c0476dfbd3f1c3be44d33885b3f2d540eddbea6.O3nYDV3vfLxuQ7zv60hkLs6fwes8WKMUKgz2AbAoTmU+ hash: v1.k794b7964.e214fd4a934bba7dd62a9e9b501cae9e66a22979352a83dda9f5823caf934c7b.Np21B7VGO-pOKkcGV0zK2aGFlEe0xM_ZLwBG0QPUtoQscenes-app-sidepanels--side-panel-discussion--light:- hash: v1.k794b7964.55286c726123d56d98ee7e235128dbd4ea1c4351ed14d2609091644f9b871da4.ybKbNSZfg6JST1QCpnrd1C9o3rnTYl9g6ytGgS2kyMk+ hash: v1.k794b7964.5b3b06288d5f30eec654aa49d15a6768215fed149b51518bbcabf3f3a8a12786.L2FZAO6hrLa9CLZZIYx_FwdppwBdk9R1y-yDyawSQqYscenes-app-sidepanels--side-panel-exports--dark:- hash: v1.k794b7964.54141f28010090a061359ccd16e2a8ef8b7bb60b664ce58a88dd17b3e2e6a892.XfiA98ZPz21RoCe8sbbs7ootPEqBh2eIxOx56Wg0lh4+ hash: v1.k794b7964.40f5d11c2bdeb3a815edd7a955341c6b4167bd4f8bccd4d44d52ffa5c8d390a5.xlmz9zDQvTMPQcCO8xL96ijgy9xxxQX0iuXZE-Kq9jkscenes-app-sidepanels--side-panel-exports--light:- hash: v1.k794b7964.630dce6d4d1d2012df191ed067dd591854290153356aefe2d1e4052ab53253b7.3Gp5UVFwsouafmhS1AtoGL4ttgfrxf-Lh8aVkgobyXg+ hash: v1.k794b7964.6b5349df7bd21ca29aff31a18e4bdeeac2d3b7b3a20bbe5b680e822253272750.NAs1FeZzn2gdS7nfAas7H6K5D6-KhEwoKHlDWY_kUb8scenes-app-sidepanels--side-panel-info--dark:- hash: v1.k794b7964.d8f17e51bf9c3397de48fb337c37cc429dad662e8fc68a61456453772ec0c4bc.Rudohv1e06RYmzlA39EC1r6iav0vT8KW_75lQTLQBgI+ hash: v1.k794b7964.9a7ebfd4747320bfe125d97ccff6b2eb0f797c610dbcfb0fbf97c79ac8e86367.woEbsx8saBmqU2PpIYsrv5eZaOzAmzs94PDf0UwV7Zcscenes-app-sidepanels--side-panel-info--light:- hash: v1.k794b7964.3455622154d4d5ff0514d6dc3672863cfabcc7f1d1051964c3e5e9681829b80a.Xsk9QO4o-WbRZX8LSOBr-GUmA0RuSwjcZOZPMt3aUGI+ hash: v1.k794b7964.eb63a430e9dcde38d7ba06ee57e7ee802b2a13e9218c2c4369e3bbddbd40fb53.e-PdOgbDk-9d8TwhkT3DHdoyYQYFg-qlg_ME8jd7xFAscenes-app-sidepanels--side-panel-max--dark:- hash: v1.k794b7964.07855c8cbec33e308e9b193a612008018f711b0d6a3e6ffc2dc858f1b09f983e.y8bwP4FosOOJTDo1fW9-jXy_osfIBQiiW7OASS0pFB0+ hash: v1.k794b7964.c926e63706eae8afadadfb72f494f43952a6d9a3d9f10be667c9d86d7b96600b.tKRK9U0z8l5MfvkIXgTWbnSeH17-LFg3nUDBCZFl2qAscenes-app-sidepanels--side-panel-max--light:- hash: v1.k794b7964.30ce1018e49582ca7639b9c2e7cfe9240a42629c37a8b373bb618b188a750f90.UDUTe659R4EjBIIM-F44jTjDeiy-tI1fceBiS7M-HnQ+ hash: v1.k794b7964.63283465673a68df94fb1a9ca5196be9c7d14c45e9d6316a08fd63531f16c0ad._V5Asw1jQARn9qxVWhKsCkqBPLZ9izGdtq6q_iBFWXkscenes-app-sidepanels--side-panel-notebooks--dark:- hash: v1.k794b7964.b45b902c323dc8c2c61b89d6b8eb6aa1f9dfcc605a5aa12be33bed1056a1fc86.b2iHTUplC0zfrNWbHp6ln7OjCBnt5CyZ46zk9F2H-74+ hash: v1.k794b7964.01c39dab32eed54741c73e2216e811cdd7884eb0a5f2b1dd8f9be9f2f4d73cf5.a0iI2p5HsL255wOq4mkA3kWqhnzuJBaKo07PuDeLFMUscenes-app-sidepanels--side-panel-notebooks--light:- hash: v1.k794b7964.185847f7e86ea32a76f99defadb1768eff911c78bf211d660a942856b75a7778.fjaN4pn-hp8IiBs5849INkOClPu9C_opblu8diksvuM+ hash: v1.k794b7964.8367b1883aa76c197fe6433dee1b6ff8db78537d776f6dda8c06bebf5d40857f.lv7KOsb5SB5fUY4ZJ0ZGrju5up1yW02eXWs1OilcnWAscenes-app-sidepanels--side-panel-support--dark:- hash: v1.k794b7964.48048a8b107087096fe49aac718863083d8ab053bdd99b008866188eec74587e.wgpa3DdBMXAFxT9JaKrAMzjEoQKBLom-gwXqcMzXmxM+ hash: v1.k794b7964.044ab19d1b43c61c3e26b1b75a993770969e7b87135a0618c18200b51f661d13.gEe7cGpxreFv4OLS3wDzboz4Qw0AXi5vMDx-T9rZgoEscenes-app-sidepanels--side-panel-support--light:- hash: v1.k794b7964.c5d4457f7a01a034fce7b156765f3a8c2670630ec3833007858d862aa4b438b7.sW-vep6EXY8BKQjp-ots49inFooKlo6VjfYCJqDzoIw+ hash: v1.k794b7964.438996b8256483be1879def954de29491b841ad2c2bd36900702c07af6d413a1.9pFe6LbxDs9o0rEq2kV6FGRwq0h9TgshWTdJ-mOoQEMscenes-app-stamphog-digests--digests-list--dark:hash: v1.k794b7964.28fbaad98ddd90b171e6774057e8e9656af77e67fd0b5d462235a1d063c1777c.6E_uVxcZxkBaFZgqKmXAg4njrs4xCTiNBGWAUNg9GT0scenes-app-stamphog-digests--digests-list--light:@@ -8441,17 +8441,17 @@ snapshots:scenes-app-visual-review-run--tracking-only-master-run--light:hash: v1.k794b7964.82f2750059b1ef9ab2adb777da603d4d0985b7213235780f24377be11e601a5e.BdVEZ3jDXINsbZgssAvaGfjq_qmGcGOqm2AhdvSYmXgscenes-app-web-analytics--web-analytics-dashboard--dark:- hash: v1.k794b7964.c688ae21f054b407379450a6ef0f626fecc75424b045f59316624bfc5fadf753.mUwX9UtJE5lmBHYG6V1BKxzaF_aIOFRtC-vS4PgIllk+ hash: v1.k794b7964.f4084b4c34b983966cfdd17f830833fe21f1ecb902a6bc69f6587cb8c45012f7.x4mfs7bSHuoJAOzpDCpF1Zcm4Nc2ANS6WwgkmQ8dV1wscenes-app-web-analytics--web-analytics-dashboard--light:- hash: v1.k794b7964.077185f302301aedbade9c3c7c18555828b615e53f58eda4521b43d57b60f938.bmuFww_tcCyO3pVKf5qfdLGfkzQoRaChvtwFgj1XeWQ+ hash: v1.k794b7964.a53d2194af3c7627262dd955de34bdb9ca508668650e87a6ffe1d2fcfdcdf09f.gzX-q9ZV8czasFNoxfg5f96CjUbfXcvAO5r_Fb5YY68scenes-app-web-analytics--web-analytics-dashboard-loading--dark:- hash: v1.k794b7964.2fce58d75a6328600aa6ad670ce4a8430dd4edbc29bf9fe97a0e77fa7582233f.Ot9sYCxJpRY1eubdEIyLW7oF2SWz39XovhQRxkPxppc+ hash: v1.k794b7964.7863ad153230755ed3241f0e3504ea4c9d591df3b33dd8a4d8bee49dcdcb9838.hI0XbxLXx2I0ngx6sFtmn1xAzXGwCax6QWhNc3k1bWcscenes-app-web-analytics--web-analytics-dashboard-loading--light:- hash: v1.k794b7964.21e2d9d306d25f7ae9ff7c1633ae495012b4e17988a9b63092b0227408dc24bb.0G_rDxlMNqORis7vhkeF-uLwmCdzU_hkF7sCw5YUMS8+ hash: v1.k794b7964.f34b70b62820743f56bdb8d7d38f0dc56d2f70d88b7498be68797235e2e64204.tNWBOQeCOaBb0wND9XGQU_auMUSKXE15Ptor6kdTV_Escenes-app-web-analytics--web-analytics-dashboard-metric-cards--dark:- hash: v1.k794b7964.15c623f5755f7df75c6b0f81a5aeaee3521ea83b616221eb0c467a05d13562cd.b5gdjeoWOexCzv1m02iIgN9aQemXbFea-k4CCmgmgJE+ hash: v1.k794b7964.06734ec52797048b5cbdca1c3dd02faca4b94669aebf1fb376dcbfac1cedaeb7.bScGnKbWixOAl8zXd2kVg6A2Bj6xEfpPPdAbdSe54z8scenes-app-web-analytics--web-analytics-dashboard-metric-cards--light:- hash: v1.k794b7964.a4417f5df57c1f429586d6ed1d099e09ad1980e08b735211c701bb0bbe798a09.w_HGMz9YajSVkyE3CXZ0d-alkgE6RDWL_EoFAxdhknw+ hash: v1.k794b7964.4b20e1bbaf23e2206dfe201106d1a299d7afbb396a7a7416af51e41bf79a0ddb.Rjra1hRuDvfYIHNpKAS5o_eDpyx74X-HZwVXeXc8Lm8scenes-app-web-analytics-achievements--daily-only-arm--dark:hash: v1.k794b7964.8f024a521e113d8101749768f8d4f49d8dcac1365f43d9b2038c6df0021bac6a.BYx467NAatau4dzb13PnZCTODi-yUho-Vhm_JdtCY9wscenes-app-web-analytics-achievements--daily-only-arm--light:@@ -8473,29 +8473,29 @@ snapshots:scenes-app-web-analytics-achievements--weekly-only-arm--light:hash: v1.k794b7964.eb042d165752cd9ff0145ee3b49f0769671244ca00e931c8ece93ec0d01a9a6f.YlQzVwE6qBKZs4cKyA1-lYowaxlhGEGt_K4jt076OSEscenes-app-web-analytics-agent-analytics--agent-analytics-issue-detail--dark:- hash: v1.k794b7964.af274a968f5fc7478aba061f54b9f72a16e62ffe34f90730eaf20c6cb4d24908.B154fMHWwqtix4WQBYKSpIBYg09BGSXEA47Ck_SPZzY+ hash: v1.k794b7964.37b28979913d4118e5c146474b3d63a5db8a58e731b6c86d1c2a816b811514ab.dpC8X_Q4SSJL7Gvkq24o2R7sD90NBYZ7xFUCdC_YR_8scenes-app-web-analytics-agent-analytics--agent-analytics-issue-detail--light:- hash: v1.k794b7964.9e90469453688fbf4a73e64d196514e06246724500b2c3abeaafe24720892466.MNwUaksA3ekrFBmDDNaEHnumzK7NMY1O2V2Wtue9oEE+ hash: v1.k794b7964.d438216ae1f55c434630f39a92fbf5b37bd3539df89ad5b5e72b43d701a57035.JalsZR05g17ViyWSLctlSsPCz7-QZSuuFTT38UhaWvYscenes-app-web-analytics-agent-analytics--agent-analytics-issues--dark:- hash: v1.k794b7964.dbb9d5de03bf6352fac544ee7ac3aa659f3a3fd2049131c0f0d43ef60286015d.lRjAydasGmuax6O8AcjmoQmB0DYmJsM9jKea5f680-w+ hash: v1.k794b7964.522586e84bf88ecd7483afd029956d829ce306b51c66c481e98677ff90ef92e3.JJTUEX1DIGP8_jxjA6Jdp6Gs1ZqrwtuygE6p2sGMgKwscenes-app-web-analytics-agent-analytics--agent-analytics-issues--light:- hash: v1.k794b7964.242da963fdefad55a219d3dceb731d1d1ac3d3a06b1ee1555311f65355a96f2f.Gy1ll240PgZ_-4KJBCy4_u6Qt0T2Y_qhD1EEnC8W-Fo+ hash: v1.k794b7964.7433402e3c891258f40556710965e99a874c00110b5d49edd070ea2bf93dbbb8.N5zxeWa8xMazTArM6TBtayqCRI6PVuv6dnHrmwPSfQ4scenes-app-web-analytics-agent-analytics--agent-analytics-journey-detail--dark:- hash: v1.k794b7964.a41af94b2f159564c15f466c86d0013477b5da1852171ce3517dc3a5b7945c3f.XJKSaN7lj3vUaFek_cyUycRbB7GMYDwwS1yl-ubyc5c+ hash: v1.k794b7964.7fb719c70c9f35f08473903cf2e08a54c9ddf67c5154d868c1b3bfc41d4292a4.4AuKLRgTvJSsSQlHvteUdpXGNc0Ai5NLSv8N2sFlmcoscenes-app-web-analytics-agent-analytics--agent-analytics-journey-detail--light:- hash: v1.k794b7964.7423c0f038b2414ad75227d6f51ac444598b6fbe292d6ccb96c77accb2065248.wDAKbneqR4cdPd-jUHIUkJ_KRR9Q6l-5eJvHnz5Xbow+ hash: v1.k794b7964.94ad9c19d9393ece07406128600a4773bb6dd7caf808b07a3dbfec8423e133f9.li6cVW-2nxvpJTMWW3jmRPyTkSBm4w4QIFb-85DD6AAscenes-app-web-analytics-agent-analytics--agent-analytics-journeys--dark:- hash: v1.k794b7964.f87591bd4b33dff97c12468aae2c4e45774a5d07bc1f0acdf14a3b0e83258a34.o2axgpUlamnIEvP9GKa7PkuM5f4HNAiGaje4HkvCKWs+ hash: v1.k794b7964.61a291aeadc75c71ec717fd56fbb21043aee87887847ef482fc7154d85f857e6.jSp8Y-YkBqcmcbXq5gIRnbhSjCaSAfmdgPlB-f3k7scscenes-app-web-analytics-agent-analytics--agent-analytics-journeys--light:- hash: v1.k794b7964.d0a60d6d52e7f303b9d472f0271123f553d9a84bb05ed72d76edd481bbcd8ba2.K4ByRriw9Y_nw2vCGUyybZz_C3VtNSWMUCVHYLxBbe0+ hash: v1.k794b7964.1c05d194739814c0e9cc81bb80b45c0be15fc34c32e023f6c46ac99e204151b7.Rj0-SIPHwj_h5KnWBzfSbG45Ld4q3eHoLFHTwsaDL8Ascenes-app-web-analytics-agent-analytics--agent-analytics-overview--dark:- hash: v1.k794b7964.4f38c8e352d3ecec0c06d3c56054e8bd713ee2fc4dddd9fb37065f9401befb69.CcbIVNmpGyPxnNYfZLgXnuttc0QgoXnYVjYsvPIhPJM+ hash: v1.k794b7964.fecdf9385ccdda7a3c9c4fcf1ae185b8d98a48229ef715afcf1316399d5d418b.Ac4lcjOJj-cJWWo4ICRMl5bsiibpFtXr1XR4s-ulCgkscenes-app-web-analytics-agent-analytics--agent-analytics-overview--light:- hash: v1.k794b7964.e1ca0655433728301a86a76b772f3667e4577305bfcfeae45b1de3f2179a3e18.uGdX8ketOinZIdo2t5edjOqxK8EtzScwmcwgMyF9q50+ hash: v1.k794b7964.7fc9d662ba575e81ebdf70a40c99ca9163423b8ae10ef629062b4de791a72591.D8RM5dE248wTlZtL5jKROJphSlFPhLOIcBUbbKt7DCoscenes-app-web-analytics-agent-analytics--agent-analytics-readiness--dark:- hash: v1.k794b7964.b5bf9c96f00005058fad9d49ce6d6326a80cfb8384734f082418c0e14ef1fb09.n62WqZrpVGLNIhRGgl19CU_nYmPalydA6d0VQI_JCNs+ hash: v1.k794b7964.3674a0e2d094991a2314ed168bfd21e933891714bf5c3694f27cdee01ddc3a23.WaBPygMTmyI2WY3aoHBaPzR-gwtqKofS-UWQ6A0HihAscenes-app-web-analytics-agent-analytics--agent-analytics-readiness--light:- hash: v1.k794b7964.0ec6ee7ca0f8b82113d0854ff0593bbbf45e86fb75ad70c17931d400950a4c59.x4Mky3FWK2KxXOs_HF37107l27zrmliUkvT3MN2wHIE+ hash: v1.k794b7964.75fabf0c85e15efdaa8f6fc724f5be47618ba00dd8e272a64e3c6f523b581fbf.RxsOv8-sC4xnlnI6U5vQdjYYCrUp7Y4GjkzgHmGLtH4scenes-app-web-analytics-livemetricscharts--bot-events-per-minute--dark:hash: v1.k794b7964.933ca8aa37de16e55b07b9be45e8784e14b6a9aa8d7119882340e8858c5f9afd.FWPAiDTJNN-96zh7GPc5h6lH7TSlCDPeLmG0lk3YW1Iscenes-app-web-analytics-livemetricscharts--bot-events-per-minute--light:@@ -8533,9 +8533,9 @@ snapshots:scenes-app-web-analytics-pageperformancemetriccard--without-sparkline--light:hash: v1.k794b7964.27bbdd01e4451fe0fe7cfbf693975714907972cdef4cc9b74ab13f99c28f5c34.9VZtUj_jx6H9AXXqTTKz1uomaF3X9e8cENkeIs8iJ_Iscenes-app-web-analytics-search-ai--web-analytics-page-performance--dark:- hash: v1.k794b7964.8eeb81f682d69259a410e13fa177f97688d93a5b4318d5802f1a526b14a04f5a.Ax7VbE9AwsNh5RDC1o5dTHOgFt9IyRADjsXNFrGp8DM+ hash: v1.k794b7964.a744208ade56cae9e8a76244b00afe1b3a13dae94aad05faabc003e1b85183da.cGXPXJHpsVAOoBgRtcj4q-K4fKJkq-ewsD0bkfOzidIscenes-app-web-analytics-search-ai--web-analytics-page-performance--light:- hash: v1.k794b7964.f99572a518724083637df057775b29ebd33277ee027d9b8abc705c82f466877c.043McBdgpHVssTGBD8VUXH9K31maA6ek32vP-RijEQY+ hash: v1.k794b7964.38e99667a5c92cd7a340a682029f5d877054414dd74127097641b0837c3c7b5a.4Tq7UsGkf2xyiR3GhAsMp7SOD9aTC-QcnsZgUvnv0W4scenes-inbox-scout-tags--editor-and-filter--dark:hash: v1.k794b7964.b76b173ee1dc78112e700af267b53d59959164f8ebbc814df2b5f4a3811bcd49.2hfIhAW_k3BdFlo9jtUoJhOyZhS1uQmgafcdvh_CGmgscenes-inbox-scout-tags--editor-and-filter--light:diff --git a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsxindex bfbe9c49bb92..ccb158da96fc 100644--- a/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/ProjectTree.tsx@@ -1,7 +1,7 @@import { BindLogic, useActions, useValues } from 'kea'import { router } from 'kea-router'import posthog from 'posthog-js'-import { RefObject, useCallback, useEffect, useRef, useState } from 'react'+import { RefObject, useEffect, useRef, useState } from 'react'import { IconCheckbox, IconChevronRight, IconEllipsis, IconFolderPlus, IconPlusSmall, IconStar } from '@posthog/icons'@@ -26,11 +26,10 @@ import { cn } from 'lib/utils/css-classes'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { sceneConfigurations } from 'scenes/scenes'-import { teamLogic } from 'scenes/teamLogic'import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'-import { FileSystemEntry, UserProductListReason } from '~/queries/schema/schema-general'+import { FileSystemEntry } from '~/queries/schema/schema-general'import { UserBasicType } from '~/types'import { PanelLayoutPanel } from '../PanelLayoutPanel'@@ -62,18 +61,6 @@ export const PROJECT_TREE_KEY = 'project-tree'let counter = 0const SHORTCUT_DISMISSAL_LOCAL_STORAGE_KEY = 'shortcut-dismissal'-const SEEN_CUSTOM_PRODUCTS_LOCAL_STORAGE_KEY = 'seen-custom-products'--const USER_PRODUCT_LIST_REASON_DEFAULTS: { [key in UserProductListReason]?: string } = {- [UserProductListReason.USED_BY_COLLEAGUES]:- 'We think you might like this product because your colleagues are using it.',- [UserProductListReason.USED_SIMILAR_PRODUCTS]:- 'We think you might like this product because you use similar products. Give it a try!',- [UserProductListReason.USED_ON_SEPARATE_TEAM]:- 'You use this product on another project so we think you might like it here.',- [UserProductListReason.NEW_PRODUCT]: 'This is a brand new product. Give it a try!',- [UserProductListReason.SALES_LED]: 'This product is recommended for you by our team.',-}// Show active state for items that are active in the URLconst isItemActive = (item: TreeDataItem): boolean => {@@ -158,7 +145,6 @@ export function ProjectTree({const { resetPanelLayout } = useActions(panelLayoutLogic)const { mainContentRef } = useValues(panelLayoutLogic)- const { currentTeamId } = useValues(teamLogic)const treeRef = useRef<LemonTreeRef>(null)const { openItemSelectModal } = useActions(itemSelectModalLogic)@@ -167,10 +153,6 @@ export function ProjectTree({false)- const [seenCustomProducts, setSeenCustomProducts] = useLocalStorage<string[]>(- `${currentTeamId ?? '*'}-${SEEN_CUSTOM_PRODUCTS_LOCAL_STORAGE_KEY}`,- []- )const showFilterDropdown = root === 'project://'const showSortDropdown = root === 'project://'@@ -231,15 +213,6 @@ export function ProjectTree({}}, [scrollTargetId, treeRef, clearScrollTarget, setLastViewedId])- const handleMouseEnterIndicator = useCallback(- (itemId: string): void => {- if (!seenCustomProducts.includes(itemId)) {- setTimeout(() => setSeenCustomProducts((state) => [...state, itemId]), 250)- }- },- [seenCustomProducts, setSeenCustomProducts]- )-const tree = (<LemonTreeref={treeRef}@@ -477,21 +450,6 @@ export function ProjectTree({root === 'custom-products://') {const key = item.record?.sceneKey- const reason = item.record?.reason as UserProductListReason | undefined- const reasonText = item.record?.reason_text as string | null | undefined-- const suggestedProductBaseTooltipText =- reasonText || (reason ? USER_PRODUCT_LIST_REASON_DEFAULTS[reason] : undefined)- const tooltipText = suggestedProductBaseTooltipText ? (- <>- {suggestedProductBaseTooltipText}- <br />- <br />- Open the three-dot menu to remove from the sidebar.- <br />- <br />- </>- ) : undefinedreturn (<>@@ -500,7 +458,6 @@ export function ProjectTree({<p className="mb-1 font-semibold">{item.displayName}</p></>)}- {tooltipText}{sceneConfigurations[key]?.description || item.name}{item.tags?.length && (@@ -566,26 +523,6 @@ export function ProjectTree({return undefined}}renderItemIcon={(item) => {- const createdAt = item.record?.created_at- const reason = item.record?.reason as UserProductListReason | undefined- const reasonText = item.record?.reason_text as string | null | undefined- const itemId = item.id-- // This indicator is shown if we detect we're looking at a custom product- // that's been recently added to the user's sidebar.- // We extract the `reasonText` from the item or come up with some default- // ones for some specific reasons that have a reasonable default.- // We exclude USED_ON_SEPARATE_TEAM as those are not particularly useful to highlight.- // We also hide the indicator once the user has hovered over the item.- const showIndicator =- root === 'custom-products://' &&- createdAt &&- dayjs().diff(dayjs(createdAt), 'days') < 7 &&- reason &&- reason !== UserProductListReason.USED_ON_SEPARATE_TEAM &&- (reasonText || USER_PRODUCT_LIST_REASON_DEFAULTS[reason]) &&- !seenCustomProducts.includes(itemId)-return (<>{sortMethod === 'recent' && item.type !== 'loading-indicator' && (@@ -595,12 +532,7 @@ export function ProjectTree({className="ml-[4px]"/>)}- <div className="relative" onMouseEnter={() => handleMouseEnterIndicator(itemId)}>- <TreeNodeDisplayIcon item={item} expandedItemIds={expandedFolders} />- {showIndicator && (- <div className="absolute top-0.5 -right-0.5 size-2 bg-success rounded-full cursor-pointer animate-pulse-5" />- )}- </div>+ <TreeNodeDisplayIcon item={item} expandedItemIds={expandedFolders} /></>)}}diff --git a/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.test.ts b/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.test.tsindex 9f232a21f146..7112c8fef107 100644--- a/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.test.ts+++ b/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.test.ts@@ -1,7 +1,7 @@import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'-import { UserProductListItem, UserProductListReason } from '~/queries/schema/schema-general'+import { UserProductListItem } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { customProductsLogic } from './customProductsLogic'@@ -10,8 +10,6 @@ const serverRow = (productPath: string): UserProductListItem => ({id: `id-${productPath}`,product_path: productPath,enabled: true,- reason: UserProductListReason.PRODUCT_INTENT,- reason_text: null,created_at: '2026-01-01T00:00:00Z',updated_at: '2026-01-01T00:00:00Z',})diff --git a/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.tsxindex fae98132a65d..a4f9a2e7a29e 100644--- a/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/customProductsLogic.tsx@@ -7,7 +7,7 @@ import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { getAppContext } from 'lib/utils/getAppContext'-import { UserProductListItem, UserProductListReason } from '~/queries/schema/schema-general'+import { UserProductListItem } from '~/queries/schema/schema-general'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface customProductsLogicValues {@@ -95,8 +95,6 @@ export const customProductsLogic = kea<customProductsLogicType>([id: '',product_path: productPath,enabled: true,- reason: UserProductListReason.PRODUCT_INTENT,- reason_text: null,created_at: now,updated_at: now,},diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.tsindex cf83b06956da..482917bf24ef 100644--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.test.ts@@ -3,7 +3,6 @@ import { expectLogic } from 'kea-test-utils'import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast'-import { UserProductListReason } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { customProductsLogic } from './customProductsLogic'@@ -40,8 +39,6 @@ describe('projectTreeDataLogic', () => {id: 'abc',product_path: 'Session replay',enabled: true,- reason: UserProductListReason.PRODUCT_INTENT,- reason_text: null,created_at: '2026-01-01T00:00:00Z',updated_at: '2026-01-01T00:00:00Z',},diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsxindex 7274f153a568..b4c5667636e6 100644--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx@@ -1635,8 +1635,6 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([const customProduct = customProductMap.get(productPath)return {...product,- reason: customProduct?.reason,- reasonText: customProduct?.reason_text,created_at: customProduct?.created_at, // Underscore because it comes from backend if it's an actual `FileSystemImport`} as FileSystemImport})diff --git a/frontend/src/layout/panel-layout/ai-first/tabs/editToolsLogic.ts b/frontend/src/layout/panel-layout/ai-first/tabs/editToolsLogic.tsindex 338a4db4470d..401a76c0a85d 100644--- a/frontend/src/layout/panel-layout/ai-first/tabs/editToolsLogic.ts+++ b/frontend/src/layout/panel-layout/ai-first/tabs/editToolsLogic.ts@@ -6,7 +6,7 @@ import api from 'lib/api'import { customProductsLogic } from '~/layout/panel-layout/ProjectTree/customProductsLogic'import { getItemId } from '~/layout/panel-layout/ProjectTree/utils'-import { UserProductListItem, UserProductListReason } from '~/queries/schema/schema-general'+import { UserProductListItem } from '~/queries/schema/schema-general'const PRODUCTS_ROOT = 'products://'@@ -143,8 +143,6 @@ export const editToolsLogic = kea<editToolsLogicType>([id: '',product_path: toolPath,enabled: true,- reason: UserProductListReason.PRODUCT_INTENT,- reason_text: null,created_at: now,updated_at: now,})diff --git a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsxindex 6e3d48684931..6e435d6f94c4 100644--- a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx+++ b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelAdvertisement.tsx@@ -9,19 +9,15 @@ import { userLogic } from 'scenes/userLogic'import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'import { CampaignPayload, isCampaignPayload } from './navPanelAdShared'-import { navPanelAdvertisementRecommendedLogic } from './navPanelAdvertisementRecommendedLogic'import { NavPanelCampaignAd } from './NavPanelCampaignAd'import { NavPanelCmdKAd } from './NavPanelCmdKAd'import { NavPanelProductPushAd } from './NavPanelProductPushAd'import { navPanelProductPushLogic } from './navPanelProductPushLogic'-import { NavPanelRecommendationAd } from './NavPanelRecommendationAd'/** Give people a few days of real usage before nudging them about search - day-one users have nothing to search for yet. */const CMD_K_AD_MIN_DAYS_SINCE_JOINING = 3export function NavPanelAdvertisement(): JSX.Element | null {- const logic = navPanelAdvertisementRecommendedLogic()- const { oldestRecommendedProduct } = useValues(logic)const { activeCampaign } = useValues(navPanelProductPushLogic)const { isLayoutNavCollapsed } = useValues(panelLayoutLogic)const { isCloudOrDev } = useValues(preflightLogic)@@ -54,9 +50,5 @@ export function NavPanelAdvertisement(): JSX.Element | null {return <NavPanelProductPushAd campaign={activeCampaign} />}- if (!oldestRecommendedProduct) {- return null- }-- return <NavPanelRecommendationAd recommendedProduct={oldestRecommendedProduct} />+ return null}diff --git a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelRecommendationAd.tsx b/frontend/src/lib/components/NavPanelAdvertisement/NavPanelRecommendationAd.tsxdeleted file mode 100644index d41c9f0703ad..000000000000--- a/frontend/src/lib/components/NavPanelAdvertisement/NavPanelRecommendationAd.tsx+++ /dev/null@@ -1,103 +0,0 @@-import { BindLogic, useValues } from 'kea'-import posthog from 'posthog-js'-import { useEffect } from 'react'--import { Link } from '@posthog/lemon-ui'--import { addProductIntent } from 'lib/utils/product-intents'--import { getTreeItemsProducts } from '~/products'-import {- FileSystemImport,- ProductIntentContext,- ProductKey,- UserProductListItem,- UserProductListReason,-} from '~/queries/schema/schema-general'--import { AdvertisementCard } from './navPanelAdShared'-import { navPanelAdvertisementLogic } from './NavPanelAdvertisementLogic'--const getReasonText = (product: UserProductListItem): string | null => {- if (product.reason_text) {- return product.reason_text- }-- switch (product.reason) {- case UserProductListReason.SALES_LED:- return "We've added this product to your sidebar because we believe you'd benefit from it! Your TAM will reach out to help you learn more about it."- case UserProductListReason.NEW_PRODUCT:- return "We've just released this new product. Based on your usage, we believe you'll like it. Give it a try!"- }-- return null-}--export function NavPanelRecommendationAd({- recommendedProduct,-}: {- recommendedProduct: UserProductListItem-}): JSX.Element | null {- const allProducts = getTreeItemsProducts()- const productInfo: FileSystemImport | undefined = allProducts.find(- (p: FileSystemImport) => p.path === recommendedProduct.product_path- )-- const logicProps = { campaign: recommendedProduct.product_path }- const logic = navPanelAdvertisementLogic(logicProps)- const { hidden } = useValues(logic)-- useEffect(() => {- if (!hidden && productInfo) {- posthog.capture('nav panel advertisement shown', {- product_path: recommendedProduct.product_path,- product_id: recommendedProduct.id,- })- }- }, [recommendedProduct.product_path, recommendedProduct.id, productInfo, hidden])-- const reasonText = getReasonText(recommendedProduct)- if (hidden || !productInfo || !reasonText) {- return null- }-- return (- <div className="w-full">- <Link- to={productInfo.href}- className="text-primary"- onClick={() => {- posthog.capture('nav panel advertisement clicked', {- product_path: recommendedProduct.product_path,- product_id: recommendedProduct.id,- })- if (productInfo.intents && productInfo.intents.length > 0) {- const productKey = productInfo.intents[0]- if (productKey in ProductKey) {- addProductIntent({- product_type: productKey as ProductKey,- intent_context: ProductIntentContext.NAV_PANEL_ADVERTISEMENT_CLICKED,- metadata: { product_path: recommendedProduct.product_path },- })- }- }- }}- >- <BindLogic logic={navPanelAdvertisementLogic} props={logicProps}>- <AdvertisementCard- emoji="✨"- emojiLabel="sparkles"- title={productInfo.displayLabel ?? productInfo.path}- text={getReasonText(recommendedProduct) ?? ''}- onClose={() => {- posthog.capture('nav panel advertisement dismissed', {- product_path: recommendedProduct.product_path,- product_id: recommendedProduct.id,- })- }}- />- </BindLogic>- </Link>- </div>- )-}diff --git a/frontend/src/lib/components/NavPanelAdvertisement/navPanelAdvertisementRecommendedLogic.ts b/frontend/src/lib/components/NavPanelAdvertisement/navPanelAdvertisementRecommendedLogic.tsdeleted file mode 100644index bd726fdc99af..000000000000--- a/frontend/src/lib/components/NavPanelAdvertisement/navPanelAdvertisementRecommendedLogic.ts+++ /dev/null@@ -1,80 +0,0 @@-import { MakeLogicType, connect, kea, path, selectors } from 'kea'--import { customProductsLogic } from '~/layout/panel-layout/ProjectTree/customProductsLogic'-import { type UserProductListItem, UserProductListReason } from '~/queries/schema/schema-general'--const RECOMMENDED_PRODUCT_CREATED_AT_THRESHOLD_IN_DAYS = 7-const RECOMMENDED_PRODUCT_REASONS: UserProductListReason[] = [- UserProductListReason.SALES_LED,- UserProductListReason.NEW_PRODUCT,-]--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface navPanelAdvertisementRecommendedLogicValues {- customProducts: UserProductListItem[] // customProductsLogic- oldestRecommendedProduct: UserProductListItem | null- recommendedProducts: UserProductListItem[]-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface navPanelAdvertisementRecommendedLogicMeta {- __keaTypeGenInternalSelectorTypes: {- recommendedProducts: (customProducts: UserProductListItem[]) => UserProductListItem[]- oldestRecommendedProduct: (recommendedProducts: UserProductListItem[]) => UserProductListItem | null- }-}--export type navPanelAdvertisementRecommendedLogicType = MakeLogicType<- navPanelAdvertisementRecommendedLogicValues,- {},- Record<string, any>,- navPanelAdvertisementRecommendedLogicMeta->--export const navPanelAdvertisementRecommendedLogic = kea<navPanelAdvertisementRecommendedLogicType>([- path(['lib', 'components', 'NavPanelAdvertisement', 'navPanelAdvertisementRecommendedLogic']),- connect(() => ({- values: [customProductsLogic, ['customProducts']],- })),- selectors({- recommendedProducts: [- (s) => [s.customProducts],- (customProducts: UserProductListItem[]): UserProductListItem[] => {- const createdAtThreshold = new Date()- createdAtThreshold.setDate(- createdAtThreshold.getDate() - RECOMMENDED_PRODUCT_CREATED_AT_THRESHOLD_IN_DAYS- )-- // Filter for the items we care about recommending in the ad slot, created in the last 7 days- return customProducts.filter(- (item) =>- RECOMMENDED_PRODUCT_REASONS.includes(item.reason) &&- item.enabled &&- new Date(item.created_at) >= createdAtThreshold- )- },- ],- oldestRecommendedProduct: [- (s) => [s.recommendedProducts],- (recommendedProducts: UserProductListItem[]): UserProductListItem | null => {- if (recommendedProducts.length === 0) {- return null- }-- // Find the oldest recommended product- // Not using sort to make this more performant, where's TS' stdlib when you need it?- let oldestRecommendedProduct: UserProductListItem | null = null- let oldestRecommendedProductDate: Date | null = null- for (const product of recommendedProducts) {- const productDate = new Date(product.created_at)- if (!oldestRecommendedProductDate || productDate < oldestRecommendedProductDate) {- oldestRecommendedProduct = product- oldestRecommendedProductDate = productDate- }- }-- return oldestRecommendedProduct- },- ],- }),-])diff --git a/frontend/src/lib/components/Superpowers/Superpowers.tsx b/frontend/src/lib/components/Superpowers/Superpowers.tsxindex 17ba19981b8c..798319cb1aba 100644--- a/frontend/src/lib/components/Superpowers/Superpowers.tsx+++ b/frontend/src/lib/components/Superpowers/Superpowers.tsx@@ -219,9 +219,6 @@ function ProductsSection(): JSX.Element {{iconForType(item.iconType)}</span><span className="flex-1 text-sm font-medium truncate">{item.path}</span>- {listItem?.reason && (- <span className="text-xs text-muted shrink-0">{listItem.reason}</span>- )}<EnablementTag enabled={!!listItem} /></div>{team && (diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 9e8b49e5284f..5f07cd997411 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -27387,14 +27387,6 @@"description": "Protocol of the item, defaults to \"project://\"","type": "string"},- "reason": {- "$ref": "#/definitions/UserProductListReason",- "description": "Reason for custom product suggestion (from UserProductList)"- },- "reasonText": {- "description": "Custom reason text for custom product suggestion (from UserProductList)",- "type": ["string", "null"]- },"ref": {"description": "Object's ID or other unique reference","type": "string"@@ -55085,33 +55077,13 @@"product_path": {"type": "string"},- "reason": {- "$ref": "#/definitions/UserProductListReason"- },- "reason_text": {- "type": ["string", "null"]- },"updated_at": {"type": "string"}},- "required": ["id", "product_path", "enabled", "reason", "reason_text", "created_at", "updated_at"],+ "required": ["id", "product_path", "enabled", "created_at", "updated_at"],"type": "object"},- "UserProductListReason": {- "enum": [- "default",- "onboarding",- "product_intent",- "used_by_colleagues",- "used_similar_products",- "used_on_separate_team",- "new_product",- "sales_led",- "onboarding_delegated"- ],- "type": "string"- },"UserUIConfiguration": {"additionalProperties": {},"description": "Per-user UI customization, persisted on the User model as a single JSONB blob. A null configuration and any absent key mean \"default\", which for visibility is \"shown\", so newly added UI surfaces appear for everyone until explicitly hidden. Writers must send the complete object; the server validates and replaces it wholesale.",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex ac3285161455..e6ad6a996aa6 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -5015,10 +5015,6 @@ export interface FileSystemImport extends Omit<FileSystemEntry, 'id'> {sceneKeys?: string[]/** Product key(s) that generate interest in this item when intent is triggered */intents?: ProductKey[]- /** Reason for custom product suggestion (from UserProductList) */- reason?: UserProductListReason- /** Custom reason text for custom product suggestion (from UserProductList) */- reasonText?: string | null/** Display label override — when set, shown in the nav instead of the last segment of `path` */displayLabel?: string}@@ -9814,24 +9810,10 @@ export interface ProductsData {metadata: ProductItem[]}-export enum UserProductListReason {- DEFAULT = 'default',- ONBOARDING = 'onboarding',- PRODUCT_INTENT = 'product_intent',- USED_BY_COLLEAGUES = 'used_by_colleagues',- USED_SIMILAR_PRODUCTS = 'used_similar_products',- USED_ON_SEPARATE_TEAM = 'used_on_separate_team',- NEW_PRODUCT = 'new_product',- SALES_LED = 'sales_led',- ONBOARDING_DELEGATED = 'onboarding_delegated',-}-export interface UserProductListItem {id: stringproduct_path: stringenabled: boolean- reason: UserProductListReason- reason_text: string | nullcreated_at: stringupdated_at: string}diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.pyindex e5a3b7de34a6..a35fef73f474 100644--- a/posthog/admin/admins/team_admin.py+++ b/posthog/admin/admins/team_admin.py@@ -33,7 +33,6 @@ from temporalio.common import SearchAttributePair, TypedSearchAttributesfrom posthog.admin.inlines.organization_member_for_related_inline import OrganizationMemberForRelatedInlinefrom posthog.admin.inlines.team_experiments_config_inline import TeamExperimentsConfigInlinefrom posthog.admin.inlines.team_marketing_analytics_config_inline import TeamMarketingAnalyticsConfigInline-from posthog.admin.inlines.user_product_list_inline import UserProductListInlinefrom posthog.helpers.impersonation import is_impersonatedfrom posthog.llm.gateway_internal_client import AIGatewayInternalError, AIGatewayNotConfigured, add_credit, get_walletfrom posthog.models import Team@@ -188,7 +187,6 @@ class TeamAdmin(admin.ModelAdmin):OrganizationMemberForRelatedInline,TeamMarketingAnalyticsConfigInline,TeamExperimentsConfigInline,- UserProductListInline,]def changeform_view(self, request, object_id=None, form_url="", extra_context=None):diff --git a/posthog/admin/admins/user_product_list_admin.py b/posthog/admin/admins/user_product_list_admin.pyindex d462cc808de6..6f268ae1bd22 100644--- a/posthog/admin/admins/user_product_list_admin.py+++ b/posthog/admin/admins/user_product_list_admin.py@@ -5,10 +5,9 @@ from posthog.models.file_system.user_product_list import UserProductList@admin.register(UserProductList)class UserProductListAdmin(admin.ModelAdmin):- list_display = ("id", "user", "team", "product_path", "reason", "enabled", "updated_at")+ list_display = ("id", "user", "team", "product_path", "enabled", "updated_at")list_display_links = ("id",)list_filter = (- "reason","product_path","enabled",("created_at", admin.DateFieldListFilter),@@ -22,8 +21,6 @@ class UserProductListAdmin(admin.ModelAdmin):"user","team","product_path",- "reason",- "reason_text","enabled","created_at","updated_at",@@ -39,7 +36,7 @@ class UserProductListAdmin(admin.ModelAdmin):("Status",{- "fields": ["enabled", "reason", "reason_text"],+ "fields": ["enabled"],},),(diff --git a/posthog/admin/inlines/user_product_list_inline.py b/posthog/admin/inlines/user_product_list_inline.pydeleted file mode 100644index c7c8070d5666..000000000000--- a/posthog/admin/inlines/user_product_list_inline.py+++ /dev/null@@ -1,159 +0,0 @@-from django import forms-from django.contrib import admin-from django.core.exceptions import ValidationError--from posthog.models.file_system.user_product_list import UserProductList-from posthog.products import Products---class UserProductListInlineForm(forms.ModelForm):- class Meta:- model = UserProductList- fields = ["user", "product_path", "reason", "reason_text", "enabled"]-- def __init__(self, *args, **kwargs):- # Extract parent_instance from kwargs if present (set by formset)- self.parent_instance = kwargs.pop("parent_instance", None)- super().__init__(*args, **kwargs)-- # Restrict reason to sales_led only and disable it- self.fields["reason"].choices = [("", "---------"), *UserProductList.Reason.choices] # type: ignore- self.fields["reason"].initial = UserProductList.Reason.SALES_LED- self.fields["reason"].widget = forms.Select(choices=self.fields["reason"].choices) # type: ignore- self.fields["reason"].disabled = True-- # Set product_path choices from Products- product_paths = Products.get_product_paths()- self.fields["product_path"].widget = forms.Select(- choices=[("", "---------")] + [(path, path) for path in product_paths]- )-- # Filter users to only show users from the team's organization- parent_instance = getattr(self, "parent_instance", None)-- # Determine which team to use for filtering- team = None- if self.instance and not self.instance._state.adding:- # Check if instance has team_id set (safer than accessing .team directly)- if hasattr(self.instance, "team_id") and self.instance.team_id:- try:- team = self.instance.team- except UserProductList.team.RelatedObjectDoesNotExist:- pass-- # If no team from instance, use parent (for new instances)- if not team and parent_instance:- team = parent_instance-- if team and hasattr(team, "organization_id") and team.organization_id:- from posthog.models.user import User-- self.fields["user"].queryset = User.objects.filter( # type: ignore- organization_membership__organization_id=team.organization_id- ).distinct()-- self.fields["reason_text"].required = False- self.fields["reason_text"].widget.attrs["rows"] = 8- self.fields["reason_text"].widget.attrs["placeholder"] = (- "We default to displaying this message in the UI when adding a new product: \"We've added this product to your sidebar because we believe you'd benefit from it! Your TAM will reach out to help you learn more about it.\""- "\nYou can override with a custom message here, make it personal!"- "\n\nExample: Hey, it's Rafael. I believe you'll like using our new SQL Editor! I went ahead and gave you 1,000,000 free rows, Merry Christmas!"- )-- # Set enabled default to True and read-only- self.fields["enabled"].initial = True- self.fields["enabled"].disabled = True-- def clean(self):- cleaned_data = super().clean()-- if not cleaned_data:- return cleaned_data-- user = cleaned_data.get("user")-- errors = {}-- # Only validate for new instances (when creating, not editing)- if user and user.allow_sidebar_suggestions is False:- errors["user"] = f"User has disabled sidebar suggestions, can't update."-- if self.instance and not self.instance._state.adding:- if (user := cleaned_data.get("user")) and user != self.instance.user:- errors["user"] = f"User cannot be changed."- if (product_path := cleaned_data.get("product_path")) and product_path != self.instance.product_path:- errors["product_path"] = f"Product path cannot be changed."- if (reason := cleaned_data.get("reason")) and reason != self.instance.reason:- errors["reason"] = f"Reason cannot be changed."-- if self.instance.reason != UserProductList.Reason.SALES_LED:- if (reason_text := cleaned_data.get("reason_text")) and reason_text != self.instance.reason_text:- errors["reason_text"] = f"Reason text cannot be changed."-- if errors:- raise ValidationError(errors)-- return cleaned_data-- def save(self, commit=True):- instance = super().save(commit=False)-- # For existing instances, only save reason_text and enabled- if not instance._state.adding:- # Only reason_text and enabled can be changed- # so guarantee we preserve the existing values when saving- existing = UserProductList.objects.get(pk=instance.pk)- instance.user = existing.user- instance.product_path = existing.product_path- instance.reason = existing.reason- instance.team = existing.team- else:- # Set defaults- if not instance.reason:- instance.reason = UserProductList.Reason.SALES_LED-- # Set team from parent instance- parent_instance = getattr(self, "parent_instance", None)- if not instance.team_id and parent_instance:- instance.team = parent_instance-- if commit:- instance.save()-- return instance---class UserProductListInline(admin.TabularInline):- model = UserProductList- form = UserProductListInlineForm- extra = 1- fields = ("user", "product_path", "reason", "reason_text", "enabled")- readonly_fields = ("id",)- verbose_name = "User Product Entry"- verbose_name_plural = "User Product entries (sales led only)"- classes = ("collapse",)-- def get_queryset(self, request):- qs = super().get_queryset(request)- return qs.filter(reason=UserProductList.Reason.SALES_LED)-- def get_formset(self, request, obj=None, **kwargs):- formset = super().get_formset(request, obj, **kwargs)- # Store parent instance (Team) in form for filtering users and setting team- original_init = formset.form.__init__-- def form_init(self, *args, **kwargs):- kwargs["parent_instance"] = obj- result = original_init(self, *args, **kwargs)- return result-- formset.form.__init__ = form_init # type: ignore- return formset-- def has_change_permission(self, request, obj=None):- # Allow editing reason_text- return True-- def has_delete_permission(self, request, obj=None):- # Don't allow deletion from inline- return Falsediff --git a/posthog/api/file_system/user_product_list.py b/posthog/api/file_system/user_product_list.pyindex 69d3491c8b56..ebe89f4630d5 100644--- a/posthog/api/file_system/user_product_list.py+++ b/posthog/api/file_system/user_product_list.py@@ -21,16 +21,12 @@ class UserProductListSerializer(serializers.ModelSerializer):"id","product_path","enabled",- "reason",- "reason_text","created_at","updated_at",]read_only_fields = ["id","product_path",- "reason",- "reason_text","created_at","updated_at",]@@ -47,15 +43,6 @@ class UserProductListSerializer(serializers.ModelSerializer):return user_product_list- def update(self, instance: UserProductList, validated_data: dict[str, Any]) -> UserProductList:- enabled = validated_data.get("enabled", instance.enabled)-- if enabled:- validated_data["reason"] = UserProductList.Reason.PRODUCT_INTENT- validated_data["reason_text"] = ""-- return super().update(instance, validated_data)-class UserProductListViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):queryset = UserProductList.objects.all()diff --git a/posthog/dags/locations/growth.py b/posthog/dags/locations/growth.pyindex 9748f9c0c647..839f6d8237ff 100644--- a/posthog/dags/locations/growth.py+++ b/posthog/dags/locations/growth.py@@ -8,7 +8,6 @@ from products.growth.dags import (oauth,product_push_campaigns,team_production_event_activation,- user_product_list,)from . import loggers, resources@@ -16,11 +15,6 @@ from . import loggers, resourcesjobs = [oauth.oauth_clear_expired_oauth_tokens_job,github_sdk_versions.cache_github_sdk_versions_job,- user_product_list.populate_user_product_list_job,- # Kept unscheduled: connection-time default seeding replaced the monthly colleague- # sync, but the job stays available for manual runs.- user_product_list.sync_colleagues_products_monthly_job,- user_product_list.sync_cross_sell_products_monthly_job,team_production_event_activation.detect_first_team_production_event_job,product_push_campaigns.product_push_campaigns_job,# Manual-run only: growth names the organizations, product, and window per run.@@ -29,7 +23,6 @@ jobs = [schedules = [oauth.oauth_clear_expired_oauth_tokens_schedule,github_sdk_versions.cache_github_sdk_versions_schedule,- user_product_list.sync_cross_sell_products_monthly_schedule,team_production_event_activation.detect_first_team_production_event_schedule,product_push_campaigns.product_push_campaigns_schedule,]diff --git a/posthog/migrations/1328_remove_userproductlist_reason_state.py b/posthog/migrations/1328_remove_userproductlist_reason_state.pynew file mode 100644index 000000000000..10464d82fc58--- /dev/null+++ b/posthog/migrations/1328_remove_userproductlist_reason_state.py@@ -0,0 +1,30 @@+from django.db import migrations+++class Migration(migrations.Migration):+ """Take `reason` / `reason_text` out of Django's model state only.++ The columns stay in Postgres so a rollback to the previous release still works, and+ so in-flight requests on old code keep writing to columns that still exist. A later+ migration drops them for real - see safe-django-migrations.md "Dropping Columns".+ """++ dependencies = [+ ("posthog", "1327_untrack_cimd_metadata_url"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.RemoveField(+ model_name="userproductlist",+ name="reason",+ ),+ migrations.RemoveField(+ model_name="userproductlist",+ name="reason_text",+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 96baef4701fe..e58cbed2d9fa 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1327_untrack_cimd_metadata_url+1328_remove_userproductlist_reason_statediff --git a/posthog/models/file_system/test/test_user_product_list.py b/posthog/models/file_system/test/test_user_product_list.pyindex 97dc82c56b20..73b2e0d5c79d 100644--- a/posthog/models/file_system/test/test_user_product_list.py+++ b/posthog/models/file_system/test/test_user_product_list.py@@ -1,28 +1,13 @@from posthog.test.base import BaseTest-from posthog.schema import ProductItemCategory-from posthog.models import Userfrom posthog.models.file_system.user_product_list import (DEFAULT_PRODUCT_PATHS,UserProductList,add_default_products_for_user,- get_user_product_list_count,)from posthog.products import Products-from products.growth.backend.cross_sell_candidate_selector import (- BASE_PREFERENCE_WEIGHTS,- DEFAULT_IGNORED_CATEGORIES,- CrossSellCandidateSelector,-)---def _get_favored_product_paths() -> set[str]:- """Derive the favored product paths from the selector constants."""- selector = CrossSellCandidateSelector(user_enabled_products=set(), ignored_categories=DEFAULT_IGNORED_CATEGORIES)- return {p for key in BASE_PREFERENCE_WEIGHTS for p in selector.intent_to_paths.get(key, [])}-class TestUserProductList(BaseTest):def test_default_product_paths_are_valid_products(self):@@ -40,7 +25,6 @@ class TestUserProductList(BaseTest):assert {row.product_path for row in rows} == set(DEFAULT_PRODUCT_PATHS)for row in rows:assert row.enabled is True- assert row.reason == UserProductList.Reason.DEFAULTdef test_add_default_products_leaves_existing_rows_untouched(self):user = User.objects.create_user(email="[email protected]", password="password", first_name="User")@@ -50,7 +34,6 @@ class TestUserProductList(BaseTest):team=self.team,product_path="Product analytics",enabled=False,- reason=UserProductList.Reason.PRODUCT_INTENT,)created_items = add_default_products_for_user(user, self.team)@@ -58,7 +41,6 @@ class TestUserProductList(BaseTest):assert "Product analytics" not in {item.product_path for item in created_items}existing = UserProductList.objects.get(user=user, team=self.team, product_path="Product analytics")assert existing.enabled is False- assert existing.reason == UserProductList.Reason.PRODUCT_INTENTadd_default_products_for_user(user, self.team)assert UserProductList.objects.filter(user=user, team=self.team).count() == len(DEFAULT_PRODUCT_PATHS)@@ -74,308 +56,3 @@ class TestUserProductList(BaseTest):assert {row.product_path for row in rows} == set(DEFAULT_PRODUCT_PATHS)for row in rows:assert row.enabled is True- assert row.reason == UserProductList.Reason.DEFAULT-- def test_sync_cross_sell_products_suggests_same_category_or_favored(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- UserProductList.objects.create(user=user, team=self.team, product_path="Product analytics", enabled=True)-- created_items = UserProductList.sync_cross_sell_products(user=user, team=self.team)-- by_category = Products.get_products_by_category()- analytics_products = set(by_category.get(ProductItemCategory.ANALYTICS, []))- # Favored products are always candidates even if from a different category- favored_products = _get_favored_product_paths()- valid_candidates = analytics_products | favored_products-- assert len(created_items) == 1- for item in created_items:- assert item.reason == UserProductList.Reason.USED_SIMILAR_PRODUCTS- assert item.enabled is True- assert item.product_path in valid_candidates- assert item.product_path != "Product analytics"-- def test_sync_cross_sell_products_excludes_existing_products(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- UserProductList.objects.create(user=user, team=self.team, product_path="Product analytics", enabled=True)- UserProductList.objects.create(user=user, team=self.team, product_path="Dashboards", enabled=True)-- created_items: list[UserProductList] = []- while True:- items = UserProductList.sync_cross_sell_products(user=user, team=self.team)- if len(items) == 0:- break- created_items.extend(items)-- created_paths = {item.product_path for item in created_items}- assert "Product analytics" not in created_paths- assert "Dashboards" not in created_paths-- def test_sync_cross_sell_products_respects_allow_sidebar_suggestions_false(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=False- )-- UserProductList.objects.create(user=user, team=self.team, product_path="Product analytics", enabled=True)-- created_items = UserProductList.sync_cross_sell_products(user=user, team=self.team)- assert len(created_items) == 0-- def test_sync_cross_sell_products_respects_max_products(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- UserProductList.objects.create(user=user, team=self.team, product_path="Product analytics", enabled=True)-- created_items = UserProductList.sync_cross_sell_products(user=user, team=self.team, max_products=3)- assert 1 <= len(created_items) <= 3-- def test_sync_cross_sell_products_with_no_enabled_products_suggests_favored(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- created_items = UserProductList.sync_cross_sell_products(user=user, team=self.team)-- # Even with no enabled products, favored products are still candidates- favored_products = _get_favored_product_paths()- assert len(created_items) == 1- assert created_items[0].product_path in favored_products-- def test_sync_cross_sell_products_candidates_include_same_category_and_favored(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- UserProductList.objects.create(user=user, team=self.team, product_path="Product analytics", enabled=True)-- products_by_category = Products.get_products_by_category()- analytics_products = set(products_by_category.get(ProductItemCategory.ANALYTICS, []))- favored_products = _get_favored_product_paths()- valid_candidates = (analytics_products | favored_products) - {"Product analytics"}-- created_items = UserProductList.sync_cross_sell_products(user=user, team=self.team, max_products=5)-- created_paths = {item.product_path for item in created_items}- for path in created_paths:- assert path in valid_candidates-- def test_sync_cross_sell_products_ignores_tools_and_unreleased_categories(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- products_by_category = Products.get_products_by_category()- tools_products = products_by_category.get(ProductItemCategory.TOOLS, [])- unreleased_products = products_by_category.get(ProductItemCategory.UNRELEASED, [])-- # Add a product from the Tools category- assert tools_products- assert "Web scripts" in tools_products- UserProductList.objects.create(user=user, team=self.team, product_path="Web scripts", enabled=True)-- # Add a product from the Unreleased category- assert unreleased_products- UserProductList.objects.create(user=user, team=self.team, product_path=unreleased_products[0], enabled=True)-- created_items = UserProductList.sync_cross_sell_products(user=user, team=self.team)- created_paths = {item.product_path for item in created_items}- assert not created_paths.intersection(tools_products)- assert not created_paths.intersection(unreleased_products)-- def test_sync_cross_sell_products_respects_custom_ignored_categories(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- UserProductList.objects.create(user=user, team=self.team, product_path="Product analytics", enabled=True)-- created_items = UserProductList.sync_cross_sell_products(- user=user, team=self.team, ignored_categories=[ProductItemCategory.ANALYTICS]- )-- products_by_category = Products.get_products_by_category()- analytics_products = set(products_by_category.get(ProductItemCategory.ANALYTICS, []))-- created_paths = {item.product_path for item in created_items}- assert not created_paths.intersection(analytics_products)-- def test_sync_cross_sell_products_falls_back_to_all_categories_when_no_same_category_or_favored(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- products_by_category = Products.get_products_by_category()- favored_products = _get_favored_product_paths()-- # Enable all favored products and all products from a category so the first candidate set- # (same-category + favored) would be empty, triggering the fallback to all categories.- for path in favored_products:- UserProductList.objects.create(user=user, team=self.team, product_path=path, enabled=True)- analytics_products = set(products_by_category.get(ProductItemCategory.ANALYTICS, []))- for path in analytics_products - favored_products:- UserProductList.objects.create(user=user, team=self.team, product_path=path, enabled=True)-- created_items = UserProductList.sync_cross_sell_products(user=user, team=self.team)-- # Should still suggest something via the fallback to all non-ignored categories- assert len(created_items) == 1- tools_products = set(products_by_category.get(ProductItemCategory.TOOLS, []))- unreleased_products = set(products_by_category.get(ProductItemCategory.UNRELEASED, []))- assert created_items[0].product_path not in tools_products- assert created_items[0].product_path not in unreleased_products- assert created_items[0].product_path not in favored_products | analytics_products-- def test_sync_cross_sell_products_same_category_gets_weight_bump(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- UserProductList.objects.create(user=user, team=self.team, product_path="Product analytics", enabled=True)-- products_by_category = Products.get_products_by_category()- analytics_products = set(products_by_category.get(ProductItemCategory.ANALYTICS, [])) - {"Product analytics"}-- all_created_paths: set[str] = set()- for _ in range(50):- items = UserProductList.sync_cross_sell_products(user=user, team=self.team)- for item in items:- all_created_paths.add(item.product_path)- UserProductList.objects.filter(- user=user, team=self.team, product_path__in=[i.product_path for i in items]- ).exclude(product_path="Product analytics").delete()-- assert len(all_created_paths & analytics_products) > 0-- def test_sync_cross_sell_products_returns_empty_when_all_products_enabled(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- # Enable all products- for product in Products.products():- UserProductList.objects.create(user=user, team=self.team, product_path=product.path, enabled=True)-- created_items = UserProductList.sync_cross_sell_products(user=user, team=self.team)- assert len(created_items) == 0-- def test_sync_from_team_colleagues_filters_out_existing_products(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- UserProductList.objects.create(user=user, team=self.team, product_path="Product analytics", enabled=True)- UserProductList.objects.create(user=user, team=self.team, product_path="Feature flags", enabled=True)-- hardcoded_counts = [- {"product_path": "Product analytics", "colleague_count": 5},- {"product_path": "Session replay", "colleague_count": 4},- {"product_path": "Feature flags", "colleague_count": 3},- {"product_path": "Surveys", "colleague_count": 2},- ]-- created_items = UserProductList.sync_from_team_colleagues(- user=user, team=self.team, count=2, colleague_product_counts=hardcoded_counts- )-- assert {item.product_path for item in created_items} == {"Session replay", "Surveys"}- for item in created_items:- assert item.reason == UserProductList.Reason.USED_BY_COLLEAGUES- assert item.enabled is True-- def test_sync_from_team_colleagues_ranks_by_counts_and_respects_limit(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- hardcoded_counts = [- {"product_path": "Product analytics", "colleague_count": 10},- {"product_path": "Session replay", "colleague_count": 8},- {"product_path": "Feature flags", "colleague_count": 5},- {"product_path": "Surveys", "colleague_count": 3},- {"product_path": "Experiments", "colleague_count": 1},- ]-- created_items = UserProductList.sync_from_team_colleagues(- user=user, team=self.team, count=3, colleague_product_counts=hardcoded_counts- )-- assert [item.product_path for item in created_items] == [- "Product analytics",- "Session replay",- "Feature flags",- ]-- def test_sync_from_team_colleagues_respects_allow_sidebar_suggestions_false(self):- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=False- )-- hardcoded_counts = [- {"product_path": "Product analytics", "colleague_count": 10},- {"product_path": "Session replay", "colleague_count": 8},- ]-- created_items = UserProductList.sync_from_team_colleagues(- user=user, team=self.team, colleague_product_counts=hardcoded_counts- )-- assert len(created_items) == 0-- def test_sync_from_team_colleagues_computes_counts_when_not_provided(self):- colleague1 = User.objects.create_user(- email="[email protected]", password="password", first_name="Colleague1"- )- colleague2 = User.objects.create_user(- email="[email protected]", password="password", first_name="Colleague2"- )- user = User.objects.create_user(- email="[email protected]", password="password", first_name="User", allow_sidebar_suggestions=True- )-- UserProductList.objects.create(user=colleague1, team=self.team, product_path="Product analytics", enabled=True)- UserProductList.objects.create(user=colleague2, team=self.team, product_path="Product analytics", enabled=True)- UserProductList.objects.create(user=colleague1, team=self.team, product_path="Session replay", enabled=True)-- created_items = UserProductList.sync_from_team_colleagues(user=user, team=self.team, count=2)-- assert {item.product_path for item in created_items} == {"Product analytics", "Session replay"}-- def test_get_user_product_list_count_ranks_and_excludes_disabled(self):- # Counts are team-wide; drop the rows seeded for the fixture user so only- # the colleagues created below contribute.- UserProductList.objects.filter(team=self.team).delete()- colleague1 = User.objects.create_user(- email="[email protected]", password="password", first_name="Colleague1"- )- colleague2 = User.objects.create_user(- email="[email protected]", password="password", first_name="Colleague2"- )-- UserProductList.objects.create(user=colleague1, team=self.team, product_path="Product analytics", enabled=True)- UserProductList.objects.create(user=colleague2, team=self.team, product_path="Product analytics", enabled=True)- UserProductList.objects.create(user=colleague1, team=self.team, product_path="Feature flags", enabled=True)- UserProductList.objects.create(user=colleague1, team=self.team, product_path="Session replay", enabled=False)- UserProductList.objects.create(user=colleague2, team=self.team, product_path="Session replay", enabled=False)-- counts = get_user_product_list_count(self.team)-- assert counts == [- {"product_path": "Product analytics", "colleague_count": 2},- {"product_path": "Feature flags", "colleague_count": 1},- ]-- def test_user_product_list_reason_enum_matches_backend(self):- from posthog.schema import UserProductListReason-- backend_reasons = {key for key, _ in UserProductList.Reason.choices}- schema_reasons = {value for _, value in UserProductListReason.__members__.items()}-- assert backend_reasons == schema_reasons, "Backend reasons do not match schema reasons"diff --git a/posthog/models/file_system/user_product_list.py b/posthog/models/file_system/user_product_list.pyindex 9ab613765434..ab3b892ff918 100644--- a/posthog/models/file_system/user_product_list.py+++ b/posthog/models/file_system/user_product_list.py@@ -1,8 +1,7 @@-from typing import TYPE_CHECKING, Any, ClassVar, cast+from typing import TYPE_CHECKING, ClassVar, castfrom django.conf import settingsfrom django.db import models, transaction-from django.db.models import Countfrom django.db.models.expressions import Ffrom django.db.models.signals import post_savefrom django.dispatch.dispatcher import receiver@@ -10,9 +9,7 @@ from django.utils import timezonefrom posthog.models.utils import UpdatedMetaFields, UUIDModel, uuid7from posthog.products import Products-from posthog.schema_enums import ProductIntentContext, ProductItemCategory, ProductKey--from products.growth.backend.cross_sell_candidate_selector import DEFAULT_IGNORED_CATEGORIES, CrossSellCandidateSelector+from posthog.schema_enums import ProductItemCategory, ProductKeyif TYPE_CHECKING:from posthog.models.organization import Organization@@ -51,12 +48,7 @@ def add_default_products_for_user(user: "User", team: "Team") -> "list[UserProdu# `ignore_conflicts` + `unique_together` on (team, user, product_path) keep this# idempotent under concurrent seeding.return UserProductList.objects.bulk_create(- [- UserProductList(- user=user, team=team, product_path=path, enabled=True, reason=UserProductList.Reason.DEFAULT- )- for path in missing_paths- ],+ [UserProductList(user=user, team=team, product_path=path, enabled=True) for path in missing_paths],ignore_conflicts=True,)@@ -76,37 +68,6 @@ def add_default_products_for_accessible_teams(user: "User", organization: "Organadd_default_products_for_user(user, team)-def get_user_product_list_count(team: "Team") -> list[dict[str, Any]]:- """- Get product counts for all items in a team, ranked by popularity.- Returns a list of dicts with 'product_path' and 'colleague_count' keys, ordered by count descending.-- Excludes rows seeded by onboarding-delegation: those are an "explore everything" default- for the delegator only and shouldn't drive what subsequent teammates see in their sidebar.- The actual setup person's choices (ONBOARDING / PRODUCT_INTENT) remain the colleague signal.- """- return list[dict[str, Any]](- UserProductList.objects.filter(team=team, enabled=True)- .exclude(reason=UserProductList.Reason.ONBOARDING_DELEGATED)- .values("product_path")- .annotate(colleague_count=Count("user", distinct=True))- .order_by("-colleague_count")- )---def backfill_user_product_list_for_new_user(user: "User", team: "Team") -> None:- """- Backfill UserProductList entries for a new user in a new team based on what- they have enabled in other teams they belong to.-- Not called from any active flow - connection-time seeding uses- `add_default_products_for_user` instead - but kept alongside the colleague-sync- Dagster job in case we bring inheritance-based suggestions back.- """- UserProductList.backfill_from_other_teams(user, team)- UserProductList.sync_from_team_colleagues(user, team, count=3)--class UserProductList(UUIDModel, UpdatedMetaFields):"""Stores a user's custom list of products they care about.@@ -128,40 +89,6 @@ class UserProductList(UUIDModel, UpdatedMetaFields):# Not using `CreatedMetaFields` because of the clashing `user` reference with `created_by`created_at = models.DateTimeField(auto_now_add=True)- class Reason(models.TextChoices):- # Part of the default product set added whenever a user gains access to a project- DEFAULT = "default", "Default"-- # User chose this product during onboarding- ONBOARDING = "onboarding", "Onboarding"-- # User showed intent for the product- PRODUCT_INTENT = "product_intent", "Product Intent"-- # Colleagues on the same team have the product in their sidebar- USED_BY_COLLEAGUES = "used_by_colleagues", "Used by Colleagues"-- # User has a similar product in their sidebar, DEPRECATED- USED_SIMILAR_PRODUCTS = "used_similar_products", "Used Similar Products"-- # User has this product on another team they belong to- USED_ON_SEPARATE_TEAM = "used_on_separate_team", "Used on Separate Team"-- # We launch a new product and want to foster adoption- NEW_PRODUCT = "new_product", "New Product"-- # Sales team can go in and automatically add a product to someone's sidebar- SALES_LED = "sales_led", "Sales Led"-- # User delegated onboarding setup to a teammate; we pre-populate their sidebar so- # the post-delegation home page isn't empty.- ONBOARDING_DELEGATED = "onboarding_delegated", "Onboarding Delegated"-- # When the system suggests a product to the user, we store the reason why we suggested it in here- # And and optional freeform text field to be displayed to the user on hover- reason: models.CharField = models.CharField(max_length=32, choices=Reason, null=True)- reason_text: models.TextField = models.TextField(null=True)-# There's a difference between the `UserProductList` not existing and it being disabled# If it's not existing it just means the user hasn't decided whether they want that in# the sidebar or not. In that case, we're free to add it to the sidebar as a suggestion@@ -180,11 +107,7 @@ class UserProductList(UUIDModel, UpdatedMetaFields):verbose_name_plural = "User Product Lists"@staticmethod- def enable_all_for_user(- user: "User",- team: "Team",- reason: "UserProductList.Reason",- ) -> "list[UserProductList]":+ def enable_all_for_user(user: "User", team: "Team") -> "list[UserProductList]":"""Enable every released product in the sidebar for a user on a given team.Skips Unreleased/alpha products — those are intentionally opt-in (mirroring the@@ -202,14 +125,11 @@ class UserProductList(UUIDModel, UpdatedMetaFields):# disabled. `unique_together` on (team, user, product_path) makes this idempotent.# `auto_now` doesn't fire on bulk update, so set updated_at explicitly.UserProductList.objects.bulk_create(- [- UserProductList(user=user, team=team, product_path=path, enabled=True, reason=reason)- for path in target_paths- ],+ [UserProductList(user=user, team=team, product_path=path, enabled=True) for path in target_paths],ignore_conflicts=True,)UserProductList.objects.filter(user=user, team=team, product_path__in=target_paths, enabled=False).update(- enabled=True, reason=reason, updated_at=timezone.now()+ enabled=True, updated_at=timezone.now())return list(UserProductList.objects.filter(user=user, team=team, product_path__in=target_paths))@@ -222,180 +142,18 @@ class UserProductList(UUIDModel, UpdatedMetaFields):if not products:return []- onboarding_contexts = [- ProductIntentContext.ONBOARDING_PRODUCT_SELECTED___PRIMARY,- ProductIntentContext.ONBOARDING_PRODUCT_SELECTED___SECONDARY,- ProductIntentContext.QUICK_START_PRODUCT_SELECTED,- ]- has_onboarding_context = any(context in (product_intent.contexts or {}) for context in onboarding_contexts)- reason = UserProductList.Reason.ONBOARDING if has_onboarding_context else UserProductList.Reason.PRODUCT_INTENT-user_product_lists = []for product in products:item, _ = UserProductList.objects.get_or_create(user=user,team=product_intent.team,product_path=product.path,- defaults={- "enabled": True,- "reason": reason,- },+ defaults={"enabled": True},)user_product_lists.append(item)return user_product_lists- @staticmethod- def sync_from_team_colleagues(- user: "User",- team: "Team",- count: int = 1,- colleague_product_counts: list[dict[str, Any]] | None = None,- ) -> "list[UserProductList]":- """- Create UserProductList entries for a user based on what their team colleagues have.- Products are ranked by how many colleagues have them enabled, and only the top `count`- items that the user doesn't already have enabled are included.-- Args:- user: The user to sync products for- team: The team to check colleagues in- count: Maximum number of products to suggest- colleague_product_counts: Optional precomputed colleague product counts.- If not provided, will be computed automatically.- """- if user.allow_sidebar_suggestions is False:- return []-- # Get products the user already has (enabled or disabled - we'll exclude these)- user_existing_products = set(- UserProductList.objects.filter(user=user, team=team).values_list("product_path", flat=True)- )-- # Count how many colleagues have each product_path enabled- if colleague_product_counts is None:- colleague_product_counts = get_user_product_list_count(team)-- # Filter out products user already has and take top `count` items- top_products = [- item["product_path"]- for item in colleague_product_counts- if item["product_path"] not in user_existing_products- ][:count]-- # Create UserProductList entries for the top products- created_items = []- for product_path in top_products:- item, created = UserProductList.objects.get_or_create(- user=user,- team=team,- product_path=product_path,- defaults={- "enabled": True,- "reason": UserProductList.Reason.USED_BY_COLLEAGUES,- },- )-- if created:- created_items.append(item)-- return created_items-- @staticmethod- def backfill_from_other_teams(user: "User", team: "Team") -> "list[UserProductList]":- """- Backfill UserProductList entries for a user in a new team based on what- they have enabled in other teams they belong to.- """- from posthog.models.team import Team-- # We IGNORE the user's suggestion config because we want them to have- # at least some products in their sidebar to start with when backfilling from- # their own teams.- #- # if user.allow_sidebar_suggestions is False:- # return []-- # Get all other teams the user belongs to (through organization membership)- user_organizations = user.organization_memberships.values_list("organization_id", flat=True)- other_teams = Team.objects.filter(organization_id__in=user_organizations).exclude(id=team.id)-- # Get all product paths the user has enabled in other teams. Skip rows seeded by- # onboarding-delegation - those represent a one-off "explore everything" state for- # the delegator and shouldn't propagate when they later join another team.- user_product_paths = set(- UserProductList.objects.filter(user=user, team__in=other_teams, enabled=True)- .exclude(reason=UserProductList.Reason.ONBOARDING_DELEGATED)- .values_list("product_path", flat=True)- )-- # Create UserProductList entries for the missing products- created_items = []- for product_path in user_product_paths:- item, created = UserProductList.objects.get_or_create(- user=user,- team=team,- product_path=product_path,- defaults={- "enabled": True,- "reason": UserProductList.Reason.USED_ON_SEPARATE_TEAM,- },- )-- if created:- created_items.append(item)-- return created_items-- @staticmethod- def sync_cross_sell_products(- user: "User",- team: "Team",- max_products: int = 1,- ignored_categories: list[ProductItemCategory] | None = None,- ) -> "list[UserProductList]":- """- Sync cross-sell products for a user based on products they already have enabled.- Delegates candidate selection to CrossSellCandidateSelector, see that for more- information on how the selection process works.- """- if user.allow_sidebar_suggestions is False:- return []-- ignored_categories_set = (- set(ignored_categories) if ignored_categories is not None else DEFAULT_IGNORED_CATEGORIES- )-- user_rows = UserProductList.objects.filter(user=user, team=team).values_list("product_path", "enabled")- user_enabled_products = {path for path, enabled in user_rows if enabled}- user_excluded_products = {path for path, _ in user_rows}-- selector = CrossSellCandidateSelector(- user_enabled_products=user_enabled_products,- ignored_categories=ignored_categories_set,- user_excluded_products=user_excluded_products,- )- selected = selector.pick(k=max_products)- if not selected:- return []-- created_items = []- for product_path in selected:- item, created = UserProductList.objects.get_or_create(- user=user,- team=team,- product_path=product_path,- defaults={- "enabled": True,- "reason": UserProductList.Reason.USED_SIMILAR_PRODUCTS,- },- )-- if created:- created_items.append(item)-- return created_items-@receiver(post_save, sender="ee.AccessControl")def access_control_created(sender, instance, created, **kwargs):diff --git a/posthog/models/onboarding_delegation.py b/posthog/models/onboarding_delegation.pyindex 46713b8a9b59..32e6f4b3715b 100644--- a/posthog/models/onboarding_delegation.py+++ b/posthog/models/onboarding_delegation.py@@ -135,11 +135,7 @@ def _seed_sidebar_for_delegator(*, user_id: int, organization_id: UUID | str) ->team = Team.objects.filter(organization_id=organization_id).order_by("id").first()if team is None:return- UserProductList.enable_all_for_user(- user=user,- team=team,- reason=UserProductList.Reason.ONBOARDING_DELEGATED,- )+ UserProductList.enable_all_for_user(user=user, team=team)except Exception as exc: # noqa: BLE001 - sidebar seeding must never block delegationcapture_exception(exc)# Pair the Sentry capture with an indexable structured log so ops can correlatediff --git a/posthog/models/test/test_product_intent.py b/posthog/models/test/test_product_intent.pyindex baea50fcc80e..1280088ea93b 100644--- a/posthog/models/test/test_product_intent.py+++ b/posthog/models/test/test_product_intent.py@@ -621,7 +621,6 @@ class TestProductIntent(BaseTest):upl = user_product_lists.get()assert upl.product_path == "Session replay"assert upl.enabled is True- assert upl.reason == UserProductList.Reason.PRODUCT_INTENTdef test_register_creates_user_product_list_entries_for_multiple_product_intent(self):ProductIntent.register(@@ -637,9 +636,6 @@ class TestProductIntent(BaseTest):enabled = [upl.enabled for upl in user_product_lists]assert all(enabled)- reasons = [upl.reason for upl in user_product_lists]- assert all(reason == UserProductList.Reason.PRODUCT_INTENT for reason in reasons)-def test_register_ignores_product_key_without_products(self):ProductIntent.register(self.team, ProductKey.ANNOTATIONS, ProductIntentContext.DATA_WAREHOUSE_SOURCES_TABLE, self.user@@ -720,54 +716,6 @@ class TestProductIntent(BaseTest):)assert UserProductList.objects.filter(user=self.user, team=self.team).count() == 0- def test_register_with_onboarding_context_creates_user_product_list_with_onboarding_reason(self):- self.user.allow_sidebar_suggestions = True- self.user.save()-- ProductIntent.register(- team=self.team,- product_type=ProductKey.SESSION_REPLAY,- context=ProductIntentContext.ONBOARDING_PRODUCT_SELECTED___PRIMARY,- user=self.user,- is_onboarding=True,- )-- user_product_lists = UserProductList.objects.filter(user=self.user, team=self.team)- assert user_product_lists.count() == 1- assert user_product_lists.get().reason == UserProductList.Reason.ONBOARDING-- def test_register_with_quick_start_context_creates_user_product_list_with_onboarding_reason(self):- self.user.allow_sidebar_suggestions = True- self.user.save()-- ProductIntent.register(- team=self.team,- product_type=ProductKey.SESSION_REPLAY,- context=ProductIntentContext.QUICK_START_PRODUCT_SELECTED,- user=self.user,- is_onboarding=True,- )-- user_product_lists = UserProductList.objects.filter(user=self.user, team=self.team)- assert user_product_lists.count() == 1- assert user_product_lists.get().reason == UserProductList.Reason.ONBOARDING-- def test_register_without_onboarding_context_creates_user_product_list_with_product_intent_reason(self):- self.user.allow_sidebar_suggestions = True- self.user.save()-- ProductIntent.register(- team=self.team,- product_type=ProductKey.SESSION_REPLAY,- context=ProductIntentContext.SESSION_REPLAY_SET_FILTERS,- user=self.user,- is_onboarding=False,- )-- user_product_lists = UserProductList.objects.filter(user=self.user, team=self.team)- assert user_product_lists.count() == 1- assert user_product_lists.get().reason == UserProductList.Reason.PRODUCT_INTENT-def _make_ai_generation_event_definition(self) -> EventDefinition:return EventDefinition.objects.create(team=self.team, name="$ai_generation")diff --git a/posthog/models/test/test_user_product_list_invites.py b/posthog/models/test/test_user_product_list_invites.pyindex 067165d6f449..6a55688bc141 100644--- a/posthog/models/test/test_user_product_list_invites.py+++ b/posthog/models/test/test_user_product_list_invites.py@@ -13,9 +13,7 @@ from products.access_control.backend.models.access_control import AccessControlclass TestUserProductListDefaults(BaseTest):def _default_paths_for(self, user: User, team: Team) -> set[str]:return set(- UserProductList.objects.filter(- user=user, team=team, enabled=True, reason=UserProductList.Reason.DEFAULT- ).values_list("product_path", flat=True)+ UserProductList.objects.filter(user=user, team=team, enabled=True).values_list("product_path", flat=True))def _make_team_private(self, team: Team) -> None:diff --git a/posthog/schema.py b/posthog/schema.pyindex 97da8d8b38e1..ccf7a7aa415b 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -281,7 +281,6 @@ from posthog.schema_enums import (UrlMatching as UrlMatching,UsageMetricDisplay as UsageMetricDisplay,UsageMetricFormat as UsageMetricFormat,- UserProductListReason as UserProductListReason,ValueDisplay as ValueDisplay,WebAgentAnalyticsQueryType as WebAgentAnalyticsQueryType,WebAgentContentGrouping as WebAgentContentGrouping,@@ -2997,6 +2996,17 @@ class UserBasicType(BaseModel):uuid: str+class UserProductListItem(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ created_at: str+ enabled: bool+ id: str+ product_path: str+ updated_at: str++class VectorSearchResponseItem(BaseModel):model_config = ConfigDict(extra="forbid",@@ -5254,14 +5264,6 @@ class FileSystemImport(BaseModel):meta: dict[str, Any] | None = Field(default=None, description="Metadata")path: str = Field(..., description="Object's name and folder")protocol: str | None = Field(default=None, description='Protocol of the item, defaults to "project://"')- reason: UserProductListReason | None = Field(- default=None,- description="Reason for custom product suggestion (from UserProductList)",- )- reasonText: str | None = Field(- default=None,- description=("Custom reason text for custom product suggestion (from UserProductList)"),- )ref: str | None = Field(default=None, description="Object's ID or other unique reference")sceneKey: str | None = Field(default=None,@@ -8355,19 +8357,6 @@ class UsageMetricsQueryResponse(BaseModel):)-class UserProductListItem(BaseModel):- model_config = ConfigDict(- extra="forbid",- )- created_at: str- enabled: bool- id: str- product_path: str- reason: UserProductListReason- reason_text: str | None = None- updated_at: str--class WebAgentAnalyticsQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 448950155fd1..0d1a1879cf6e 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -4175,18 +4175,6 @@ class UsageMetricFormat(StrEnum):CURRENCY = "currency"-class UserProductListReason(StrEnum):- DEFAULT = "default"- ONBOARDING = "onboarding"- PRODUCT_INTENT = "product_intent"- USED_BY_COLLEAGUES = "used_by_colleagues"- USED_SIMILAR_PRODUCTS = "used_similar_products"- USED_ON_SEPARATE_TEAM = "used_on_separate_team"- NEW_PRODUCT = "new_product"- SALES_LED = "sales_led"- ONBOARDING_DELEGATED = "onboarding_delegated"--class WebAgentAnalyticsQueryType(StrEnum):OVERVIEW = "overview"ISSUES = "issues"diff --git a/posthog/temporal/tests/weekly_digest/test_activities.py b/posthog/temporal/tests/weekly_digest/test_activities.pyindex 174d4061ef1d..70644d89e0f1 100644--- a/posthog/temporal/tests/weekly_digest/test_activities.py+++ b/posthog/temporal/tests/weekly_digest/test_activities.py@@ -1,3 +1,4 @@+import jsonfrom datetime import UTC, datetime, timedeltafrom uuid import UUID, uuid4@@ -28,6 +29,7 @@ from posthog.temporal.weekly_digest.activities import (send_weekly_digest_batch,)from posthog.temporal.weekly_digest.types import (+ DEFAULT_PRODUCT_SUGGESTION_TEXT,CommonInput,Digest,GenerateDigestDataBatchInput,@@ -36,6 +38,8 @@ from posthog.temporal.weekly_digest.types import (UsageTrends,)+from products.growth.backend.product_push.selection import project_uses_product+class MockRedis:"""Mock Redis client for testing."""@@ -732,71 +736,114 @@ async def test_send_weekly_digest_batch_dry_run(mock_redis, common_input, digest@pytest.mark.asyncioasync def test_generate_product_suggestion_lookup(mock_redis, common_input, digest):- """Test generating product suggestion lookup stores only one suggestion per user."""+ """Test that an org's active product push campaign becomes one suggestion per opted-in user."""batch = (0, 1)input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)+ organization_id = UUID("12345678-1234-1234-1234-123456789abc")mock_team = MagicMock()mock_team.id = 1+ mock_team.project_id = 1+ mock_team.organization_id = organization_id- mock_user_1 = MagicMock()- mock_user_1.id = 100+ mock_user = MagicMock()+ mock_user.id = 100+ mock_user.allow_sidebar_suggestions = True- mock_user_2 = MagicMock()- mock_user_2.id = 101+ # Opted out of suggestions, so the campaign must not reach them.+ mock_opted_out_user = MagicMock()+ mock_opted_out_user.id = 101+ mock_opted_out_user.allow_sidebar_suggestions = False- # Mock product suggestions - user 1 has multiple, but only first should be stored- mock_suggestions_user_1: list[dict] = [- {"product_path": "Error tracking", "reason": "sales_led", "reason_text": None},- {"product_path": "Session replay", "reason": "new_product", "reason_text": "Custom text"},- ]- mock_suggestions_user_2: list[dict] = [] # No suggestions for user 2+ campaigns = [{"product_key": "session_replay", "reason_text": "Give replay a go"}]mock_team_queryset = MockAsyncQuerySet([mock_team])- # Create an async generator function for usersasync def async_user_generator():- for user in [mock_user_1, mock_user_2]:+ for user in [mock_user, mock_opted_out_user]:yield user- async def async_wrapper():+ async def users_wrapper():return async_user_generator()- # Mock queryset that returns different results based on user_id- def mock_query_user_product_suggestions(user_id, team_id, period_start, period_end):- mock_qs = MagicMock()- mock_qs.user_id = user_id- return mock_qs+ async def project_uses_product_wrapper(*args, **kwargs):+ return False++ def fake_database_sync_to_async(fn):+ # The activity wraps two different sync callables; dispatch on which one.+ if fn is project_uses_product:+ return project_uses_product_wrapper+ return users_wrapperasync def mock_queryset_to_list(qs):- if hasattr(qs, "user_id"):- if qs.user_id == 100:- return mock_suggestions_user_1- return mock_suggestions_user_2- return []+ return campaignswith patch("posthog.temporal.weekly_digest.activities.query_teams_for_digest", return_value=mock_team_queryset):- with patch(- "posthog.temporal.weekly_digest.activities.query_user_product_suggestions",- side_effect=mock_query_user_product_suggestions,- ):+ with patch("posthog.temporal.weekly_digest.activities.query_org_product_push_campaigns"):with patch("posthog.temporal.weekly_digest.activities.queryset_to_list", side_effect=mock_queryset_to_list):- with patch("posthog.temporal.weekly_digest.activities.database_sync_to_async") as mock_sync:- mock_sync.return_value = async_wrapper+ with patch(+ "posthog.temporal.weekly_digest.activities.database_sync_to_async",+ side_effect=fake_database_sync_to_async,+ ):with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):await generate_product_suggestion_lookup(input_data)- # Verify only one suggestion stored per user (user 100), none for user 101- assert f"{digest.key}-product-suggestion-100" in mock_redis.dataassert f"{digest.key}-product-suggestion-101" not in mock_redis.data- # Verify only the first suggestion was stored with team_id- import json-stored_data = json.loads(mock_redis.data[f"{digest.key}-product-suggestion-100"])assert stored_data["team_id"] == mock_team.id- assert stored_data["product_path"] == "Error tracking"- assert stored_data["reason"] == "sales_led"+ assert stored_data["product_path"] == "Session replay"+ assert stored_data["reason_text"] == "Give replay a go"+++async def test_generate_product_suggestion_lookup_skips_projects_already_using_the_product(+ mock_redis, common_input, digest+):+ """Test that a project already using the pushed product isn't nudged about it."""+ batch = (0, 1)+ input_data = GenerateDigestDataBatchInput(batch=batch, digest=digest, common=common_input)++ mock_team = MagicMock()+ mock_team.id = 1+ mock_team.project_id = 1+ mock_team.organization_id = UUID("12345678-1234-1234-1234-123456789abc")++ mock_user = MagicMock()+ mock_user.id = 100+ mock_user.allow_sidebar_suggestions = True++ async def async_user_generator():+ yield mock_user++ async def users_wrapper():+ return async_user_generator()++ async def project_uses_product_wrapper(*args, **kwargs):+ return True++ def fake_database_sync_to_async(fn):+ if fn is project_uses_product:+ return project_uses_product_wrapper+ return users_wrapper++ async def mock_queryset_to_list(qs):+ return [{"product_key": "session_replay", "reason_text": None}]++ with patch(+ "posthog.temporal.weekly_digest.activities.query_teams_for_digest",+ return_value=MockAsyncQuerySet([mock_team]),+ ):+ with patch("posthog.temporal.weekly_digest.activities.query_org_product_push_campaigns"):+ with patch("posthog.temporal.weekly_digest.activities.queryset_to_list", side_effect=mock_queryset_to_list):+ with patch(+ "posthog.temporal.weekly_digest.activities.database_sync_to_async",+ side_effect=fake_database_sync_to_async,+ ):+ with patch("posthog.temporal.weekly_digest.activities.redis.from_url", return_value=mock_redis):+ await generate_product_suggestion_lookup(input_data)++ assert mock_redis.data == {}@pytest.mark.asyncio@@ -850,7 +897,7 @@ async def test_send_weekly_digest_batch_with_product_suggestion(mock_redis, commawait mock_redis.sadd(f"{digest.key}-user-notify-100", "1")# Add single product suggestion for user 100 (team_id matches the team in the digest)- suggestion_json = '{"team_id": 1, "product_path": "Error tracking", "reason": "sales_led", "reason_text": null}'+ suggestion_json = '{"team_id": 1, "product_path": "Error tracking", "reason_text": null}'await mock_redis.setex(f"{digest.key}-product-suggestion-100", 3600, suggestion_json)mock_org_queryset = MockAsyncQuerySet([mock_org])@@ -892,7 +939,7 @@ async def test_send_weekly_digest_batch_with_product_suggestion(mock_redis, commassert "new_product_suggestion" in team_reportsuggestion = team_report["new_product_suggestion"]assert suggestion["product_path"] == "Error tracking"- assert suggestion["reason_text"] == "This product is recommended for you by our team."+ assert suggestion["reason_text"] == DEFAULT_PRODUCT_SUGGESTION_TEXT@pytest.mark.parametrize(diff --git a/posthog/temporal/tests/weekly_digest/test_types.py b/posthog/temporal/tests/weekly_digest/test_types.pyindex 5eaa8ddc854e..0582859e86b5 100644--- a/posthog/temporal/tests/weekly_digest/test_types.py+++ b/posthog/temporal/tests/weekly_digest/test_types.py@@ -3,6 +3,7 @@ from uuid import uuid4from posthog.temporal.weekly_digest.activities import DIGEST_ITEM_COUNT_THRESHOLDfrom posthog.temporal.weekly_digest.types import (+ DEFAULT_PRODUCT_SUGGESTION_TEXT,DashboardList,Digest,DigestDashboard,@@ -461,69 +462,26 @@ def test_digest_external_data_source():assert source.id == source_id-def test_digest_product_suggestion_get_readable_reason_text_with_custom_text():- """Test that custom reason_text takes precedence."""+def test_digest_product_suggestion_uses_campaign_copy_when_present():+ """Test that the campaign's own promo copy takes precedence."""suggestion = DigestProductSuggestion(team_id=1,product_path="Error tracking",- reason="used_by_colleagues",reason_text="Custom message for this user",)assert suggestion.get_readable_reason_text() == "Custom message for this user"-def test_digest_product_suggestion_get_readable_reason_text_fallback_to_default():- """Test that reason enum maps to default text when reason_text is None."""+def test_digest_product_suggestion_falls_back_to_default_copy():+ """Test that a campaign without promo copy gets the default blurb."""suggestion = DigestProductSuggestion(team_id=1,product_path="Session replay",- reason="sales_led",reason_text=None,)- assert suggestion.get_readable_reason_text() == "This product is recommended for you by our team."---def test_digest_product_suggestion_get_readable_reason_text_supported_reasons():- """Test that sales_led and new_product reasons map to readable text."""- reason_mappings = {- "new_product": "This is a brand new product. Give it a try!",- "sales_led": "This product is recommended for you by our team.",- }-- for reason, expected_text in reason_mappings.items():- suggestion = DigestProductSuggestion(- team_id=1,- product_path="Test Product",- reason=reason,- reason_text=None,- )- assert suggestion.get_readable_reason_text() == expected_text, f"Failed for reason: {reason}"---def test_digest_product_suggestion_get_readable_reason_text_unsupported_reason():- """Test that unsupported reasons return None (fallback)."""- suggestion = DigestProductSuggestion(- team_id=1,- product_path="Test Product",- reason="used_by_colleagues", # Not in digest defaults- reason_text=None,- )-- assert suggestion.get_readable_reason_text() is None---def test_digest_product_suggestion_get_readable_reason_text_no_reason():- """Test that None is returned when neither reason nor reason_text is set."""- suggestion = DigestProductSuggestion(- team_id=1,- product_path="Feature flags",- reason=None,- reason_text=None,- )-- assert suggestion.get_readable_reason_text() is None+ assert suggestion.get_readable_reason_text() == DEFAULT_PRODUCT_SUGGESTION_TEXTdef test_user_specific_digest_render_payload_with_product_suggestion():@@ -552,7 +510,6 @@ def test_user_specific_digest_render_payload_with_product_suggestion():suggestion = DigestProductSuggestion(team_id=1,product_path="Error tracking",- reason="sales_led",reason_text=None,)@@ -568,7 +525,7 @@ def test_user_specific_digest_render_payload_with_product_suggestion():assert "new_product_suggestion" in team_reportnew_suggestion = team_report["new_product_suggestion"]assert new_suggestion["product_path"] == "Error tracking"- assert new_suggestion["reason_text"] == "This product is recommended for you by our team."+ assert new_suggestion["reason_text"] == DEFAULT_PRODUCT_SUGGESTION_TEXTdef test_user_specific_digest_render_payload_with_custom_reason_text():@@ -597,7 +554,6 @@ def test_user_specific_digest_render_payload_with_custom_reason_text():suggestion = DigestProductSuggestion(team_id=1,product_path="Session replay",- reason="product_intent",reason_text="Custom reason text for this user",)@@ -642,7 +598,6 @@ def test_user_specific_digest_render_payload_suggestion_wrong_team():suggestion = DigestProductSuggestion(team_id=999,product_path="Error tracking",- reason="sales_led",reason_text=None,)diff --git a/posthog/temporal/weekly_digest/activities.py b/posthog/temporal/weekly_digest/activities.pyindex 568a730ad176..25a692b9a3f9 100644--- a/posthog/temporal/weekly_digest/activities.py+++ b/posthog/temporal/weekly_digest/activities.py@@ -40,12 +40,12 @@ from posthog.temporal.weekly_digest.queries import (query_new_external_data_sources,query_new_feature_flags,query_org_members,+ query_org_product_push_campaigns,query_org_teams,query_orgs_for_digest,query_saved_filters,query_surveys_launched,query_teams_for_digest,- query_user_product_suggestions,queryset_to_list,)from posthog.temporal.weekly_digest.types import (@@ -73,6 +73,8 @@ from posthog.temporal.weekly_digest.types import (UserDigestContext,)+from products.growth.backend.product_push.selection import project_uses_product, resolve_product_path+def _redis_url(common: CommonInput) -> str:return f"redis://{common.redis_host}:{common.redis_port}?decode_responses=true"@@ -537,30 +539,52 @@ async def generate_product_suggestion_lookup(input: GenerateDigestDataBatchInputuser_count = 0suggestion_count = 0users_with_suggestion: set[int] = set()+ # Campaigns are org-scoped but this batch walks teams, so cache per org.+ campaigns_by_org: dict[str, list[dict]] = {}async with redis.from_url(_redis_url(input.common)) as r:batch_start, batch_end = input.batchasync for team in query_teams_for_digest()[batch_start:batch_end]:try:+ organization_id = str(team.organization_id)+ if organization_id not in campaigns_by_org:+ campaigns_by_org[organization_id] = await queryset_to_list(+ query_org_product_push_campaigns(organization_id, input.digest.period_end)+ )+ campaigns = campaigns_by_org[organization_id]+ if not campaigns:+ team_count += 1+ continue++ campaign = campaigns[0]+ product_path = resolve_product_path(campaign["product_key"])+ # The push is org-wide, but a project that already uses the product+ # shouldn't be nudged about it - same rule the nav card applies.+ if product_path is None or await database_sync_to_async(project_uses_product)(+ team.project_id, campaign["product_key"]+ ):+ team_count += 1+ continue+async for user in await database_sync_to_async(team.all_users_with_access)():# Only store one suggestion per user (first one found)if user.id in users_with_suggestion:continue- suggestions = await queryset_to_list(- query_user_product_suggestions(- user.id, team.id, input.digest.period_start, input.digest.period_end- )- )+ user_count += 1- if suggestions:- suggestion = DigestProductSuggestion(team_id=team.id, **suggestions[0])- key = user_data_key(input.digest.key, UserDataKey.PRODUCT_SUGGESTION, user.id)- await r.setex(key, input.common.redis_ttl, suggestion.model_dump_json())- users_with_suggestion.add(user.id)- suggestion_count += 1+ if user.allow_sidebar_suggestions is False:+ continue- user_count += 1+ suggestion = DigestProductSuggestion(+ team_id=team.id,+ product_path=product_path,+ reason_text=campaign["reason_text"],+ )+ key = user_data_key(input.digest.key, UserDataKey.PRODUCT_SUGGESTION, user.id)+ await r.setex(key, input.common.redis_ttl, suggestion.model_dump_json())+ users_with_suggestion.add(user.id)+ suggestion_count += 1team_count += 1except Exception as e:logger.warning(diff --git a/posthog/temporal/weekly_digest/queries.py b/posthog/temporal/weekly_digest/queries.pyindex 43d26e78b52f..84bd27e3015f 100644--- a/posthog/temporal/weekly_digest/queries.py+++ b/posthog/temporal/weekly_digest/queries.py@@ -4,7 +4,6 @@ from django.db.models import Count, Q, QuerySetfrom posthog.helpers.session_recording_playlist_templates import DEFAULT_PLAYLIST_NAMESfrom posthog.models import Organization-from posthog.models.file_system.user_product_list import UserProductListfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist@@ -15,6 +14,7 @@ from products.error_tracking.backend.facade.api import query_new_error_issues asfrom products.event_definitions.backend.models.event_definition import EventDefinitionfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.growth.backend.models import ProductPushCampaignfrom products.surveys.backend.models import Surveyfrom products.warehouse_sources.backend.facade.models import ExternalDataSource@@ -26,6 +26,8 @@ def query_teams_for_digest() -> QuerySet:.only("id","name",+ "project_id",+ "organization_id","organization__id","organization__name","organization__created_at",@@ -138,17 +140,21 @@ def query_saved_filters(period_start: datetime, period_end: datetime) -> QuerySe)-def query_user_product_suggestions(- user_id: int, team_id: int, period_start: datetime, period_end: datetime-) -> QuerySet:- return UserProductList.objects.filter(- user_id=user_id,- team_id=team_id,- enabled=True,- reason__in=[UserProductList.Reason.SALES_LED, UserProductList.Reason.NEW_PRODUCT],- created_at__gt=period_start,- created_at__lte=period_end,- ).values("product_path", "reason", "reason_text")+def query_org_product_push_campaigns(organization_id: str, period_end: datetime) -> QuerySet:+ """Product push campaigns still running at the end of the digest period.++ Only ACTIVE campaigns qualify. A campaign that closed mid-period did so because the org+ either adopted the product or moved on from it, and neither is worth an email nudge.+ """+ return (+ ProductPushCampaign.objects.filter(+ organization_id=organization_id,+ status=ProductPushCampaign.Status.ACTIVE,+ started_at__lte=period_end,+ )+ .order_by("-started_at")+ .values("product_key", "reason_text")+ )@database_sync_to_asyncdiff --git a/posthog/temporal/weekly_digest/types.py b/posthog/temporal/weekly_digest/types.pyindex 2f0147d2f2a4..0bfe21d5d293 100644--- a/posthog/temporal/weekly_digest/types.py+++ b/posthog/temporal/weekly_digest/types.py@@ -183,25 +183,19 @@ class ErrorIssueList(RootModel):root: list[DigestErrorIssue]-PRODUCT_SUGGESTION_REASON_DEFAULTS: dict[str, str] = {- "new_product": "This is a brand new product. Give it a try!",- "sales_led": "This product is recommended for you by our team.",-}+# Shown when the campaign carries no hand-written promo copy. Mirrors the nav card's+# DEFAULT_PRODUCT_PUSH_DISPLAY tagline so both surfaces say the same thing.+DEFAULT_PRODUCT_SUGGESTION_TEXT = "We think your organization would get a lot out of this product. Give it a try!"class DigestProductSuggestion(BaseModel):team_id: intproduct_path: str # This is the product name (e.g., "Product analytics")- reason: str | Nonereason_text: str | None- def get_readable_reason_text(self) -> str | None:- """Returns human-readable reason text for email interpolation."""- if self.reason_text:- return self.reason_text- if self.reason:- return PRODUCT_SUGGESTION_REASON_DEFAULTS.get(self.reason)- return None+ def get_readable_reason_text(self) -> str:+ """Returns human-readable suggestion copy for email interpolation."""+ return self.reason_text or DEFAULT_PRODUCT_SUGGESTION_TEXT# mypy and ruff do not agree about TypeAliasdiff --git a/products/growth/backend/api/product_push.py b/products/growth/backend/api/product_push.pyindex 4ec8fd612424..f0c4869c4550 100644--- a/products/growth/backend/api/product_push.py+++ b/products/growth/backend/api/product_push.py@@ -10,12 +10,10 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from posthog.products import Products-from posthog.schema_enums import ProductKeyfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.growth.backend.models import ProductPushCampaign-from products.growth.backend.product_push.selection import PUSH_PRODUCT_PATHS, project_uses_product+from products.growth.backend.product_push.selection import project_uses_product, resolve_product_pathclass ProductPushCampaignSerializer(serializers.ModelSerializer):@@ -48,18 +46,7 @@ class ProductPushCampaignSerializer(serializers.ModelSerializer):@extend_schema_field(serializers.CharField(allow_null=True))def get_product_path(self, campaign: ProductPushCampaign) -> str | None:- try:- product_key = ProductKey(campaign.product_key)- except ValueError:- return None- # Curated mapping first — intent→product inference is ambiguous for- # several keys (see PUSH_PRODUCT_PATHS). The inference fallback covers- # TAM-scheduled keys outside the push lists.- curated_path = PUSH_PRODUCT_PATHS.get(product_key)- if curated_path is not None:- return curated_path- products = Products.get_products_by_intent(product_key)- return products[0].path if products else None+ return resolve_product_path(campaign.product_key)class ProductPushCampaignViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):diff --git a/products/growth/backend/cross_sell_candidate_selector.py b/products/growth/backend/cross_sell_candidate_selector.pydeleted file mode 100644index 4ef7aa963175..000000000000--- a/products/growth/backend/cross_sell_candidate_selector.py+++ /dev/null@@ -1,221 +0,0 @@-from collections import defaultdict-from dataclasses import dataclass, field--from posthog.products import Products-from posthog.schema_enums import ProductItemCategory, ProductKey--# Base weights for high-value products.-# Analysis: https://us.posthog.com/project/2/notebooks/x3AWOfsm-BASE_PREFERENCE_WEIGHTS: dict[ProductKey, int] = {- ProductKey.PRODUCT_ANALYTICS: 10,- ProductKey.WEB_ANALYTICS: 6,- ProductKey.SESSION_REPLAY: 6,- ProductKey.FEATURE_FLAGS: 6,- ProductKey.ERROR_TRACKING: 4,-}--LLM_ADJACENT_KEYS: list[ProductKey] = [- ProductKey.LLM_ANALYTICS,- ProductKey.LLM_EVALUATIONS,- ProductKey.LLM_DATASETS,- ProductKey.LLM_PROMPTS,- ProductKey.LLM_CLUSTERS,-]--DEFAULT_IGNORED_CATEGORIES: set[ProductItemCategory] = {- ProductItemCategory.TOOLS,- ProductItemCategory.UNRELEASED,-}--SAME_CATEGORY_WEIGHT_BUMP = 2-LLM_ADJACENT_WEIGHT = 10---@dataclass-class CrossSellCandidateSelector:- """- Given product catalog metadata and user state, produces a weighted list- of candidate product paths for cross-sell suggestions.-- Pure computation — no DB access. The caller- (UserProductList.sync_cross_sell_products) handles querying enabled- products and persisting results. Randomness is isolated to `pick`,- which uses `np.random.choice` for weighted sampling without replacement.-- Algorithm overview- ------------------- The goal is to suggest products the user doesn't have yet, biased toward- products that are likely to be useful given what they already use.-- **Step 1 — Build preference weights** (build_preference_weights)-- Every product starts with a default weight of 1. Three layers of boosts- are applied on top, in order:-- a) Base preference weights: a handful of universally high-value products- get static weights (e.g. Product analytics=10, Session replay=6).- See BASE_PREFERENCE_WEIGHTS for the full list and the linked notebook- for the analysis behind these numbers.-- b) LLM adjacent boost: if the user already has AI observability enabled,- all LLM-adjacent products (Evaluations, Datasets, Prompts, Clusters)- are set to weight 10, because they're most useful together.-- c) Same-category bump: for every category the user already has a product- in, all *other* products in that category get +2. This makes the- selection favor expanding within a familiar area.-- **Step 2 — Build the candidate set** (build_candidates)-- Candidates are chosen in two tiers:-- Tier 1 (narrow): products from the same categories the user already- uses, plus all "favored" products (those that received a base preference- weight in step 1a). Both are filtered to exclude user_excluded_products- (which includes dismissed/disabled products, not just enabled ones) and- any ignored categories (Tools, Unreleased by default).-- Tier 2 (fallback): if tier 1 is empty — e.g. the user already has- every favored and same-category product — we expand to all products- outside ignored categories that the user doesn't have yet.-- **Step 3 — Combine** (_get_weighted_candidates)-- Returns the candidate set paired with their weights as- list[tuple[str, int]], ready to be passed to random.choices by the caller.- """-- # Products the user actively has enabled — drives category weighting and LLM boost.- user_enabled_products: set[str]- ignored_categories: set[ProductItemCategory]- # Products to exclude from the candidate pool. Superset of user_enabled_products:- # includes dismissed (enabled=False) rows so we don't re-suggest them.- # Defaults to user_enabled_products when not provided.- user_excluded_products: set[str] = field(default_factory=set)-- # Derived lookups, built from Products singleton in __post_init__- products_by_category: dict[ProductItemCategory, list[str]] = field(init=False, repr=False)- product_to_category: dict[str, ProductItemCategory] = field(init=False, repr=False)- intent_to_paths: dict[ProductKey, list[str]] = field(init=False, repr=False)- user_enabled_categories: set[ProductItemCategory] = field(init=False, repr=False)-- def __post_init__(self) -> None:- if not self.user_excluded_products:- self.user_excluded_products = self.user_enabled_products-- self.products_by_category = Products.get_products_by_category()-- self.product_to_category = {}- self.intent_to_paths = defaultdict(list)- for product in Products.products():- if product.category:- self.product_to_category[product.path] = product.category- for intent in product.intents:- self.intent_to_paths[intent].append(product.path)-- self.user_enabled_categories = {- category- for path in self.user_enabled_products- if (category := self.product_to_category.get(path)) is not None- } - self.ignored_categories-- def _resolve_paths(self, key: ProductKey) -> list[str]:- return self.intent_to_paths.get(key, [])-- def _build_preference_weights(self) -> defaultdict[str, int]:- """- Build a weight map (product_path → int) that controls how likely- each product is to be selected.-- Three layers, applied in order:- 1. Base weights for universally high-value products- 2. Contextual boost when the user already uses AI observability- 3. +2 bump for products in the same category as the user's enabled products- """- weights: defaultdict[str, int] = defaultdict(lambda: 1)-- for key, weight in BASE_PREFERENCE_WEIGHTS.items():- for path in self._resolve_paths(key):- weights[path] = weight-- self._apply_llm_adjacent_boost(weights)- self._apply_same_category_boost(weights)- return weights-- def _apply_llm_adjacent_boost(self, weights: defaultdict[str, int]) -> None:- llm_analytics_paths = self._resolve_paths(ProductKey.LLM_ANALYTICS)- if not any(p in self.user_enabled_products for p in llm_analytics_paths):- return-- for key in LLM_ADJACENT_KEYS:- for path in self._resolve_paths(key):- weights[path] = LLM_ADJACENT_WEIGHT-- def _apply_same_category_boost(self, weights: defaultdict[str, int]) -> None:- for category in self.user_enabled_categories:- for path in self.products_by_category.get(category, []):- if path not in self.user_enabled_products:- weights[path] += SAME_CATEGORY_WEIGHT_BUMP-- def _build_candidates(self, preference_weights: defaultdict[str, int]) -> set[str]:- """- Build the candidate set in two tiers:-- 1. Same-category products (where user already has something) + favored products- (those with explicit preference weights), both filtered by ignored categories.- 2. Fallback: all products outside ignored categories, if tier 1 is empty.- """- same_category = {- product.path- for product in Products.products()- if product.path not in self.user_excluded_products- and (category := self.product_to_category.get(product.path)) is not None- and category in self.user_enabled_categories- and category not in self.ignored_categories- }-- favored = {- path- for path in set(preference_weights.keys()) - self.user_excluded_products- if self.product_to_category.get(path) not in self.ignored_categories- }-- candidates = same_category | favored- if candidates:- return candidates-- return {- product.path- for product in Products.products()- if product.path not in self.user_excluded_products- and self.product_to_category.get(product.path) not in self.ignored_categories- }-- def _get_weighted_candidates(self) -> list[tuple[str, int]]:- """- Returns a list of (product_path, weight) pairs for all eligible candidates.- Useful for inspection/testing without introducing randomness.- """- weights = self._build_preference_weights()- candidates = self._build_candidates(weights)- return [(path, weights[path]) for path in candidates]-- def pick(self, k: int = 1) -> list[str]:- """- Main entry point. Selects up to k product paths via weighted random- sampling from the candidate set. Returns an empty list when there- are no eligible candidates.- """- # this module loads at django.setup() via the file-system product list — numpy at- # module scope would put it on every process's startup path- import numpy as np # noqa: PLC0415-- weighted = self._get_weighted_candidates()- if not weighted:- return []-- paths, weights = zip(*weighted)-- # From a list of weights to a normalized [0, 1] probability distribution- prob_distribution = np.array(weights) / sum(weights)- return list(np.random.choice(list(paths), min(k, len(paths)), replace=False, p=prob_distribution))diff --git a/products/growth/backend/product_push/selection.py b/products/growth/backend/product_push/selection.pyindex a456540b7e84..6187f66f0f0b 100644--- a/products/growth/backend/product_push/selection.py+++ b/products/growth/backend/product_push/selection.py@@ -23,14 +23,16 @@ from django.db.models import Qfrom posthog.models.organization import Organizationfrom posthog.models.product_intent.product_intent import ACTIVATION_CHECK_PRODUCT_KEYS, ProductIntentfrom posthog.models.project import Project+from posthog.products import Productsfrom posthog.schema_enums import ProductKeyfrom products.growth.backend.models import ProductPushCampaignfrom products.growth.backend.product_push.cadence import is_retry_eligible# The order in which we push products to organizations that don't use them yet.-# Seeded from the cross-sell BASE_PREFERENCE_WEIGHTS ranking (see-# cross_sell_candidate_selector.py); extend as growth adds products to the program.+# Seeded from the preference weights of the retired cross-sell suggester, whose+# ranking came from https://us.posthog.com/project/2/notebooks/x3AWOfsm+# Extend as growth adds products to the program.BLESSED_PRODUCT_ORDER: list[ProductKey] = [ProductKey.PRODUCT_ANALYTICS,ProductKey.WEB_ANALYTICS,@@ -80,6 +82,24 @@ PUSH_PRODUCT_PATHS: dict[ProductKey, str] = {}+def resolve_product_path(product_key: str) -> str | None:+ """Catalog path for a pushed product, or None when the key maps to no catalog item.++ Curated mapping first — intent→product inference is ambiguous for several keys+ (see PUSH_PRODUCT_PATHS). The inference fallback covers TAM-scheduled keys+ outside the push lists.+ """+ try:+ key = ProductKey(product_key)+ except ValueError:+ return None+ curated_path = PUSH_PRODUCT_PATHS.get(key)+ if curated_path is not None:+ return curated_path+ products = Products.get_products_by_intent(key)+ return products[0].path if products else None++@dataclass(frozen=True)class Selection:product_key: strdiff --git a/products/growth/backend/tests/test_cross_sell_candidate_selector.py b/products/growth/backend/tests/test_cross_sell_candidate_selector.pydeleted file mode 100644index a518ff7534aa..000000000000--- a/products/growth/backend/tests/test_cross_sell_candidate_selector.py+++ /dev/null@@ -1,334 +0,0 @@-from django.test import TestCase--from hypothesis import (- given,- settings,- strategies as st,-)--from posthog.schema import ProductItemCategory, ProductKey--from posthog.products import Products--from products.growth.backend.cross_sell_candidate_selector import (- BASE_PREFERENCE_WEIGHTS,- DEFAULT_IGNORED_CATEGORIES,- LLM_ADJACENT_KEYS,- LLM_ADJACENT_WEIGHT,- SAME_CATEGORY_WEIGHT_BUMP,- CrossSellCandidateSelector,-)--ALL_PRODUCT_PATHS = sorted(set(Products.get_product_paths()))-ALL_CATEGORIES = list(ProductItemCategory)-PRODUCTS_BY_CATEGORY = Products.get_products_by_category()--# Hypothesis strategies-product_paths_st = st.frozensets(st.sampled_from(ALL_PRODUCT_PATHS))-categories_st = st.frozensets(st.sampled_from(ALL_CATEGORIES))---def _make_selector(- enabled: set[str] | None = None,- ignored: set[ProductItemCategory] | None = None,- excluded: set[str] | None = None,-) -> CrossSellCandidateSelector:- return CrossSellCandidateSelector(- user_enabled_products=enabled or set(),- ignored_categories=ignored if ignored is not None else DEFAULT_IGNORED_CATEGORIES,- user_excluded_products=excluded or set(),- )---class TestCrossSellCandidateSelectorPreferenceWeights(TestCase):- def test_base_weights_are_applied(self):- selector = _make_selector()- weights = selector._build_preference_weights()-- for key, expected_weight in BASE_PREFERENCE_WEIGHTS.items():- paths = selector.intent_to_paths.get(key, [])- assert len(paths) > 0, f"ProductKey {key} should resolve to at least one product path"- for path in paths:- assert weights[path] == expected_weight, (- f"Expected weight {expected_weight} for {path}, got {weights[path]}"- )-- def test_non_favored_products_get_default_weight(self):- selector = _make_selector()- weights = selector._build_preference_weights()-- favored_paths = {p for k in BASE_PREFERENCE_WEIGHTS for p in selector.intent_to_paths.get(k, [])}- for product in Products.products():- if product.path not in favored_paths:- assert weights[product.path] == 1, f"Non-favored product {product.path} should have weight 1"-- def test_llm_adjacent_boost_when_llm_analytics_enabled(self):- selector_for_lookup = _make_selector()- llm_paths = selector_for_lookup.intent_to_paths.get(ProductKey.LLM_ANALYTICS, [])- assert len(llm_paths) > 0-- selector = _make_selector(enabled=set(llm_paths))- weights = selector._build_preference_weights()-- for key in LLM_ADJACENT_KEYS:- for path in selector.intent_to_paths.get(key, []):- # Weight is at least LLM_ADJACENT_WEIGHT, possibly higher if same-category boost stacks- assert weights[path] >= LLM_ADJACENT_WEIGHT, (- f"LLM adjacent product {path} should have weight >= {LLM_ADJACENT_WEIGHT}, got {weights[path]}"- )-- def test_no_llm_boost_when_llm_analytics_not_enabled(self):- selector = _make_selector()- weights = selector._build_preference_weights()-- for key in LLM_ADJACENT_KEYS:- for path in selector.intent_to_paths.get(key, []):- if key not in BASE_PREFERENCE_WEIGHTS:- assert weights[path] != LLM_ADJACENT_WEIGHT, (- f"LLM adjacent product {path} should NOT have boosted weight when AI observability is not enabled"- )-- def test_same_category_boost(self):- selector_for_lookup = _make_selector()- pa_paths = selector_for_lookup.intent_to_paths.get(ProductKey.PRODUCT_ANALYTICS, [])- assert len(pa_paths) > 0- pa_path = pa_paths[0]-- selector = _make_selector(enabled={pa_path})- weights = selector._build_preference_weights()-- # Build a reverse map: path -> base weight (if it's a favored product)- favored_path_to_weight: dict[str, int] = {}- for key, w in BASE_PREFERENCE_WEIGHTS.items():- for path in selector.intent_to_paths.get(key, []):- favored_path_to_weight[path] = w-- analytics_products = set(selector.products_by_category.get(ProductItemCategory.ANALYTICS, []))- for path in analytics_products - {pa_path}:- base = favored_path_to_weight.get(path, 1)- assert weights[path] == base + SAME_CATEGORY_WEIGHT_BUMP, (- f"Same-category product {path} should have weight {base + SAME_CATEGORY_WEIGHT_BUMP}, got {weights[path]}"- )---class TestCrossSellCandidateSelectorCandidates(TestCase):- def test_same_category_products_are_candidates(self):- selector_for_lookup = _make_selector()- pa_paths = selector_for_lookup.intent_to_paths.get(ProductKey.PRODUCT_ANALYTICS, [])- assert len(pa_paths) > 0- pa_path = pa_paths[0]-- selector = _make_selector(enabled={pa_path})- weights = selector._build_preference_weights()- candidates = selector._build_candidates(weights)-- analytics_products = set(selector.products_by_category.get(ProductItemCategory.ANALYTICS, []))- same_category_not_enabled = analytics_products - {pa_path}-- assert same_category_not_enabled <= candidates, (- f"Same-category products should be candidates: missing {same_category_not_enabled - candidates}"- )-- def test_favored_products_are_candidates(self):- selector = _make_selector()- weights = selector._build_preference_weights()- candidates = selector._build_candidates(weights)-- for key in BASE_PREFERENCE_WEIGHTS:- for path in selector.intent_to_paths.get(key, []):- if selector.product_to_category.get(path) not in DEFAULT_IGNORED_CATEGORIES:- assert path in candidates, f"Favored product {path} should be a candidate"-- def test_enabled_products_excluded_from_candidates(self):- selector_for_lookup = _make_selector()- pa_path = selector_for_lookup.intent_to_paths.get(ProductKey.PRODUCT_ANALYTICS, [])[0]- sr_path = selector_for_lookup.intent_to_paths.get(ProductKey.SESSION_REPLAY, [])[0]- assert pa_path and sr_path-- selector = _make_selector(enabled={pa_path, sr_path})- weights = selector._build_preference_weights()- candidates = selector._build_candidates(weights)-- assert pa_path not in candidates- assert sr_path not in candidates-- def test_dismissed_products_excluded_from_candidates(self):- selector_for_lookup = _make_selector()- pa_path = selector_for_lookup.intent_to_paths.get(ProductKey.PRODUCT_ANALYTICS, [])[0]- sr_path = selector_for_lookup.intent_to_paths.get(ProductKey.SESSION_REPLAY, [])[0]- ff_path = selector_for_lookup.intent_to_paths.get(ProductKey.FEATURE_FLAGS, [])[0]- assert pa_path and sr_path and ff_path-- # pa is enabled, sr is dismissed (excluded but not enabled), ff is not in the system- selector = _make_selector(enabled={pa_path}, excluded={pa_path, sr_path})- weights = selector._build_preference_weights()- candidates = selector._build_candidates(weights)-- assert pa_path not in candidates, "Enabled product should not be a candidate"- assert sr_path not in candidates, "Dismissed product should not be a candidate"- assert ff_path in candidates, "Product not in system should be a candidate"-- def test_dismissed_products_do_not_influence_category_weights(self):- selector_for_lookup = _make_selector()- sr_path = selector_for_lookup.intent_to_paths.get(ProductKey.SESSION_REPLAY, [])[0]- assert sr_path is not None-- # sr is dismissed — its category (Behavior) should NOT get the same-category boost- selector_with_dismissed = _make_selector(enabled=set(), excluded={sr_path})- weights_dismissed = selector_with_dismissed._build_preference_weights()-- selector_with_enabled = _make_selector(enabled={sr_path})- weights_enabled = selector_with_enabled._build_preference_weights()-- sr_category = selector_for_lookup.product_to_category.get(sr_path)- assert sr_category is not None- sibling_paths = set(selector_for_lookup.products_by_category.get(sr_category, [])) - {sr_path}-- for path in sibling_paths:- assert weights_dismissed[path] < weights_enabled[path], (- f"Dismissed product's category should not boost {path}"- )-- def test_ignored_categories_excluded_from_candidates(self):- selector_for_lookup = _make_selector()- pa_path = selector_for_lookup.intent_to_paths.get(ProductKey.PRODUCT_ANALYTICS, [])[0]- assert pa_path is not None-- selector = _make_selector(enabled={pa_path}, ignored={ProductItemCategory.ANALYTICS})- weights = selector._build_preference_weights()- candidates = selector._build_candidates(weights)-- analytics_products = set(selector.products_by_category.get(ProductItemCategory.ANALYTICS, []))- assert not candidates & analytics_products, (- "Analytics products should not be candidates when Analytics is ignored"- )-- def test_fallback_when_no_primary_candidates(self):- products_by_category = Products.get_products_by_category()- analytics_products = set(products_by_category.get(ProductItemCategory.ANALYTICS, []))-- lookup_selector = _make_selector()- favored_paths = {p for k in BASE_PREFERENCE_WEIGHTS for p in lookup_selector.intent_to_paths.get(k, [])}-- enabled = analytics_products | favored_paths- selector = _make_selector(enabled=enabled)- weights = selector._build_preference_weights()- candidates = selector._build_candidates(weights)-- tools_products = set(products_by_category.get(ProductItemCategory.TOOLS, []))- unreleased_products = set(products_by_category.get(ProductItemCategory.UNRELEASED, []))-- assert len(candidates) > 0, "Fallback should produce candidates"- assert not candidates & enabled, "Enabled products should not be in fallback candidates"- assert not candidates & tools_products, "Tools should not be in fallback candidates"- assert not candidates & unreleased_products, "Unreleased should not be in fallback candidates"-- def test_empty_candidates_when_all_products_enabled(self):- selector = _make_selector(enabled=set(Products.get_product_paths()))- assert selector._get_weighted_candidates() == []---class TestCrossSellCandidateSelectorGetWeightedCandidates(TestCase):- def test_returns_tuples_of_path_and_weight(self):- selector = _make_selector()- weighted = selector._get_weighted_candidates()-- assert len(weighted) > 0- for path, weight in weighted:- assert isinstance(path, str)- assert isinstance(weight, int)- assert weight >= 1-- def test_all_paths_are_valid_products(self):- all_paths = set(Products.get_product_paths())- selector = _make_selector()- weighted = selector._get_weighted_candidates()-- for path, _ in weighted:- assert path in all_paths, f"{path} is not a valid product path"-- def test_weights_reflect_preference_weights(self):- selector = _make_selector()- weighted = selector._get_weighted_candidates()- weight_map = dict(weighted)-- for key, expected_weight in BASE_PREFERENCE_WEIGHTS.items():- for path in selector.intent_to_paths.get(key, []):- if path in weight_map:- assert weight_map[path] == expected_weight, (- f"Expected {path} to have weight {expected_weight}, got {weight_map[path]}"- )---def _assert_selector_invariants(selector: CrossSellCandidateSelector) -> None:- weighted = selector._get_weighted_candidates()- candidate_paths = {path for path, _ in weighted}- all_paths = set(ALL_PRODUCT_PATHS)-- assert not candidate_paths & selector.user_excluded_products, (- f"Candidates include excluded products: {candidate_paths & selector.user_excluded_products}"- )- assert candidate_paths <= all_paths, f"Candidates include invalid paths: {candidate_paths - all_paths}"-- for cat in selector.ignored_categories:- ignored_paths = set(PRODUCTS_BY_CATEGORY.get(cat, []))- assert not candidate_paths & ignored_paths, (- f"Candidates from ignored category {cat}: {candidate_paths & ignored_paths}"- )-- for _, weight in weighted:- assert weight >= 1---class TestCrossSellCandidateSelectorPropertyTests:- @given(enabled=product_paths_st)- @settings(max_examples=200, deadline=None)- def test_invariants_across_random_states(self, enabled: frozenset[str]):- selector = CrossSellCandidateSelector(- user_enabled_products=set(enabled),- ignored_categories=DEFAULT_IGNORED_CATEGORIES,- )- _assert_selector_invariants(selector)-- @given(enabled=product_paths_st, ignored=categories_st)- @settings(max_examples=200, deadline=None)- def test_invariants_with_random_ignored_categories(- self, enabled: frozenset[str], ignored: frozenset[ProductItemCategory]- ):- selector = CrossSellCandidateSelector(- user_enabled_products=set(enabled),- ignored_categories=set(ignored),- )- _assert_selector_invariants(selector)-- @given(- enabled=product_paths_st,- dismissed=product_paths_st,- )- @settings(max_examples=200, deadline=None)- def test_invariants_with_dismissed_products(self, enabled: frozenset[str], dismissed: frozenset[str]):- selector = CrossSellCandidateSelector(- user_enabled_products=set(enabled),- ignored_categories=DEFAULT_IGNORED_CATEGORIES,- user_excluded_products=set(enabled | dismissed),- )- _assert_selector_invariants(selector)-- @given(- enabled=product_paths_st,- dismissed=product_paths_st,- ignored=categories_st,- )- @settings(max_examples=200, deadline=None)- def test_invariants_all_dimensions(- self,- enabled: frozenset[str],- dismissed: frozenset[str],- ignored: frozenset[ProductItemCategory],- ):- selector = CrossSellCandidateSelector(- user_enabled_products=set(enabled),- ignored_categories=set(ignored),- user_excluded_products=set(enabled | dismissed),- )- _assert_selector_invariants(selector)diff --git a/products/growth/dags/tests/test_user_product_list.py b/products/growth/dags/tests/test_user_product_list.pydeleted file mode 100644index 3ff71256a020..000000000000--- a/products/growth/dags/tests/test_user_product_list.py+++ /dev/null@@ -1,846 +0,0 @@-import pytest-from unittest.mock import MagicMock, patch--import dagster-from dagster import build_op_context--from posthog.models import Organization, Team, User-from posthog.models.file_system.user_product_list import UserProductList--from products.growth.dags.user_product_list import populate_user_product_list, populate_user_product_list_job--[email protected](autouse=True)-def _disable_default_product_seeding():- # These tests exercise the dagster op in isolation. Joining the org would otherwise- # seed the fixed default product set and skew the entry counts under test.- with patch("posthog.models.file_system.user_product_list.add_default_products_for_user"):- yield---def create_mock_s3_resource():- """Create a mock S3 resource for testing."""- mock_s3_resource = MagicMock()- mock_s3_client = MagicMock()- mock_s3_resource.get_client.return_value = mock_s3_client- return mock_s3_resource---def build_default_context(op_config: dict, resources: dict | None = None):- """Build a Dagster op context with default mock S3 resource.-- Args:- op_config: The op configuration dictionary- resources: Optional resources dictionary. If not provided or doesn't include 's3',- the default mock S3 resource will be added.-- Returns:- A Dagster OpExecutionContext with the provided config and resources.- """- if resources is None:- resources = {}-- if "s3" not in resources:- resources = {**resources, "s3": create_mock_s3_resource()}-- return build_op_context(op_config=op_config, resources=resources)---class TestPopulateUserProductListOp:- @pytest.mark.django_db- def test_basic_populate_creates_entries(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user = User.objects.create(email="[email protected]", first_name="Test", allow_sidebar_suggestions=True)- user.join(organization=org)-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics", "session_replay"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- }- )-- populate_user_product_list(context)-- entries = UserProductList.objects.filter(user=user, team=team)- assert entries.count() == 1- entry = entries.first()- assert entry is not None- assert entry.product_path == "product_analytics"- assert entry.enabled is True- assert entry.reason is None-- metadata = context.get_output_metadata("result")- assert metadata["created"].value == 1- assert metadata["skipped"].value == 0-- @pytest.mark.django_db- def test_populate_with_reason(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user = User.objects.create(email="[email protected]", first_name="Test", allow_sidebar_suggestions=True)- user.join(organization=org)-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "reason": "product_intent",- }- )-- populate_user_product_list(context)-- entry = UserProductList.objects.get(user=user, team=team, product_path="product_analytics")- assert entry.reason == "product_intent"-- @pytest.mark.django_db- def test_populate_with_reason_text(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user = User.objects.create(email="[email protected]", first_name="Test", allow_sidebar_suggestions=True)- user.join(organization=org)-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "reason": "product_intent",- "reason_text": "You've been using this product frequently",- }- )-- populate_user_product_list(context)-- entry = UserProductList.objects.get(user=user, team=team, product_path="product_analytics")- assert entry.reason == "product_intent"- assert entry.reason_text == "You've been using this product frequently"-- @pytest.mark.django_db- def test_populate_with_reason_text_only(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user = User.objects.create(email="[email protected]", first_name="Test", allow_sidebar_suggestions=True)- user.join(organization=org)-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "reason_text": "Custom message for user",- }- )-- populate_user_product_list(context)-- entry = UserProductList.objects.get(user=user, team=team, product_path="product_analytics")- assert entry.reason is None- assert entry.reason_text == "Custom message for user"-- @pytest.mark.django_db- def test_populate_respects_allow_sidebar_suggestions_false(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user_allowed = User.objects.create(- email="[email protected]",- first_name="Allowed",- allow_sidebar_suggestions=True,- )- user_disallowed = User.objects.create(- email="[email protected]",- first_name="Disallowed",- allow_sidebar_suggestions=False,- )- user_allowed.join(organization=org)- user_disallowed.join(organization=org)-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- }- )-- populate_user_product_list(context)-- allowed_entry = UserProductList.objects.filter(user=user_allowed, team=team)- disallowed_entry = UserProductList.objects.filter(user=user_disallowed, team=team)-- assert allowed_entry.count() == 1- assert disallowed_entry.count() == 0-- metadata = context.get_output_metadata("result")- assert metadata["created"].value == 1-- @pytest.mark.django_db- def test_populate_respects_allow_sidebar_suggestions_null_defaults_to_allowed(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user_null = User.objects.create(email="[email protected]", first_name="Null", allow_sidebar_suggestions=None)- user_null.join(organization=org)-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- }- )-- populate_user_product_list(context)-- entry = UserProductList.objects.filter(user=user_null, team=team)- assert entry.count() == 1-- @pytest.mark.django_db- def test_populate_multiple_products(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user = User.objects.create(email="[email protected]", first_name="Test", allow_sidebar_suggestions=True)- user.join(organization=org)-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics", "session_replay", "feature_flags"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics", "session_replay"],- }- )-- populate_user_product_list(context)-- entries = UserProductList.objects.filter(user=user, team=team)- assert entries.count() == 2- assert set(entries.values_list("product_path", flat=True)) == {- "product_analytics",- "session_replay",- }-- metadata = context.get_output_metadata("result")- assert metadata["created"].value == 2-- @pytest.mark.django_db- def test_populate_skips_existing_entries(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user = User.objects.create(email="[email protected]", first_name="Test", allow_sidebar_suggestions=True)- user.join(organization=org)-- UserProductList.objects.create(- user=user,- team=team,- product_path="product_analytics",- enabled=True,- reason="product_intent",- )-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "reason": "new_product",- }- )-- populate_user_product_list(context)-- entries = UserProductList.objects.filter(user=user, team=team, product_path="product_analytics")- assert entries.count() == 1- entry = entries.first()- assert entry is not None- assert entry.reason == "product_intent"-- metadata = context.get_output_metadata("result")- assert metadata["created"].value == 0- assert metadata["skipped"].value == 1-- @pytest.mark.django_db- def test_populate_multiple_teams(self):- org = Organization.objects.create(name="Test Org")- team1 = Team.objects.create(organization=org, name="Test Team 1")- team2 = Team.objects.create(organization=org, name="Test Team 2")- user = User.objects.create(email="[email protected]", first_name="Test", allow_sidebar_suggestions=True)- user.join(organization=org)-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- }- )-- populate_user_product_list(context)-- entries_team1 = UserProductList.objects.filter(user=user, team=team1)- entries_team2 = UserProductList.objects.filter(user=user, team=team2)-- assert entries_team1.count() == 1- assert entries_team2.count() == 1-- metadata = context.get_output_metadata("result")- assert metadata["created"].value == 2-- @pytest.mark.django_db- def test_populate_filters_by_require_existing_product(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user_with_product = User.objects.create(- email="[email protected]", first_name="With", allow_sidebar_suggestions=True- )- user_without_product = User.objects.create(- email="[email protected]",- first_name="Without",- allow_sidebar_suggestions=True,- )- user_with_product.join(organization=org)- user_without_product.join(organization=org)-- UserProductList.objects.create(- user=user_with_product,- team=team,- product_path="product_analytics",- enabled=True,- )-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics", "session_replay"},- ):- context = build_default_context(- op_config={- "product_paths": ["session_replay"],- "require_existing_product": "product_analytics",- }- )-- populate_user_product_list(context)-- with_entry = UserProductList.objects.filter(- user=user_with_product, team=team, product_path="session_replay"- )- without_entry = UserProductList.objects.filter(- user=user_without_product, team=team, product_path="session_replay"- )-- assert with_entry.count() == 1- assert without_entry.count() == 0-- @pytest.mark.django_db- def test_populate_fails_with_empty_product_paths(self):- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": [],- }- )-- with pytest.raises(dagster.Failure, match="product_paths cannot be empty"):- populate_user_product_list(context)-- @pytest.mark.django_db- def test_populate_fails_with_invalid_product_paths(self):- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["invalid_product"],- }- )-- with pytest.raises(dagster.Failure, match="Invalid product paths"):- populate_user_product_list(context)-- @pytest.mark.django_db- def test_populate_fails_with_invalid_require_existing_product(self):- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "require_existing_product": "invalid_product",- }- )-- with pytest.raises(dagster.Failure, match="Invalid require_existing_product"):- populate_user_product_list(context)-- @pytest.mark.django_db- def test_populate_fails_with_invalid_reason(self):- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "reason": "invalid_reason",- }- )-- with pytest.raises(Exception): # Dagster will fail at config validation time- populate_user_product_list(context)-- @pytest.mark.django_db- def test_populate_filters_by_role_at_organization(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user_engineering = User.objects.create(- email="[email protected]",- first_name="Engineer",- allow_sidebar_suggestions=True,- role_at_organization="engineering",- )- user_data = User.objects.create(- email="[email protected]",- first_name="Data",- allow_sidebar_suggestions=True,- role_at_organization="data",- )- user_no_role = User.objects.create(- email="[email protected]",- first_name="NoRole",- allow_sidebar_suggestions=True,- role_at_organization=None,- )- user_engineering.join(organization=org)- user_data.join(organization=org)- user_no_role.join(organization=org)-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "role_at_organization": "engineering",- }- )-- populate_user_product_list(context)-- eng_entry = UserProductList.objects.filter(user=user_engineering, team=team)- data_entry = UserProductList.objects.filter(user=user_data, team=team)- no_role_entry = UserProductList.objects.filter(user=user_no_role, team=team)-- assert eng_entry.count() == 1- assert data_entry.count() == 0- assert no_role_entry.count() == 0-- metadata = context.get_output_metadata("result")- assert metadata["created"].value == 1-- @pytest.mark.django_db- def test_populate_fails_with_invalid_role_at_organization(self):- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "role_at_organization": "invalid_role",- }- )-- with pytest.raises(dagster.Failure, match="Invalid role_at_organization"):- populate_user_product_list(context)-- @pytest.mark.django_db- def test_populate_filters_by_emails_from_s3(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user1 = User.objects.create(- email="[email protected]",- first_name="User1",- allow_sidebar_suggestions=True,- )- user2 = User.objects.create(- email="[email protected]",- first_name="User2",- allow_sidebar_suggestions=True,- )- user3 = User.objects.create(- email="[email protected]",- first_name="User3",- allow_sidebar_suggestions=True,- )- user1.join(organization=org)- user2.join(organization=org)- user3.join(organization=org)-- email_list_content = "[email protected]\[email protected]\n"- mock_s3_client = MagicMock()- mock_response = MagicMock()- mock_response["Body"].read.return_value = email_list_content.encode("utf-8")- mock_s3_client.get_object.return_value = mock_response-- mock_s3_resource = MagicMock()- mock_s3_resource.get_client.return_value = mock_s3_client-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "email_filter_s3_url": "s3://my-bucket/emails.txt",- },- resources={"s3": mock_s3_resource},- )-- populate_user_product_list(context)-- user1_entry = UserProductList.objects.filter(user=user1, team=team)- user2_entry = UserProductList.objects.filter(user=user2, team=team)- user3_entry = UserProductList.objects.filter(user=user3, team=team)-- assert user1_entry.count() == 1- assert user2_entry.count() == 1- assert user3_entry.count() == 0-- mock_s3_resource.get_client.assert_called_once()- mock_s3_client.get_object.assert_called_once_with(Bucket="my-bucket", Key="emails.txt")-- metadata = context.get_output_metadata("result")- assert metadata["created"].value == 2-- @pytest.mark.django_db- def test_populate_filters_by_emails_from_s3_case_insensitive(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user_upper = User.objects.create(email="[email protected]", first_name="Upper", allow_sidebar_suggestions=True)- user_lower = User.objects.create(email="[email protected]", first_name="Lower", allow_sidebar_suggestions=True)- user_upper.join(organization=org)- user_lower.join(organization=org)-- email_list_content = "[email protected]\n"- mock_s3_client = MagicMock()- mock_response = MagicMock()- mock_response["Body"].read.return_value = email_list_content.encode("utf-8")- mock_s3_client.get_object.return_value = mock_response-- mock_s3_resource = MagicMock()- mock_s3_resource.get_client.return_value = mock_s3_client-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "email_filter_s3_url": "s3://my-bucket/emails.txt",- },- resources={"s3": mock_s3_resource},- )-- populate_user_product_list(context)-- upper_entry = UserProductList.objects.filter(user=user_upper, team=team)- lower_entry = UserProductList.objects.filter(user=user_lower, team=team)-- assert upper_entry.count() == 1- assert lower_entry.count() == 1-- @pytest.mark.django_db- def test_populate_filters_by_emails_from_s3_with_whitespace(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user = User.objects.create(email="[email protected]", first_name="User", allow_sidebar_suggestions=True)- user.join(organization=org)-- email_list_content = " [email protected] \n\n [email protected] \n"- mock_s3_client = MagicMock()- mock_response = MagicMock()- mock_response["Body"].read.return_value = email_list_content.encode("utf-8")- mock_s3_client.get_object.return_value = mock_response-- mock_s3_resource = MagicMock()- mock_s3_resource.get_client.return_value = mock_s3_client-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "email_filter_s3_url": "s3://my-bucket/emails.txt",- },- resources={"s3": mock_s3_resource},- )-- populate_user_product_list(context)-- entry = UserProductList.objects.filter(user=user, team=team)- assert entry.count() == 1-- @pytest.mark.django_db- def test_populate_filters_by_emails_from_s3_empty_list(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user = User.objects.create(email="[email protected]", first_name="User", allow_sidebar_suggestions=True)- user.join(organization=org)-- email_list_content = ""- mock_s3_client = MagicMock()- mock_response = MagicMock()- mock_response["Body"].read.return_value = email_list_content.encode("utf-8")- mock_s3_client.get_object.return_value = mock_response-- mock_s3_resource = MagicMock()- mock_s3_resource.get_client.return_value = mock_s3_client-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "email_filter_s3_url": "s3://my-bucket/emails.txt",- },- resources={"s3": mock_s3_resource},- )-- populate_user_product_list(context)-- entry = UserProductList.objects.filter(user=user, team=team)- assert entry.count() == 0-- @pytest.mark.django_db- def test_populate_fails_with_invalid_s3_url_scheme(self):- mock_s3_resource = MagicMock()-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "email_filter_s3_url": "https://my-bucket/emails.txt",- },- resources={"s3": mock_s3_resource},- )-- with pytest.raises(- dagster.Failure,- match="Failed to download or process email filter from S3",- ):- populate_user_product_list(context)-- @pytest.mark.django_db- def test_populate_fails_with_invalid_s3_url_format(self):- mock_s3_resource = MagicMock()-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "email_filter_s3_url": "s3://",- },- resources={"s3": mock_s3_resource},- )-- with pytest.raises(- dagster.Failure,- match="Failed to download or process email filter from S3",- ):- populate_user_product_list(context)-- @pytest.mark.django_db- def test_populate_fails_when_s3_download_fails(self):- mock_s3_client = MagicMock()- mock_s3_client.get_object.side_effect = Exception("S3 access denied")-- mock_s3_resource = MagicMock()- mock_s3_resource.get_client.return_value = mock_s3_client-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "email_filter_s3_url": "s3://my-bucket/emails.txt",- },- resources={"s3": mock_s3_resource},- )-- with pytest.raises(- dagster.Failure,- match="Failed to download or process email filter from S3",- ):- populate_user_product_list(context)-- @pytest.mark.django_db- def test_populate_combines_email_filter_with_other_filters(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user1 = User.objects.create(- email="[email protected]",- first_name="User1",- allow_sidebar_suggestions=True,- role_at_organization="engineering",- )- user2 = User.objects.create(- email="[email protected]",- first_name="User2",- allow_sidebar_suggestions=True,- role_at_organization="data",- )- user3 = User.objects.create(- email="[email protected]",- first_name="User3",- allow_sidebar_suggestions=True,- role_at_organization="engineering",- )- user1.join(organization=org)- user2.join(organization=org)- user3.join(organization=org)-- mock_s3_client = MagicMock()- mock_response = MagicMock()- mock_response["Body"].read.return_value = email_list_content.encode("utf-8")- mock_s3_client.get_object.return_value = mock_response-- mock_s3_resource = MagicMock()- mock_s3_resource.get_client.return_value = mock_s3_client-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- context = build_default_context(- op_config={- "product_paths": ["product_analytics"],- "email_filter_s3_url": "s3://my-bucket/emails.txt",- "role_at_organization": "engineering",- },- resources={"s3": mock_s3_resource},- )-- populate_user_product_list(context)-- user1_entry = UserProductList.objects.filter(user=user1, team=team)- user2_entry = UserProductList.objects.filter(user=user2, team=team)- user3_entry = UserProductList.objects.filter(user=user3, team=team)-- assert user1_entry.count() == 1- assert user2_entry.count() == 0- assert user3_entry.count() == 1---class TestPopulateUserProductListJob:- @pytest.mark.django_db- def test_job_execution_success(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user = User.objects.create(email="[email protected]", first_name="Test", allow_sidebar_suggestions=True)- user.join(organization=org)-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- result = populate_user_product_list_job.execute_in_process(- run_config={- "ops": {- "populate_user_product_list": {- "config": {- "product_paths": ["product_analytics"],- "reason": "product_intent",- }- }- }- },- resources={"s3": create_mock_s3_resource()},- )-- assert result.success-- entry = UserProductList.objects.get(user=user, team=team, product_path="product_analytics")- assert entry.reason == "product_intent"-- @pytest.mark.django_db- def test_job_respects_allow_sidebar_suggestions(self):- org = Organization.objects.create(name="Test Org")- team = Team.objects.create(organization=org, name="Test Team")- user_allowed = User.objects.create(- email="[email protected]",- first_name="Allowed",- allow_sidebar_suggestions=True,- )- user_disallowed = User.objects.create(- email="[email protected]",- first_name="Disallowed",- allow_sidebar_suggestions=False,- )- user_allowed.join(organization=org)- user_disallowed.join(organization=org)-- with patch(- "products.growth.dags.user_product_list.get_valid_product_paths",- return_value={"product_analytics"},- ):- result = populate_user_product_list_job.execute_in_process(- run_config={- "ops": {- "populate_user_product_list": {- "config": {- "product_paths": ["product_analytics"],- }- }- }- },- resources={"s3": create_mock_s3_resource()},- )-- assert result.success-- allowed_entry = UserProductList.objects.filter(user=user_allowed, team=team)- disallowed_entry = UserProductList.objects.filter(user=user_disallowed, team=team)-- assert allowed_entry.count() == 1- assert disallowed_entry.count() == 0diff --git a/products/growth/dags/user_product_list.py b/products/growth/dags/user_product_list.pydeleted file mode 100644index 2e384b388a91..000000000000--- a/products/growth/dags/user_product_list.py+++ /dev/null@@ -1,520 +0,0 @@-from dataclasses import dataclass-from typing import Literal-from urllib.parse import urlparse--from django.db import connections--import dagster-import pydantic--from posthog.dags.common import JobOwners-from posthog.dags.common.ops import get_all_team_ids_op-from posthog.exceptions_capture import capture_exception-from posthog.models.file_system.user_product_list import UserProductList, get_user_product_list_count-from posthog.models.team import Team-from posthog.models.user import ROLE_CHOICES, User-from posthog.products import Products---def get_valid_product_paths() -> set[str]:- """Get all valid product paths from products.json and hardcoded sidebar products"""- valid_paths = set[str](Products.get_product_paths())- return valid_paths---def download_emails_from_s3(s3_url: str, s3_client) -> set[str]:- """Download a list of emails from an S3 URL and return them as a set.-- Args:- s3_url: S3 URL in format s3://bucket/key- s3_client: boto3 S3 client from Dagster resource-- Returns:- Set of email addresses (lowercased and stripped)-- Raises:- ValueError: If S3 URL format is invalid- Exception: If S3 download fails- """- parsed = urlparse(s3_url)- if parsed.scheme != "s3":- raise ValueError(f"Invalid S3 URL scheme: {s3_url}. Expected s3://bucket/key")-- bucket = parsed.netloc- key = parsed.path.lstrip("/")-- if not bucket or not key:- raise ValueError(f"Invalid S3 URL format: {s3_url}. Expected s3://bucket/key")-- response = s3_client.get_object(Bucket=bucket, Key=key)- content = response["Body"].read().decode("utf-8")-- emails = set()- for line in content.splitlines():- email = line.strip().lower()- if email:- emails.add(email)-- return emails---class PopulateConfig(dagster.Config):- """Configuration for UserProductList populate operations"""-- product_paths: list[str] = pydantic.Field(- default=[],- description="List of product paths to add to users' product lists",- )- reason: str | None = pydantic.Field(- default=None,- description="Reason for creating UserProductList entries",- examples=UserProductList.Reason.values,- )- reason_text: str | None = pydantic.Field(- default=None,- description="Optional freeform text to be displayed to the user on hover",- )- require_existing_product: str | None = pydantic.Field(- default=None,- description="Only create entries for users who already have this product enabled in their UserProductList",- )- role_at_organization: str | None = pydantic.Field(- default=None,- description="Only process users with this role_at_organization value (e.g., 'engineering', 'data', 'product')",- )- email_filter_s3_url: str | None = pydantic.Field(- default=None,- description="S3 URL (s3://bucket/key) to a file containing emails (one per line) to filter users by",- )---def populate_user_product_list(- context: dagster.OpExecutionContext,- config: PopulateConfig,- s3: dagster.ResourceParam,-) -> None:- """- Populate UserProductList with configurable options:- - Set a specific reason for created entries- - Set optional reason_text for display to users- - Only create for users who have a specific product enabled- - Filter by role_at_organization (e.g., 'engineering', 'data', 'product')- - Filter by emails from an S3 URL (s3://bucket/key) containing one email per line- """- if not config.product_paths:- raise dagster.Failure("product_paths cannot be empty")-- # Validate product paths against valid products- valid_paths = get_valid_product_paths()- invalid_paths = [path for path in config.product_paths if path not in valid_paths]- if invalid_paths:- raise dagster.Failure(f"Invalid product paths: {invalid_paths}. Valid options: {sorted(valid_paths)}")-- # Validate require_existing_product if provided- if config.require_existing_product is not None and config.require_existing_product not in valid_paths:- raise dagster.Failure(- f"Invalid require_existing_product: {config.require_existing_product}. Valid options: {sorted(valid_paths)}"- )-- # Validate reason if provided- if config.reason:- if config.reason not in UserProductList.Reason.values:- raise dagster.Failure(f"Invalid reason: {config.reason}. Valid options: {UserProductList.Reason.values}")-- # Validate role_at_organization if provided-- valid_roles = [choice[0] for choice in ROLE_CHOICES]- if config.role_at_organization is not None and config.role_at_organization not in valid_roles:- raise dagster.Failure(- f"Invalid role_at_organization: {config.role_at_organization}. Valid options: {valid_roles}"- )-- context.log.info(f"Starting populate for {len(config.product_paths)} products: {config.product_paths}")-- # Build user queryset with filters- users = User.objects.all().order_by("date_joined")-- # Filter by existing products requirement- if config.require_existing_product:- users_with_product = (- UserProductList.objects.filter(product_path=config.require_existing_product, enabled=True)- .values_list("user_id", flat=True)- .distinct()- )- users = users.filter(id__in=users_with_product)- context.log.info(f"Only processing users with '{config.require_existing_product}' enabled")-- # Filter by role_at_organization if specified- if config.role_at_organization:- users = users.filter(role_at_organization=config.role_at_organization)- context.log.info(f"Only processing users with role_at_organization='{config.role_at_organization}'")-- # Download emails from S3 if specified (will filter in loop for performance)- allowed_emails: set[str] | None = None- if config.email_filter_s3_url:- try:- context.log.info(f"Downloading email filter from S3: {config.email_filter_s3_url}")- s3_client = s3.get_client()- allowed_emails = download_emails_from_s3(config.email_filter_s3_url, s3_client)- context.log.info(f"Loaded {len(allowed_emails)} emails from S3")- if not allowed_emails:- context.log.warning("Email filter from S3 is empty, no users will match")- except Exception as e:- raise dagster.Failure(f"Failed to download or process email filter from S3: {str(e)}")-- # Respect user preference for sidebar suggestions- users = users.exclude(allow_sidebar_suggestions=False)- context.log.info("Excluding users with allow_sidebar_suggestions=False")-- total_users = users.count()- context.log.info(f"Processing {total_users} users")-- created_count = 0- skipped_count = 0-- for user in users.iterator(chunk_size=1000):- # Filter by email if email filter is specified- if allowed_emails is not None and user.email.lower() not in allowed_emails:- context.log.debug(f"Skipping user {user.id} because their email {user.email} is not in the allowed emails")- continue-- # Get all teams this user has access to through organization membership- teams = Team.objects.filter(organization__members=user).distinct()-- for team in teams:- for product_path in config.product_paths:- _, created = UserProductList.objects.get_or_create(- team=team,- user=user,- product_path=product_path,- defaults={- "enabled": True,- "reason": config.reason,- "reason_text": config.reason_text,- },- )-- if created:- created_count += 1- else:- skipped_count += 1-- if created_count != 0 and created_count % 1000 == 0:- context.log.info(- f"Progress: {created_count} created, {skipped_count} skipped (processed user {user.id})"- )-- context.log.info(f"Populate complete: {created_count} created, {skipped_count} skipped")-- context.add_output_metadata(- {- "created": dagster.MetadataValue.int(created_count),- "skipped": dagster.MetadataValue.int(skipped_count),- "total_products": dagster.MetadataValue.int(len(config.product_paths)),- "reason": dagster.MetadataValue.text(config.reason or "None"),- }- )--[email protected](tags={"owner": JobOwners.TEAM_GROWTH.value})-def populate_user_product_list_job():- """- Add products to users' product lists with configurable options.- - product_paths: List of product paths to add (required)- - reason: Optional reason from UserProductList.Reason- - reason_text: Optional freeform text to display to users on hover- - require_existing_product: Only add for users who have this product enabled- - role_at_organization: Only process users with this role (e.g., 'engineering', 'data')- - email_filter_s3_url: S3 URL (s3://bucket/key) to a file containing emails (one per line) to filter users by- """- populate_user_product_list()---@dataclass(kw_only=True)-class SyncColleaguesProductsResult:- team_id: int- users_processed: int- products_created: int- status: Literal["success", "failed", "error"]---def sync_colleagues_products_for_team_op(- context: dagster.OpExecutionContext,- team_ids: list[int],-) -> list[SyncColleaguesProductsResult]:- """Sync colleague products for all users in a batch of teams."""- results = []-- for team_id in team_ids:- try:- team = Team.objects.get(id=team_id)- users_processed = 0- products_created = 0-- colleague_product_counts = get_user_product_list_count(team)-- users_qs = (- team.all_users_with_access()- .exclude(allow_sidebar_suggestions=False)- .only("id", "allow_sidebar_suggestions")- )- for user in users_qs.iterator(chunk_size=500):- created_items = UserProductList.sync_from_team_colleagues(- user=user,- team=team,- colleague_product_counts=colleague_product_counts,- )- users_processed += 1- products_created += len(created_items)-- context.log.info(- f"Team {team_id}: processed {users_processed} users, created {products_created} product entries"- )-- results.append(- SyncColleaguesProductsResult(- team_id=team_id,- users_processed=users_processed,- products_created=products_created,- status="success",- )- )- except Team.DoesNotExist:- context.log.warning(f"Team {team_id} not found")- results.append(- SyncColleaguesProductsResult(- team_id=team_id,- users_processed=0,- products_created=0,- status="failed",- )- )- except Exception as e:- context.log.exception(f"Failed to process team {team_id}")- capture_exception(e, {"team_id": team_id, "team": "team-growth"})- results.append(- SyncColleaguesProductsResult(- team_id=team_id,- users_processed=0,- products_created=0,- status="error",- )- )- finally:- # Release per-connection buffers between teams to keep RSS flat- # across a 1000-team batch inside one subprocess.- connections.close_all()-- success_results = [r for r in results if r.status == "success"]- failed_results = [r for r in results if r.status in ("failed", "error")]-- context.add_output_metadata(- {- "batch_size": dagster.MetadataValue.int(len(team_ids)),- "processed": dagster.MetadataValue.int(len(results)),- "success_count": dagster.MetadataValue.int(len(success_results)),- "failed_count": dagster.MetadataValue.int(len(failed_results)),- "total_users_processed": dagster.MetadataValue.int(sum(r.users_processed for r in results)),- "total_products_created": dagster.MetadataValue.int(sum(r.products_created for r in results)),- }- )-- return results---def aggregate_colleagues_sync_results_op(- context: dagster.OpExecutionContext,- results: list[list[SyncColleaguesProductsResult]],-) -> None:- """Aggregate results from all team processing ops."""- flat_results = [r for batch in results for r in batch]-- total_teams = len(flat_results)- success_count = sum(1 for r in flat_results if r.status == "success")- failed_count = sum(1 for r in flat_results if r.status in ("failed", "error"))- total_users_processed = sum(r.users_processed for r in flat_results)- total_products_created = sum(r.products_created for r in flat_results)-- context.log.info(- f"Completed processing {total_teams} teams: {success_count} succeeded, {failed_count} failed. "- f"Processed {total_users_processed} users, created {total_products_created} product entries"- )-- context.add_output_metadata(- {- "total_teams": dagster.MetadataValue.int(total_teams),- "success_count": dagster.MetadataValue.int(success_count),- "failed_count": dagster.MetadataValue.int(failed_count),- "total_users_processed": dagster.MetadataValue.int(total_users_processed),- "total_products_created": dagster.MetadataValue.int(total_products_created),- }- )-- if failed_count > 0:- failed_team_ids = [r.team_id for r in flat_results if r.status in ("failed", "error")]- context.log.warning(f"Failed to sync colleague products for {failed_count} teams: {failed_team_ids}")--- description="Syncs products used by colleagues to each user's product list for all teams",- executor_def=dagster.multiprocess_executor.configured({"max_concurrent": 5}),- tags={"owner": JobOwners.TEAM_GROWTH.value},-)-def sync_colleagues_products_monthly_job():- """- Monthly job that syncs products used by colleagues to each user's product list.- For each team, finds the most popular products among colleagues and suggests them to users.-- Not on a schedule: connection-time default seeding replaced it, but the job is kept- available for manual runs from the Dagster UI.- """- team_ids = get_all_team_ids_op()- results = team_ids.map(sync_colleagues_products_for_team_op)- aggregate_colleagues_sync_results_op(results.collect())---@dataclass(kw_only=True)-class SyncCrossSellProductsResult:- team_id: int- users_processed: int- products_created: int- status: Literal["success", "failed", "error"]---def sync_cross_sell_products_for_team_op(- context: dagster.OpExecutionContext,- team_ids: list[int],-) -> list[SyncCrossSellProductsResult]:- """Sync cross-sell products for all users in a batch of teams."""- results = []-- for team_id in team_ids:- try:- team = Team.objects.get(id=team_id)- users_processed = 0- products_created = 0-- users_qs = (- team.all_users_with_access()- .exclude(allow_sidebar_suggestions=False)- .only("id", "allow_sidebar_suggestions")- )- for user in users_qs.iterator(chunk_size=500):- created_items = UserProductList.sync_cross_sell_products(user=user, team=team)- users_processed += 1- products_created += len(created_items)-- context.log.info(- f"Team {team_id}: processed {users_processed} users, created {products_created} cross-sell product entries"- )-- results.append(- SyncCrossSellProductsResult(- team_id=team_id,- users_processed=users_processed,- products_created=products_created,- status="success",- )- )- except Team.DoesNotExist:- context.log.warning(f"Team {team_id} not found")- results.append(- SyncCrossSellProductsResult(- team_id=team_id,- users_processed=0,- products_created=0,- status="failed",- )- )- except Exception as e:- context.log.exception(f"Failed to process team {team_id}")- capture_exception(e, {"team_id": team_id, "team": "team-growth"})- results.append(- SyncCrossSellProductsResult(- team_id=team_id,- users_processed=0,- products_created=0,- status="error",- )- )- finally:- # Release per-connection buffers between teams to keep RSS flat- # across a 1000-team batch inside one subprocess.- connections.close_all()-- success_results = [r for r in results if r.status == "success"]- failed_results = [r for r in results if r.status in ("failed", "error")]-- context.add_output_metadata(- {- "batch_size": dagster.MetadataValue.int(len(team_ids)),- "processed": dagster.MetadataValue.int(len(results)),- "success_count": dagster.MetadataValue.int(len(success_results)),- "failed_count": dagster.MetadataValue.int(len(failed_results)),- "total_users_processed": dagster.MetadataValue.int(sum(r.users_processed for r in results)),- "total_products_created": dagster.MetadataValue.int(sum(r.products_created for r in results)),- }- )-- return results---def aggregate_cross_sell_sync_results_op(- context: dagster.OpExecutionContext,- results: list[list[SyncCrossSellProductsResult]],-) -> None:- """Aggregate results from all team processing ops."""- flat_results = [r for batch in results for r in batch]-- total_teams = len(flat_results)- success_count = sum(1 for r in flat_results if r.status == "success")- failed_count = sum(1 for r in flat_results if r.status in ("failed", "error"))- total_users_processed = sum(r.users_processed for r in flat_results)- total_products_created = sum(r.products_created for r in flat_results)-- context.log.info(- f"Completed processing {total_teams} teams: {success_count} succeeded, {failed_count} failed. "- f"Processed {total_users_processed} users, created {total_products_created} cross-sell product entries"- )-- context.add_output_metadata(- {- "total_teams": dagster.MetadataValue.int(total_teams),- "success_count": dagster.MetadataValue.int(success_count),- "failed_count": dagster.MetadataValue.int(failed_count),- "total_users_processed": dagster.MetadataValue.int(total_users_processed),- "total_products_created": dagster.MetadataValue.int(total_products_created),- }- )-- if failed_count > 0:- failed_team_ids = [r.team_id for r in flat_results if r.status in ("failed", "error")]- context.log.warning(f"Failed to sync cross-sell products for {failed_count} teams: {failed_team_ids}")--- description="Syncs cross-sell products from the same category to users' product lists for all teams",- executor_def=dagster.multiprocess_executor.configured({"max_concurrent": 5}),- tags={"owner": JobOwners.TEAM_GROWTH.value},-)-def sync_cross_sell_products_monthly_job():- """- Monthly job that syncs cross-sell products to each user's product list.- For each user, finds products in the same category as their enabled products and suggests them.- """- team_ids = get_all_team_ids_op()- results = team_ids.map(sync_cross_sell_products_for_team_op)- aggregate_cross_sell_sync_results_op(results.collect())---sync_cross_sell_products_monthly_schedule = dagster.ScheduleDefinition(- job=sync_cross_sell_products_monthly_job,- cron_schedule="0 5 1 * *", # 1st day of every month at 5am UTC- execution_timezone="UTC",- name="sync_cross_sell_products_monthly_schedule",-)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex abbb9500a0a0..373f748b3a1a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -58490,39 +58490,10 @@ export namespace Schemas {results: User[];}- /**- * * `default` - Default- * * `onboarding` - Onboarding- * * `product_intent` - Product Intent- * * `used_by_colleagues` - Used by Colleagues- * * `used_similar_products` - Used Similar Products- * * `used_on_separate_team` - Used on Separate Team- * * `new_product` - New Product- * * `sales_led` - Sales Led- * * `onboarding_delegated` - Onboarding Delegated- */- export type UserProductListReasonEnum = typeof UserProductListReasonEnum[keyof typeof UserProductListReasonEnum];--- export const UserProductListReasonEnum = {- Default: 'default',- Onboarding: 'onboarding',- ProductIntent: 'product_intent',- UsedByColleagues: 'used_by_colleagues',- UsedSimilarProducts: 'used_similar_products',- UsedOnSeparateTeam: 'used_on_separate_team',- NewProduct: 'new_product',- SalesLed: 'sales_led',- OnboardingDelegated: 'onboarding_delegated',- } as const;-export interface UserProductList {readonly id: string;readonly product_path: string;enabled?: boolean;- readonly reason: UserProductListReasonEnum | null;- /** @nullable */- readonly reason_text: string | null;readonly created_at: string;/** @nullable */readonly updated_at: string | null;@@ -67325,9 +67296,6 @@ export namespace Schemas {readonly id?: string;readonly product_path?: string;enabled?: boolean;- readonly reason?: UserProductListReasonEnum | null;- /** @nullable */- readonly reason_text?: string | null;readonly created_at?: string;/** @nullable */readonly updated_at?: string | null;