Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(cdp): move linkedin ads destination off sunset api version (#85324)

Xander3e6e711ba93e
diff --git a/nodejs/src/cdp/templates/_destinations/linkedin_ads/linkedin.template.test.ts b/nodejs/src/cdp/templates/_destinations/linkedin_ads/linkedin.template.test.ts
index e17d8af8b54a..abd88ec90589 100644
--- a/nodejs/src/cdp/templates/_destinations/linkedin_ads/linkedin.template.test.ts
+++ b/nodejs/src/cdp/templates/_destinations/linkedin_ads/linkedin.template.test.ts
@@ -1,5 +1,7 @@
import { DateTime, Settings } from 'luxon'
+import { parseJSON } from '~/common/utils/json-parse'
+
import { TemplateTester } from '../../test/test-helpers'
import { template } from './linkedin.template'
@@ -48,7 +50,7 @@ describe('linkedin template', () => {
"headers": {
"Authorization": "Bearer oauth-1234",
"Content-Type": "application/json",
- "LinkedIn-Version": "202508",
+ "LinkedIn-Version": "202607",
},
"method": "POST",
"type": "fetch",
@@ -65,6 +67,17 @@ describe('linkedin template', () => {
expect(fetchResponse.error).toBeUndefined()
})
+ it.each([
+ ['firstName', { lastName: 'AI', countryCode: 'US' }],
+ ['lastName', { firstName: 'Max', countryCode: 'US' }],
+ ])('omits userInfo when %s is missing', async (_missing, userInfo) => {
+ const response = await tester.invoke(buildInputs({ userInfo }))
+
+ const body = parseJSON((response.invocation.queueParameters as any).body)
+ expect(body.user.userInfo).toBeUndefined()
+ expect(body.user.userIds).toHaveLength(2)
+ })
+
it('does not contain empty objects', async () => {
const response = await tester.invoke(
buildInputs({
@@ -80,7 +93,7 @@ describe('linkedin template', () => {
"headers": {
"Authorization": "Bearer oauth-1234",
"Content-Type": "application/json",
- "LinkedIn-Version": "202508",
+ "LinkedIn-Version": "202607",
},
"method": "POST",
"type": "fetch",
diff --git a/nodejs/src/cdp/templates/_destinations/linkedin_ads/linkedin.template.ts b/nodejs/src/cdp/templates/_destinations/linkedin_ads/linkedin.template.ts
index cbb28747f9aa..adec74134aeb 100644
--- a/nodejs/src/cdp/templates/_destinations/linkedin_ads/linkedin.template.ts
+++ b/nodejs/src/cdp/templates/_destinations/linkedin_ads/linkedin.template.ts
@@ -36,7 +36,9 @@ for (let key, value in inputs.userInfo) {
userInfo[key] := value
}
}
-if (length(keys(userInfo)) >= 1) {
+// LinkedIn requires firstName and lastName within userInfo and rejects a partial object with a 422,
+// so send userInfo only when both are present and fall back to matching on userIds alone.
+if (not empty(userInfo['firstName']) and not empty(userInfo['lastName'])) {
body.user['userInfo'] := userInfo
}
@@ -51,7 +53,7 @@ let res := fetch('https://api.linkedin.com/rest/conversionEvents', {
'headers': {
'Authorization': f'Bearer {inputs.oauth.access_token}',
'Content-Type': 'application/json',
- 'LinkedIn-Version': '202508'
+ 'LinkedIn-Version': '202607'
},
'body': body
})
diff --git a/posthog/management/commands/test/test_update_hog_function_code.py b/posthog/management/commands/test/test_update_hog_function_code.py
index 1411664158a7..bb207e62c293 100644
--- a/posthog/management/commands/test/test_update_hog_function_code.py
+++ b/posthog/management/commands/test/test_update_hog_function_code.py
@@ -43,6 +43,109 @@ COMMENTED_OUT_STALE = (
"// throw Error('Invalid URL.')\n// }"
) + _SEND_BODY
+# The two LinkedIn hog shapes carrying a version header in production. Destinations created from the
+# Python-era template (before Oct 2025, including those bumped from 202409 by linked-api-version-update)
+# build body.user.userInfo in place with no guard; destinations created later collect userInfo into a
+# local and guard on its length. `{version}` is substituted per test.
+LINKEDIN_LEGACY_SHAPE = """
+let body := {
+ 'conversion': f'urn:lla:llaPartnerConversion:{inputs.conversionRuleId}',
+ 'conversionHappenedAt': inputs.conversionDateTime,
+ 'user': {
+ 'userIds': [],
+ 'userInfo': {}
+ },
+ 'eventId' : inputs.eventId
+}
+
+if (not empty(inputs.conversionValue) or not empty(inputs.currencyCode)) {
+ body.conversionValue := {}
+}
+if (not empty(inputs.currencyCode)) {
+ body.conversionValue.currencyCode := inputs.currencyCode
+}
+if (not empty(inputs.conversionValue)) {
+ body.conversionValue.amount := inputs.conversionValue
+}
+
+for (let key, value in inputs.userInfo) {
+ if (not empty(value)) {
+ body.user.userInfo[key] := value
+ }
+}
+
+for (let key, value in inputs.userIds) {
+ if (not empty(value)) {
+ body.user.userIds := arrayPushBack(body.user.userIds, {'idType': key, 'idValue': value})
+ }
+}
+
+let res := fetch('https://api.linkedin.com/rest/conversionEvents', {
+ 'method': 'POST',
+ 'headers': {
+ 'Authorization': f'Bearer {inputs.oauth.access_token}',
+ 'Content-Type': 'application/json',
+ 'LinkedIn-Version': '{version}'
+ },
+ 'body': body
+})
+
+if (res.status >= 400) {
+ throw Error(f'Error from api.linkedin.com (status {res.status}): {res.body}')
+}
+""".strip()
+
+LINKEDIN_NEW_SHAPE = """
+let body := {
+ 'conversion': f'urn:lla:llaPartnerConversion:{inputs.conversionRuleId}',
+ 'conversionHappenedAt': inputs.conversionDateTime,
+ 'user': {
+ 'userIds': []
+ },
+ 'eventId' : inputs.eventId
+}
+
+if (not empty(inputs.conversionValue) or not empty(inputs.currencyCode)) {
+ body.conversionValue := {}
+}
+if (not empty(inputs.currencyCode)) {
+ body.conversionValue.currencyCode := inputs.currencyCode
+}
+if (not empty(inputs.conversionValue)) {
+ body.conversionValue.amount := inputs.conversionValue
+}
+
+let userInfo := {}
+for (let key, value in inputs.userInfo) {
+ if (not empty(value)) {
+ userInfo[key] := value
+ }
+}
+if (length(keys(userInfo)) >= 1) {
+ body.user['userInfo'] := userInfo
+}
+
+for (let key, value in inputs.userIds) {
+ if (not empty(value)) {
+ body.user.userIds := arrayPushBack(body.user.userIds, {'idType': key, 'idValue': value})
+ }
+}
+
+let res := fetch('https://api.linkedin.com/rest/conversionEvents', {
+ 'method': 'POST',
+ 'headers': {
+ 'Authorization': f'Bearer {inputs.oauth.access_token}',
+ 'Content-Type': 'application/json',
+ 'LinkedIn-Version': '{version}'
+ },
+ 'body': body
+})
+
+if (res.status >= 400) {
+ throw Error(f'Error from api.linkedin.com (status {res.status}): {res.body}')
+}
+""".strip()
+
class TestUpdateHogFunctionCode(BaseTest):
def setUp(self):
@@ -319,6 +422,60 @@ class TestUpdateHogFunctionCode(BaseTest):
self.assertIn("Found 0 destinations to process", output)
self.assertIn("Updated: 0", output)
+ def _create_linkedin_function(self, hog: str) -> HogFunction:
+ with patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers"):
+ return HogFunction.objects.create(
+ team=self.team,
+ name="LinkedIn Shape Function",
+ type="destination",
+ template_id="template-linkedin-ads",
+ hog=hog,
+ enabled=True,
+ )
+
+ @parameterized.expand(
+ [
+ ("legacy_shape", LINKEDIN_LEGACY_SHAPE),
+ ("new_shape", LINKEDIN_NEW_SHAPE),
+ ]
+ )
+ def test_linkedin_202607_migration_guards_userinfo_in_both_shapes(self, _name, shape):
+ function = self._create_linkedin_function(shape.replace("{version}", "202508"))
+
+ with patch(
+ "posthog.management.commands.update_hog_function_code.compile_hog",
+ return_value="compiled_bytecode",
+ ):
+ out = StringIO()
+ call_command("update_hog_function_code", replace_key="linkedin-api-version-update-202607", stdout=out)
+
+ function.refresh_from_db()
+ assert "'LinkedIn-Version': '202607'" in function.hog
+ assert "'LinkedIn-Version': '202508'" not in function.hog
+ # 202607 rejects a userInfo without both names, so no path may still attach one unguarded.
+ assert "not empty(userInfo['firstName']) and not empty(userInfo['lastName'])" in function.hog
+ assert "body.user.userInfo[key]" not in function.hog
+ assert "'userInfo': {}" not in function.hog
+ assert "length(keys(userInfo))" not in function.hog
+ # The migrated source must be valid Hog - guards against a typo in the replacement's to_string.
+ compile_hog_for_check(function.hog, "destination")
+
+ def test_linkedin_202607_migration_skips_202409_destinations(self):
+ legacy_202409 = LINKEDIN_LEGACY_SHAPE.replace("{version}", "202409")
+ function = self._create_linkedin_function(legacy_202409)
+
+ with patch(
+ "posthog.management.commands.update_hog_function_code.compile_hog",
+ return_value="compiled_bytecode",
+ ):
+ out = StringIO()
+ call_command("update_hog_function_code", replace_key="linkedin-api-version-update-202607", stdout=out)
+
+ function.refresh_from_db()
+ # 202409 destinations died a year ago and are revived separately with customer awareness,
+ # so the run must not touch any part of their code.
+ assert function.hog == legacy_202409
+
def _create_teams_function(self, hog: str) -> HogFunction:
with patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers"):
return HogFunction.objects.create(
diff --git a/posthog/management/commands/update_hog_function_code.py b/posthog/management/commands/update_hog_function_code.py
index 32b63cf7cb3e..04c64920e5b5 100644
--- a/posthog/management/commands/update_hog_function_code.py
+++ b/posthog/management/commands/update_hog_function_code.py
@@ -1,5 +1,5 @@
import time
-from typing import TypedDict
+from typing import NotRequired, TypedDict
from django.core.management.base import BaseCommand
from django.core.paginator import Paginator
@@ -21,6 +21,10 @@ class _Replacement(TypedDict):
class _ReplaceOption(TypedDict):
template_id: str
replacements: list[_Replacement]
+ # Skip a destination entirely unless its hog contains this string. For options whose replacements
+ # would otherwise also match code deliberately left behind (e.g. a sunset version kept dead on
+ # purpose), this pins the run to the intended cohort.
+ only_if_contains: NotRequired[str]
class Command(BaseCommand):
@@ -52,6 +56,46 @@ class Command(BaseCommand):
},
],
},
+ # LinkedIn supports each dated version for a minimum of one year, then rejects it with a
+ # 426 NONEXISTENT_VERSION on every call. 202508 passed that mark on 2026-08-01. 202409 is
+ # deliberately excluded: those destinations have been failing for a year already, so
+ # bumping them would abruptly revive dormant-but-enabled destinations and resume
+ # conversions into customers' LinkedIn Ads accounts without warning. Reviving those is
+ # handled separately with customer awareness.
+ #
+ # 202607 also enforces firstName and lastName within userInfo, so the version bump alone
+ # would turn the 426 into a 422 for any event lacking a name. The header bump and a
+ # userInfo guard have to land together for a destination to send successfully.
+ #
+ # Two hog shapes carry the 202508 header. Destinations created since Oct 2025 collect
+ # userInfo into a local and guard on its length; the guard just needs tightening to
+ # require both names. Older destinations (including those bumped from 202409 by
+ # linked-api-version-update) instead build body.user.userInfo in place with no guard and
+ # always send userInfo, even empty, so their whole userInfo section is replaced with the
+ # collect-and-guard form. only_if_contains keeps the userInfo replacements, which match
+ # both eras' code, from touching the excluded 202409 destinations.
+ "linkedin-api-version-update-202607": {
+ "template_id": "template-linkedin-ads",
+ "only_if_contains": "'LinkedIn-Version': '202508'",
+ "replacements": [
+ {
+ "from_string": "'LinkedIn-Version': '202508'",
+ "to_string": "'LinkedIn-Version': '202607'",
+ },
+ {
+ "from_string": "if (length(keys(userInfo)) >= 1) {",
+ "to_string": "if (not empty(userInfo['firstName']) and not empty(userInfo['lastName'])) {",
+ },
+ {
+ "from_string": "'userIds': [],\n 'userInfo': {}\n },",
+ "to_string": "'userIds': []\n },",
+ },
+ {
+ "from_string": "for (let key, value in inputs.userInfo) {\n if (not empty(value)) {\n body.user.userInfo[key] := value\n }\n}",
+ "to_string": "let userInfo := {}\nfor (let key, value in inputs.userInfo) {\n if (not empty(value)) {\n userInfo[key] := value\n }\n}\nif (not empty(userInfo['firstName']) and not empty(userInfo['lastName'])) {\n body.user['userInfo'] := userInfo\n}",
+ },
+ ],
+ },
"meta-ads-api-version-update": {
"template_id": "template-meta-ads",
"replacements": [
@@ -143,6 +187,10 @@ class Command(BaseCommand):
if not destination.hog:
continue
+ required_marker = replaceOption.get("only_if_contains")
+ if required_marker and required_marker not in destination.hog:
+ continue
+
new_hog = destination.hog
for replacement in replaceOption["replacements"]:
if replacement["from_string"] in new_hog:
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index bc6f0e07f541..c4176523e728 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -2975,7 +2975,7 @@ class LinkedInAdsIntegration:
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",
- "LinkedIn-Version": "202508",
+ "LinkedIn-Version": "202607",
},
timeout=10,
)
@@ -2990,7 +2990,7 @@ class LinkedInAdsIntegration:
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {self.integration.sensitive_config['access_token']}",
- "LinkedIn-Version": "202508",
+ "LinkedIn-Version": "202607",
},
timeout=10,
)