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(product-empty-states): stop retrying a dead project 404 (#93895)

posthog[bot]8144176f5d32
diff --git a/frontend/src/lib/api-error.test.ts b/frontend/src/lib/api-error.test.ts
index fc500316e5d2..eb3a22107198 100644
--- a/frontend/src/lib/api-error.test.ts
+++ b/frontend/src/lib/api-error.test.ts
@@ -1,4 +1,10 @@
-import { ApiError, NetworkError, isTransientServerError, shouldReportApiFailure } from './api-error'
+import {
+ ApiError,
+ NetworkError,
+ isScopeNotFoundError,
+ isTransientServerError,
+ shouldReportApiFailure,
+} from './api-error'
describe('api-error', () => {
describe('ApiError.fromResponse', () => {
@@ -103,6 +109,11 @@ describe('api-error', () => {
// degrades excuses one, through `isUnavailableEndpointError`.
['a 404', { status: 404 }, true],
['a 405', { status: 405 }, true],
+ // The exception is a 404 that names a dead scope: retrying it can never succeed, so it
+ // is excused globally rather than per caller.
+ ['a project-not-found 404', { status: 404, detail: 'Project not found.' }, false],
+ ['an organization-not-found 404', { status: 404, detail: 'Organization not found.' }, false],
+ ['a 404 for some other missing resource', { status: 404, detail: 'Not found.' }, true],
// A request the browser never sent. Nothing of ours failed, and grouping is stack-based,
// so reporting these opens one issue per loader that met the same connectivity blip.
['a Chromium fetch failure', new TypeError('Failed to fetch'), false],
@@ -139,4 +150,25 @@ describe('api-error', () => {
expect(shouldReportApiFailure(error)).toBe(false)
})
})
+
+ describe('isScopeNotFoundError', () => {
+ it.each([
+ ['a project-not-found 404 via detail', { status: 404, detail: 'Project not found.' }, true],
+ ['an org-not-found 404 via detail', { status: 404, detail: 'Organization not found.' }, true],
+ ['a 404 with the detail nested under data', { status: 404, data: { detail: 'Project not found.' } }, true],
+ ['a 404 for another resource', { status: 404, detail: 'Not found.' }, false],
+ ['a 404 with no detail', { status: 404 }, false],
+ ['a 403 that names the project', { status: 403, detail: 'Project not found.' }, false],
+ ['null', null, false],
+ ])('decides whether %s is a scope-not-found error', (_, error, expected) => {
+ expect(isScopeNotFoundError(error)).toBe(expected)
+ })
+
+ it('reads the detail off a constructed ApiError', async () => {
+ const error = await ApiError.fromResponse(
+ new Response(JSON.stringify({ detail: 'Project not found.' }), { status: 404 })
+ )
+ expect(isScopeNotFoundError(error)).toBe(true)
+ })
+ })
})
diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.ts
index aa75b33f3483..222dedb8f397 100644
--- a/frontend/src/lib/api-error.ts
+++ b/frontend/src/lib/api-error.ts
@@ -55,6 +55,32 @@ export function isUnavailableEndpointError(error: unknown): boolean {
return status === 404 || status === 405
}
+/**
+ * The DRF `detail` values `posthog/api/routing.py` raises when a URL's scope no longer resolves.
+ * This is user-facing copy that the backend plans to rename (`Project` to `Environment`), so the
+ * match is fragile: keep this set in sync with those raise sites, which point back here.
+ */
+const SCOPE_NOT_FOUND_DETAILS: ReadonlySet<string> = new Set(['Project not found.', 'Organization not found.'])
+
+/**
+ * A 404 raised because the project or organization in the URL no longer resolves - it was deleted,
+ * or the user lost access to it. Every endpoint under that scope answers the same way, so the
+ * failure describes the URL the user sits on rather than the request that hit it, and repeating
+ * that request cannot make it succeed.
+ *
+ * Narrower than `isUnavailableEndpointError` on purpose, and unlike that one it is safe to excuse
+ * globally: a dead scope is read off the `detail`, so a 404 from a resource the app expects to
+ * exist still reports.
+ */
+export function isScopeNotFoundError(error: unknown): boolean {
+ const failure = error as { status?: unknown; detail?: unknown; data?: { detail?: unknown } } | null
+ if (failure?.status !== 404) {
+ return false
+ }
+ const detail = failure.detail ?? failure.data?.detail
+ return typeof detail === 'string' && SCOPE_NOT_FOUND_DETAILS.has(detail)
+}
+
/** The 403 gates `apiStatusLogic` recovers from, keyed by the DRF `code` the backend sends. */
const HANDLED_AUTH_GATE_CODES: ReadonlySet<string> = new Set([
'two_factor_setup_required',
@@ -123,6 +149,9 @@ export function isBrowserNetworkFailure(error: unknown): boolean {
* - 403 `permission_denied` — the sceneLogic gates render the AccessDenied scene.
* - 403 auth gates — `apiStatusLogic` opens 2FA setup, re-verification, or a re-auth prompt.
* - 409 carrying a `change_request_id` — the approvals UI shows the change request it created.
+ * - 404 `Project not found.` / `Organization not found.` — the scope in the URL is gone, so every
+ * request under it fails the same way. The scene routing takes the user off that URL, and until
+ * it does, a poll on the dead scope would otherwise file one exception per tick.
* - 502/503/504 — the gateway couldn't reach the backend, so application code is not at fault.
*
* Left unreported for a second reason, that there is nothing to fix:
@@ -156,6 +185,9 @@ export function shouldReportApiFailure(error: unknown): boolean {
if (status === 401 || isTransientGatewayStatus(status)) {
return false
}
+ if (isScopeNotFoundError(failure)) {
+ return false
+ }
if (isAccessDeniedError(failure)) {
return false
}
diff --git a/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.test.ts b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.test.ts
index 2ef30087281b..35d19c78601a 100644
--- a/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.test.ts
+++ b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.test.ts
@@ -2,6 +2,7 @@ import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
+import { ApiError } from 'lib/api-error'
import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
import { teamLogic } from 'scenes/teamLogic'
@@ -97,6 +98,49 @@ describe('createSetupDetectionLogic', () => {
expect(detect).toHaveBeenCalledTimes(2)
})
+ it('stops polling once a request 404s on a deleted or inaccessible project', async () => {
+ jest.useFakeTimers()
+ const detect = jest
+ .fn<Promise<ProductSetupStatus>, []>()
+ .mockResolvedValueOnce('needs-setup')
+ .mockRejectedValue(new ApiError('Project not found.', 404, undefined, { detail: 'Project not found.' }))
+ const logic = buildLogic(detect, 1000)
+ logic.mount()
+ await flushMicrotasks()
+ expect(detect).toHaveBeenCalledTimes(1)
+
+ // The first poll tick 404s, which disposes the poll...
+ jest.advanceTimersByTime(1000)
+ await flushMicrotasks()
+ expect(detect).toHaveBeenCalledTimes(2)
+
+ // ...so no later tick fires another doomed request.
+ jest.advanceTimersByTime(5000)
+ await flushMicrotasks()
+ expect(detect).toHaveBeenCalledTimes(2)
+ })
+
+ it('keeps polling on a generic failure that may recover', async () => {
+ jest.useFakeTimers()
+ const detect = jest
+ .fn<Promise<ProductSetupStatus>, []>()
+ .mockResolvedValueOnce('needs-setup')
+ .mockRejectedValue(new Error('transient blip'))
+ const logic = buildLogic(detect, 1000)
+ logic.mount()
+ await flushMicrotasks()
+ expect(detect).toHaveBeenCalledTimes(1)
+
+ jest.advanceTimersByTime(1000)
+ await flushMicrotasks()
+ expect(detect).toHaveBeenCalledTimes(2)
+
+ // A non-404 failure leaves the poll running.
+ jest.advanceTimersByTime(1000)
+ await flushMicrotasks()
+ expect(detect).toHaveBeenCalledTimes(3)
+ })
+
it('re-detects when a recheck action fires', async () => {
const detect = jest
.fn<Promise<ProductSetupStatus>, []>()
diff --git a/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts
index f57aea76dd56..a3475bb1ae58 100644
--- a/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts
+++ b/frontend/src/lib/components/ProductEmptyState/setupDetectionLogic.ts
@@ -1,6 +1,7 @@
import { BreakPointFunction, LogicWrapper, MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'
import { loaders } from 'kea-loaders'
+import { isScopeNotFoundError } from 'lib/api-error'
import { projectLogic } from 'scenes/projectLogic'
import { teamLogic } from 'scenes/teamLogic'
@@ -66,7 +67,7 @@ export interface SetupDetectionActions {
detectedStatus: ProductSetupStatus | null,
payload?: void
) => { detectedStatus: ProductSetupStatus | null }
- detectStatusFailure: (error: string, errorObject?: unknown) => { error: string }
+ detectStatusFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }
setDetectedStatus: (status: ProductSetupStatus) => { status: ProductSetupStatus }
}
@@ -163,13 +164,19 @@ export function createSetupDetectionLogic(options: SetupDetectionLogicOptions):
}
}
},
- detectStatusFailure: () => {
+ detectStatusFailure: ({ errorObject }) => {
// Never strand the gate on its spinner: if nothing (preload included)
// has answered yet, fail open to the real scene. The poll keeps
// retrying, and a failure never downgrades an existing answer.
if (values.setupStatus === 'loading') {
actions.setDetectedStatus('unknown')
}
+ // A deleted project (or one the user lost access to) 404s every request
+ // under it, so retrying only files one error per tick. Stop the poll and
+ // leave the scene routing to move the user off the dead URL.
+ if (isScopeNotFoundError(errorObject)) {
+ cache.disposables.dispose('poll')
+ }
},
[projectLogic.actionTypes.loadCurrentProjectSuccess]: () => {
// Covers non-polling products mounted before bootstrap settled.
diff --git a/posthog/api/routing.py b/posthog/api/routing.py
index d30a7d3f1a71..5456cea98c3d 100644
--- a/posthog/api/routing.py
+++ b/posthog/api/routing.py
@@ -474,7 +474,10 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):
team = Team.objects.select_related("organization").get(id=self.team_id)
except (Team.DoesNotExist, ValueError):
raise NotFound(
- detail="Project not found." # TODO: "Environment" instead of "Project" when project environments are rolled out
+ # TODO: "Environment" instead of "Project" when project environments are rolled out.
+ # Keep in sync with SCOPE_NOT_FOUND_DETAILS in frontend/src/lib/api-error.ts, which
+ # matches this exact text to stop dead-scope polling and to skip error reports.
+ detail="Project not found."
)
tag_queries(**get_team_query_tags(team))
@@ -604,7 +607,9 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):
current_team = self.request.user.team
if current_team is None:
raise NotFound(
- "Project not found." # TODO: "Environment" instead of "Project" when project environments are rolled out
+ # TODO: "Environment" instead of "Project" when project environments are rolled out.
+ # Keep in sync with SCOPE_NOT_FOUND_DETAILS in frontend/src/lib/api-error.ts.
+ "Project not found."
)
query_value = current_team.id
elif query_lookup == "project_id":
@@ -621,7 +626,9 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):
try:
query_value = team_from_request.id if team_from_request else int(query_value)
except ValueError:
- raise NotFound("Project not found.") # TODO: "Environment"
+ # TODO: "Environment" instead of "Project" when project environments are rolled out.
+ # Keep in sync with SCOPE_NOT_FOUND_DETAILS in frontend/src/lib/api-error.ts.
+ raise NotFound("Project not found.")
elif query_lookup == "project_id":
try:
query_value = team_from_request.project_id if team_from_request else int(query_value)