: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(messaging): publish configured push app_ids in remote config (#83148)
Daniel Marchukb686b0d5355c
diff --git a/docs/internal/push-subscription-registration.md b/docs/internal/push-subscription-registration.mdnew file mode 100644index 000000000000..47186d9231f6--- /dev/null+++ b/docs/internal/push-subscription-registration.md@@ -0,0 +1,77 @@+# Push subscription registration++How a mobile device registers a push token, and what an SDK has to do so that a project without push+configured does not generate a request per device per app open.++## The flow++A mobile SDK with push capture enabled posts its device token to `/api/push_subscriptions/` when the+app starts. The server resolves the `app_id` to a Firebase or APNs integration on the team and stores+the token as a `$device_push_subscription_<app_id>` person property.++Push is opt-in per project, and the SDK cannot see whether a project opted in. So an app that ships+with push capture on registers against every project it reports to, configured or not.++## What the server does with an unconfigured `app_id`++`POST` answers `200` with `{"stored": false, "push_enabled": false}` and does not store the token.+`DELETE` still runs its `$unset`, because a logout has to clear a subscription stored while an+integration existed.++The 200 is deliberate. A 4xx makes this the error path for the majority of the requests the endpoint+receives, which is both wrong (nothing about the request was invalid) and expensive to everything+that watches non-2xx rates.++## The `push.appIds` remote config key++Remote config carries the list of `app_id`s a team can accept registrations for:++```json+{ "push": { "appIds": ["my-firebase-project", "com.example.app"] } }+```++Firebase contributes its `project_id`, APNs its `bundle_id`. The key is always present, including as+an empty list.++**Absent and empty are not the same thing.** Absent means the server predates this key, so the SDK+cannot conclude anything and must attempt the registration. Empty means the server said this team has+no push configured. An SDK that treats absent as empty stops registering against every older+self-hosted deployment.++## What an SDK has to do++1. **Absent key** — register as before.+2. **`app_id` not in `appIds`** — skip the request entirely. There is nothing to register against, and+ the server would discard it.+3. **`app_id` appears in `appIds` having been absent before** — clear any local record that the token+ was already delivered, and register.++Rule 3 is the one that is easy to miss, and without it a project that turns push on never reaches the+devices it already has.++## Why rule 3 exists++Both mobile SDKs persist a delivered marker (`deliveredForDistinctId`) alongside the pending+registration, and skip the request when the stored token, `app_id` and distinct id all match. The+marker is written on any 2xx and survives a process restart, which is what stops a device re-posting+on every launch.++It also means a device that registered while its project was unconfigured recorded a success for a+token the server never kept. Nothing on the server can undo that: no response reaches a device that+has stopped asking. The only triggers left are a token rotation, an `identify()` to a different+distinct id, or a reinstall.++So a device that registered before its project was configured stays unreachable until it updates to an+SDK that implements rule 3.++## Server-side notes++- `build_push_config` in `products/messaging/backend/remote_config.py` derives the list. A `post_save`+ and `post_delete` receiver on `Integration` rebuilds the team's remote config when a `firebase` or+ `apns` integration changes, so a project that configures push is published without waiting for an+ unrelated write.+- Non-string identifiers are skipped. `Integration.config` is a `JSONField`, and an unusable value+ would otherwise raise inside `build_config` and leave the team's whole remote config stale.+- Registration outcomes are observable through `push_subscription_rejection{code, method}`,+ `push_subscription_discarded{reason}`, and the `push_subscription_discarded` log line, which is+ emitted once per team per minute rather than once per request.diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.pyindex b769b5bb665f..658ecd00ef99 100644--- a/posthog/models/remote_config.py+++ b/posthog/models/remote_config.py@@ -213,6 +213,7 @@ class RemoteConfig(UUIDTModel):from products.error_tracking.backend.facade import build_error_tracking_configfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+ from products.messaging.backend.remote_config import build_push_configfrom products.surveys.backend.api.survey import get_surveys_opt_in, get_surveys_response# NOTE: It is important this is changed carefully. This is what the SDK will load in place of "decide" so the format@@ -248,6 +249,9 @@ class RemoteConfig(UUIDTModel):# MARK: Error trackingconfig["errorTracking"] = build_error_tracking_config(team)+ # MARK: Push notifications+ config["push"] = build_push_config(team)+# MARK: Logslogs_settings = team.logs_settings or {}config["logs"] = {@@ -591,3 +595,21 @@ def error_tracking_suppression_rule_saved(sender, instance, created, **kwargs):@receiver(post_save, sender="posthog.TeamJsSnippetConfig")def js_snippet_config_saved(sender, instance, created, **kwargs):transaction.on_commit(lambda: _update_team_remote_config(instance.team_id))+++@receiver(post_save, sender="posthog.Integration")+@receiver(post_delete, sender="posthog.Integration")+def push_integration_changed(sender, instance, **kwargs):+ from products.messaging.backend.remote_config import PUSH_APP_ID_CONFIG_KEYS++ # Integrations cover every kind we support, and most of them have nothing to do with the SDK+ # payload. Only refresh for the two push kinds, so an OAuth token refresh on an unrelated+ # integration doesn't enqueue a rebuild for every team that has one.+ if instance.kind not in PUSH_APP_ID_CONFIG_KEYS:+ return+ # The app_ids live in config, and integration code saves errors and created_by on their own —+ # apns_integration alone does three saves per creation. Only config can change the payload.+ update_fields = kwargs.get("update_fields")+ if update_fields is not None and "config" not in update_fields:+ return+ transaction.on_commit(lambda: _update_team_remote_config(instance.team_id))diff --git a/posthog/models/test/__snapshots__/test_remote_config.ambr b/posthog/models/test/__snapshots__/test_remote_config.ambrindex f9bd34fd2a06..545653842085 100644--- a/posthog/models/test/__snapshots__/test_remote_config.ambr+++ b/posthog/models/test/__snapshots__/test_remote_config.ambr@@ -26,6 +26,10 @@'captureConsoleLogs': False,}),'productTours': False,+ 'push': dict({+ 'appIds': list([+ ]),+ }),'sessionRecording': dict({'canvasFps': None,'canvasQuality': None,diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.pyindex 584bb46a5eb3..b5d63ee945a4 100644--- a/posthog/models/test/test_remote_config.py+++ b/posthog/models/test/test_remote_config.py@@ -11,6 +11,7 @@ from django.utils import timezonefrom parameterized import parameterized+from posthog.models.integration import Integrationfrom posthog.models.project import Projectfrom posthog.models.remote_config import REMOTE_CONFIG_CACHE_EXPIRY_SORTED_SET, RemoteConfig@@ -133,6 +134,37 @@ class TestRemoteConfig(_RemoteConfigBase):self.sync_remote_config()assert self.remote_config.config["autocaptureExceptions"]+ @parameterized.expand([("firebase", True), ("apns", True), ("slack", False)])+ def test_only_push_integrations_schedule_a_config_rebuild(self, kind, expects_rebuild):+ # Configuring push is the moment the payload has to change, and nothing else on the team is+ # touched when it happens. Guard both directions: without the receiver a project that+ # configures push keeps serving the old empty appIds, and without the kind check every OAuth+ # token refresh on an unrelated integration would enqueue a rebuild.+ with patch("posthog.models.remote_config._update_team_remote_config") as mock_rebuild:+ with self.captureOnCommitCallbacks(execute=True):+ integration = Integration.objects.create(team=self.team, kind=kind, config={})+ assert mock_rebuild.called is expects_rebuild++ mock_rebuild.reset_mock()+ with self.captureOnCommitCallbacks(execute=True):+ integration.delete()+ assert mock_rebuild.called is expects_rebuild++ def test_push_integration_save_that_cannot_change_app_ids_skips_the_rebuild(self):+ # Integration code saves errors and created_by on their own — apns_integration does three+ # saves per creation. Without the update_fields guard each one enqueues a rebuild and a CDN+ # purge for a payload that cannot have changed.+ integration = Integration.objects.create(team=self.team, kind="apns", config={"bundle_id": "com.example.app"})++ with patch("posthog.models.remote_config._update_team_remote_config") as mock_rebuild:+ with self.captureOnCommitCallbacks(execute=True):+ integration.save(update_fields=["errors"])+ assert not mock_rebuild.called++ with self.captureOnCommitCallbacks(execute=True):+ integration.save(update_fields=["config"])+ assert mock_rebuild.called+def test_conversations_disabled_by_default(self):self.sync_remote_config()assert (diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex 7bd8ff9116f6..6a544ea17895 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -61,6 +61,7 @@ post_delete:posthog.models.organization.sync_billing_on_membership_removalpost_delete:posthog.models.organization_domain.delete_orphaned_identity_provider_configpost_delete:posthog.models.product_intent.product_intent._invalidate_product_intents_on_deletepost_delete:posthog.models.remote_config.product_tour_deleted+post_delete:posthog.models.remote_config.push_integration_changedpost_delete:posthog.models.remote_config.site_function_changedpost_delete:posthog.models.team.team.delete_team_in_cache_on_deletepost_delete:posthog.session.signals.delete_sessions_on_user_deletion@@ -124,6 +125,7 @@ post_save:posthog.models.remote_config.error_tracking_suppression_rule_savedpost_save:posthog.models.remote_config.feature_flag_savedpost_save:posthog.models.remote_config.js_snippet_config_savedpost_save:posthog.models.remote_config.product_tour_saved+post_save:posthog.models.remote_config.push_integration_changedpost_save:posthog.models.remote_config.site_app_savedpost_save:posthog.models.remote_config.site_function_changedpost_save:posthog.models.remote_config.survey_saveddiff --git a/products/messaging/backend/remote_config.py b/products/messaging/backend/remote_config.pynew file mode 100644index 000000000000..f923da38eb66--- /dev/null+++ b/products/messaging/backend/remote_config.py@@ -0,0 +1,31 @@+from posthog.models.integration import Integration+from posthog.models.team.team import Team++# Firebase identifies an app by its project_id, APNs by its bundle_id. Kept in step with+# _find_integrations in products/messaging/backend/api/push_subscriptions.py, which resolves the same+# mapping in the opposite direction (app_id to integration).+PUSH_APP_ID_CONFIG_KEYS = {"firebase": "project_id", "apns": "bundle_id"}+++def build_push_config(team: Team) -> dict:+ """The app_ids this team can accept device registrations for.++ Mobile SDKs register a device token on launch whenever push capture is on, and the registration+ endpoint rejects any app_id with no matching integration. Publishing the configured ids lets an SDK+ skip the request entirely rather than posting a rejection on every process start.++ Always present, including as an empty list. An SDK cannot tell an unconfigured project from an+ older server that never sends the key, so absent has to keep meaning "attempt the registration".+ """+ integrations = Integration.objects.filter(team=team, kind__in=list(PUSH_APP_ID_CONFIG_KEYS)).only("kind", "config")+ # config is a JSONField, so an identifier can be any JSON value. Anything but a non-empty string is+ # unusable as an app_id, and letting one through would raise inside the set or the sort — which+ # aborts build_config and leaves the team's whole remote config stale, not just its push key.+ app_ids = sorted(+ {+ app_id+ for integration in integrations+ if isinstance(app_id := integration.config.get(PUSH_APP_ID_CONFIG_KEYS[integration.kind]), str) and app_id+ }+ )+ return {"appIds": app_ids}diff --git a/products/messaging/backend/tests/test_remote_config.py b/products/messaging/backend/tests/test_remote_config.pynew file mode 100644index 000000000000..d4c608460c72--- /dev/null+++ b/products/messaging/backend/tests/test_remote_config.py@@ -0,0 +1,33 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.models.integration import Integration++from products.messaging.backend.remote_config import build_push_config+++class TestBuildPushConfig(BaseTest):+ @parameterized.expand(+ [+ ("firebase reads project_id", [("firebase", {"project_id": "my-project"})], ["my-project"]),+ ("apns reads bundle_id", [("apns", {"bundle_id": "com.example.app"})], ["com.example.app"]),+ ("other kinds are ignored", [("slack", {"project_id": "my-project"})], []),+ ("a push kind without its id key", [("firebase", {}), ("apns", {})], []),+ (+ "non-string identifiers",+ [("apns", {"bundle_id": ["com.example.app"]}), ("firebase", {"project_id": 42})],+ [],+ ),+ (+ "deduped and sorted",+ [("firebase", {"project_id": "b"}), ("apns", {"bundle_id": "a"}), ("firebase", {"project_id": "a"})],+ ["a", "b"],+ ),+ ]+ )+ def test_push_config_lists_the_app_ids_a_device_can_register_against(self, _name, integrations, expected_app_ids):+ for kind, config in integrations:+ Integration.objects.create(team=self.team, kind=kind, config=config)++ assert build_push_config(self.team) == {"appIds": expected_app_ids}