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(workflows): capture account action system failures in error tracking (#69484)

Arthur Moreira de Deusa1f4e331f15e
diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.ts
index d8a4099d27fb..1b8059baeaae 100644
--- a/nodejs/src/cdp/async-functions/customer_analytics.ts
+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts
@@ -1,8 +1,29 @@
import { DateTime } from 'luxon'
import { CyclotronInvocationQueueParametersFetchSchema } from '~/cdp/schema/cyclotron'
-
-import { registerAsyncFunction } from '../async-function-registry'
+import { captureException } from '~/common/utils/posthog'
+import { Team } from '~/types'
+
+import { AsyncFunctionContext, registerAsyncFunction } from '../async-function-registry'
+
+async function getTeamWithSecretToken(context: AsyncFunctionContext, functionName: string): Promise<Team> {
+ const team = await context.teamManager.getTeam(context.invocation.teamId)
+ if (!team) {
+ throw new Error(`Team ${context.invocation.teamId} not found`)
+ }
+ if (!team.secret_api_token) {
+ const error = new Error(`Team ${context.invocation.teamId} has no secret API token configured`)
+ captureException(error, {
+ tags: {
+ team_id: context.invocation.teamId,
+ function: functionName,
+ template_id: context.invocation.hogFunction.template_id ?? null,
+ },
+ })
+ throw error
+ }
+ return team
+}
registerAsyncFunction('postHogGetAccount', {
execute: async (args, context, result) => {
@@ -13,19 +34,11 @@ registerAsyncFunction('postHogGetAccount', {
throw new Error("[HogFunction] - postHogGetAccount call missing 'external_id' property")
}
- const team = await context.teamManager.getTeam(context.invocation.teamId)
- if (!team) {
- throw new Error(`Team ${context.invocation.teamId} not found`)
- }
- if (!team.secret_api_token) {
- throw new Error(`Team ${context.invocation.teamId} has no secret API token configured`)
- }
+ const team = await getTeamWithSecretToken(context, 'postHogGetAccount')
result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({
type: 'fetch',
- url: `${context.siteUrl}/api/customer_analytics/external/account?external_id=${encodeURIComponent(
- externalId
- )}`,
+ url: `${context.siteUrl}/api/customer_analytics/external/account?external_id=${encodeURIComponent(externalId)}`,
method: 'GET',
headers: { Authorization: `Bearer ${team.secret_api_token}` },
})
@@ -77,13 +90,7 @@ registerAsyncFunction('postHogUpdateAccount', {
throw new Error("[HogFunction] - postHogUpdateAccount call missing 'external_id' property")
}
- const team = await context.teamManager.getTeam(context.invocation.teamId)
- if (!team) {
- throw new Error(`Team ${context.invocation.teamId} not found`)
- }
- if (!team.secret_api_token) {
- throw new Error(`Team ${context.invocation.teamId} has no secret API token configured`)
- }
+ const team = await getTeamWithSecretToken(context, 'postHogUpdateAccount')
result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({
type: 'fetch',
@@ -126,13 +133,7 @@ registerAsyncFunction('postHogSetAccountProperties', {
throw new Error("[HogFunction] - postHogSetAccountProperties call missing 'external_id' property")
}
- const team = await context.teamManager.getTeam(context.invocation.teamId)
- if (!team) {
- throw new Error(`Team ${context.invocation.teamId} not found`)
- }
- if (!team.secret_api_token) {
- throw new Error(`Team ${context.invocation.teamId} has no secret API token configured`)
- }
+ const team = await getTeamWithSecretToken(context, 'postHogSetAccountProperties')
result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({
type: 'fetch',
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.ts
index 733abadb406a..27bcbe73ba89 100644
--- a/nodejs/src/cdp/services/hog-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts
@@ -1039,6 +1039,39 @@ describe('Hog Executor', () => {
expect(result.error).toContain('has no secret API token configured')
})
+ it('captures exception with team_id when secret API token is missing', async () => {
+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({
+ id: 1,
+ secret_api_token: null,
+ } as any)
+
+ const posthogModule = require('~/common/utils/posthog')
+ const captureExceptionSpy = jest.spyOn(posthogModule, 'captureException')
+
+ mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])
+ await executor.execute(createAccountInvocation())
+
+ expect(captureExceptionSpy).toHaveBeenCalledWith(
+ expect.any(Error),
+ expect.objectContaining({ tags: expect.objectContaining({ team_id: 1 }) })
+ )
+ })
+
+ it('does not capture exception when queue is set up successfully', async () => {
+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({
+ id: 1,
+ secret_api_token: 'test-secret-token',
+ } as any)
+
+ const posthogModule = require('~/common/utils/posthog')
+ const captureExceptionSpy = jest.spyOn(posthogModule, 'captureException')
+
+ mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])
+ await executor.execute(createAccountInvocation())
+
+ expect(captureExceptionSpy).not.toHaveBeenCalled()
+ })
+
it('postHogUpdateAccount queues a PATCH with external_id merged into the body', async () => {
jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({
id: 1,
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 24a79c5b71cf..50f11e311fb4 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -388,7 +388,7 @@ def update_external_account(
if tags is not None:
_apply_external_tags(account, tags, tags_mode)
except Exception as e:
- capture_exception(e, {"account_id": str(account.id)})
+ capture_exception(e, {"team_id": team_id, "external_id": external_id, "account_id": str(account.id)})
return contracts.ExternalAccountUpdateResult(error=contracts.ExternalAccountUpdateError.UPDATE_FAILED)
account.refresh_from_db()
@@ -445,7 +445,7 @@ def set_external_account_custom_properties(
error=contracts.ExternalAccountCustomPropertiesError.CONFLICT
)
except Exception as e:
- capture_exception(e, {"external_id": external_id})
+ capture_exception(e, {"team_id": team_id, "external_id": external_id})
return contracts.ExternalAccountCustomPropertiesResult(
error=contracts.ExternalAccountCustomPropertiesError.UPDATE_FAILED
)
diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.py
index dd9cd8b7c424..a2beb7f1cc4e 100644
--- a/products/customer_analytics/backend/test/test_external.py
+++ b/products/customer_analytics/backend/test/test_external.py
@@ -249,6 +249,30 @@ class TestExternalAccountAPI(APIBaseTest):
self.assertEqual(self.account.external_id, "acme-1")
self.assertEqual(self.account.name, "Acme Corp")
+ def test_patch_unexpected_exception_captures_with_team_and_external_id(self):
+ with (
+ patch(
+ "products.customer_analytics.backend.facade.api._apply_external_tags",
+ side_effect=RuntimeError("db exploded"),
+ ),
+ patch("products.customer_analytics.backend.facade.api.capture_exception") as mock_capture,
+ ):
+ self._patch({"external_id": "acme-1", "tags": ["enterprise"]})
+
+ mock_capture.assert_called_once()
+ _exc, context = mock_capture.call_args[0]
+ self.assertEqual(context["team_id"], self.team.id)
+ self.assertEqual(context["external_id"], "acme-1")
+
+ def test_patch_relationship_definition_not_found_does_not_capture(self):
+ with patch("products.customer_analytics.backend.facade.api.capture_exception") as mock_capture:
+ response = self._patch(
+ {"external_id": "acme-1", "relationships": {"AE": {"type": "user", "id": self.user.id}}}
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ mock_capture.assert_not_called()
+
class TestExternalAccountCustomPropertiesAPI(APIBaseTest):
def setUp(self):
@@ -305,3 +329,25 @@ class TestExternalAccountCustomPropertiesAPI(APIBaseTest):
def test_rejects_non_scalar_value(self):
response = self._patch({"external_id": "acme-1", "properties": {str(self.plan.id): {"nested": "object"}}})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_unexpected_exception_captures_with_team_and_external_id(self):
+ with (
+ patch(
+ "products.customer_analytics.backend.logic.custom_property_values.set_account_custom_properties_by_id",
+ side_effect=RuntimeError("db exploded"),
+ ),
+ patch("products.customer_analytics.backend.facade.api.capture_exception") as mock_capture,
+ ):
+ self._patch({"external_id": "acme-1", "properties": {str(self.plan.id): "enterprise"}})
+
+ mock_capture.assert_called_once()
+ _exc, context = mock_capture.call_args[0]
+ self.assertEqual(context["team_id"], self.team.id)
+ self.assertEqual(context["external_id"], "acme-1")
+
+ def test_unknown_definition_does_not_capture(self):
+ with patch("products.customer_analytics.backend.facade.api.capture_exception") as mock_capture:
+ response = self._patch({"external_id": "acme-1", "properties": {str(uuid4()): "x"}})
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ mock_capture.assert_not_called()