diff --git a/server/src/__tests__/cloud-runtime-identity.test.ts b/server/src/__tests__/cloud-runtime-identity.test.ts index be32714d0a9..438fff1987d 100644 --- a/server/src/__tests__/cloud-runtime-identity.test.ts +++ b/server/src/__tests__/cloud-runtime-identity.test.ts @@ -21,6 +21,7 @@ import { cloudRuntimeIdentityMiddleware } from "../middleware/cloud-runtime-iden import { idleAdmissionMiddleware, trackIdleRequestHandlers } from "../middleware/idle-admission.js"; import { idleWorkSnapshot } from "../services/task-admission.js"; import { healthRoutes } from "../routes/health.js"; +import { createPostHogDirectTransport, type PostHogNodeClient } from "../services/posthog-direct/transport.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, @@ -164,6 +165,140 @@ describeEmbeddedPostgres("Cloud runtime identity", () => { }); }); + it("re-identifies the PostHog workspace group with the claimed slug and host", async () => { + const groupIdentifies: Array[0]> = []; + const flush = vi.fn(async () => {}); + const fakeClient: PostHogNodeClient = { + capture: () => {}, + groupIdentify: (message) => void groupIdentifies.push(message), + flush, + shutdown: async () => {}, + }; + const transport = createPostHogDirectTransport( + { + token: "phc_test", + host: "http://127.0.0.1:1", + environment: "staging", + stackId: STACK_ID, + directEnabled: true, + browserEnabled: false, + replayEnabled: false, + cloudTrialInferenceEnabled: false, + }, + { factory: async () => fakeClient }, + ); + + try { + await transport.announceWorkspace({ + stackSlug: "pool-123", + primaryHost: "pool-123.staging.paperclip.app", + app: "paperclip", + schemaVersion: "1", + version: "1.0.0", + installId: "install-1", + installHash: "hash-1", + }); + + expect(groupIdentifies).toHaveLength(1); + expect(groupIdentifies[0]?.properties).toMatchObject({ + stack_slug: "pool-123", + primary_host: "pool-123.staging.paperclip.app", + }); + + await applyCloudRuntimeIdentityAssertion({ + db, + compactJws: assertion(), + now: NOW, + }); + + await vi.waitFor(() => { + expect(groupIdentifies).toHaveLength(2); + }); + expect(groupIdentifies[1]).toMatchObject({ + groupType: "workspace", + groupKey: STACK_ID, + properties: { + stack_slug: "gonzo", + primary_host: "gonzo.staging.paperclip.app", + environment: "staging", + }, + }); + expect(flush).toHaveBeenCalledTimes(2); + + // Idempotent retry of the same claim does not spam duplicate groupIdentify calls. + await applyCloudRuntimeIdentityAssertion({ + db, + compactJws: assertion(), + now: NOW, + }); + await new Promise((resolve) => setTimeout(resolve, 25)); + expect(groupIdentifies).toHaveLength(2); + } finally { + await transport.shutdown(); + } + }); + + it("uses the claimed slug and host when the claim arrives while PostHog client loading is in flight", async () => { + const groupIdentifies: Array[0]> = []; + const fakeClient: PostHogNodeClient = { + capture: () => {}, + groupIdentify: (message) => void groupIdentifies.push(message), + flush: async () => {}, + shutdown: async () => {}, + }; + let resolveFactory!: (client: PostHogNodeClient) => void; + const factoryPromise = new Promise((resolve) => { + resolveFactory = resolve; + }); + const transport = createPostHogDirectTransport( + { + token: "phc_test", + host: "http://127.0.0.1:1", + environment: "staging", + stackId: STACK_ID, + directEnabled: true, + browserEnabled: false, + replayEnabled: false, + cloudTrialInferenceEnabled: false, + }, + { factory: () => factoryPromise }, + ); + + try { + const announcePromise = transport.announceWorkspace({ + stackSlug: "pool-123", + primaryHost: "pool-123.staging.paperclip.app", + app: "paperclip", + schemaVersion: "1", + version: "1.0.0", + installId: "install-1", + installHash: "hash-1", + }); + + await applyCloudRuntimeIdentityAssertion({ + db, + compactJws: assertion(), + now: NOW, + }); + + resolveFactory(fakeClient); + await announcePromise; + + expect(groupIdentifies).toHaveLength(1); + expect(groupIdentifies[0]).toMatchObject({ + groupType: "workspace", + groupKey: STACK_ID, + properties: { + stack_slug: "gonzo", + primary_host: "gonzo.staging.paperclip.app", + environment: "staging", + }, + }); + } finally { + await transport.shutdown(); + } + }); + it("applies the assertion on the existing health request and acknowledges the exact origin", async () => { const requestTime = Math.floor(Date.now() / 1000); const app = express(); diff --git a/server/src/services/cloud-runtime-identity.ts b/server/src/services/cloud-runtime-identity.ts index 874419c0063..43e3f5134a6 100644 --- a/server/src/services/cloud-runtime-identity.ts +++ b/server/src/services/cloud-runtime-identity.ts @@ -51,6 +51,26 @@ export type RuntimeIdentityClaims = { let initialized = false; let startupOrigin: string | null = null; let currentIdentity: CloudRuntimeIdentitySnapshot | null = null; +const identityListeners = new Set<(identity: CloudRuntimeIdentitySnapshot) => void>(); + +function notifyIdentityListeners(identity: CloudRuntimeIdentitySnapshot) { + for (const listener of identityListeners) { + try { + listener({ ...identity }); + } catch { + // Best-effort listeners (such as telemetry) must never disrupt identity claims. + } + } +} + +export function onCloudRuntimeIdentityChange( + listener: (identity: CloudRuntimeIdentitySnapshot) => void, +): () => void { + identityListeners.add(listener); + return () => { + identityListeners.delete(listener); + }; +} function nonEmpty(value: string | undefined): string | null { const normalized = value?.trim(); @@ -193,6 +213,7 @@ export async function initializeCloudRuntimeIdentity( assertPersistedIdentityMatchesStack(row, env); currentIdentity = snapshot(row); applyCompatibilityEnvironment(currentIdentity, env); + notifyIdentityListeners(currentIdentity); return currentIdentity; } @@ -418,8 +439,16 @@ export async function applyCloudRuntimeIdentityAssertion(input: { return durable; }); + const previousIdentity = currentIdentity; currentIdentity = snapshot(row); applyCompatibilityEnvironment(currentIdentity, env); + if ( + !previousIdentity || + previousIdentity.stackSlug !== currentIdentity.stackSlug || + previousIdentity.canonicalOrigin !== currentIdentity.canonicalOrigin + ) { + notifyIdentityListeners(currentIdentity); + } return { ...currentIdentity }; } @@ -428,6 +457,7 @@ export function resetCloudRuntimeIdentityForTests() { initialized = false; startupOrigin = null; currentIdentity = null; + identityListeners.clear(); } // --------------------------------------------------------------------------- diff --git a/server/src/services/posthog-direct/transport.ts b/server/src/services/posthog-direct/transport.ts index 54df09494c7..23e1b3a155b 100644 --- a/server/src/services/posthog-direct/transport.ts +++ b/server/src/services/posthog-direct/transport.ts @@ -11,6 +11,7 @@ import { getResolvedCloudTrialInferenceEnabled, onCloudTrialInferenceCohortChange, } from "../cloud-posthog-cohort.js"; +import { onCloudRuntimeIdentityChange } from "../cloud-runtime-identity.js"; import { buildCloudDirectEvent, buildPostHogDirectEvent, @@ -103,6 +104,8 @@ export function createPostHogDirectTransport( let clientPromise: Promise | null = null; let pendingAnnouncement: { startup: WorkspaceStartup; occurredAt: string } | null = null; let announcedCohort: boolean | null = null; + let announcedIdentity: { stackSlug: string | null; primaryHost: string | null } | null = null; + let latestIdentity: { stackSlug: string; primaryHost: string } | null = null; let explicitCloudTrialInferenceEnabled: boolean | null = null; const effectiveCloudTrialInferenceEnabled = (): boolean => @@ -136,6 +139,59 @@ export function createPostHogDirectTransport( syncWorkspaceGroupCohort(enabled); }); + const identifyWorkspaceGroup = ( + client: PostHogNodeClient, + activeConfig: CloudPostHogConfig, + identity: { stackSlug: string | null; primaryHost: string | null }, + ) => { + client.groupIdentify({ + groupType: POSTHOG_WORKSPACE_GROUP_TYPE, + groupKey: activeConfig.stackId, + disableGeoip: true, + properties: { + stack_slug: identity.stackSlug, + primary_host: identity.primaryHost, + environment: activeConfig.environment, + cloud_trial_inference_enabled: activeConfig.cloudTrialInferenceEnabled, + cloud_trial_inference_cohort: cloudTrialInferenceCohort(activeConfig.cloudTrialInferenceEnabled), + }, + }); + }; + + const syncWorkspaceGroupIdentity = (stackId: string, stackSlug: string, primaryHost: string) => { + if (stackId !== config.stackId) return; + // Always record the latest claimed identity so an in-flight or retried + // startup announcement uses it instead of stale warm-pool values. + latestIdentity = { stackSlug, primaryHost }; + if ( + !announcedIdentity || + (announcedIdentity.stackSlug === stackSlug && announcedIdentity.primaryHost === primaryHost) || + !clientPromise + ) { + return; + } + announcedIdentity = { stackSlug, primaryHost }; + const activeConfig = currentConfig(); + void clientPromise + .then(async (client) => { + identifyWorkspaceGroup(client, activeConfig, { stackSlug, primaryHost }); + await client.flush(); + }) + .catch(() => { + // Best-effort analytics must never interrupt Cloud runtime identity claims. + }); + }; + + const unsubscribeIdentityChange = onCloudRuntimeIdentityChange((identity) => { + let primaryHost: string; + try { + primaryHost = new URL(identity.canonicalOrigin).hostname; + } catch { + return; + } + syncWorkspaceGroupIdentity(identity.stackId, identity.stackSlug, primaryHost); + }); + const currentConfig = (): CloudPostHogConfig => { const enabled = effectiveCloudTrialInferenceEnabled(); return enabled === config.cloudTrialInferenceEnabled @@ -175,19 +231,13 @@ export function createPostHogDirectTransport( { startup, occurredAt }: { startup: WorkspaceStartup; occurredAt: string }, ) { const activeConfig = currentConfig(); + const identity = latestIdentity ?? { + stackSlug: startup.stackSlug, + primaryHost: startup.primaryHost, + }; announcedCohort = activeConfig.cloudTrialInferenceEnabled; - client.groupIdentify({ - groupType: POSTHOG_WORKSPACE_GROUP_TYPE, - groupKey: activeConfig.stackId, - disableGeoip: true, - properties: { - stack_slug: startup.stackSlug, - primary_host: startup.primaryHost, - environment: activeConfig.environment, - cloud_trial_inference_enabled: activeConfig.cloudTrialInferenceEnabled, - cloud_trial_inference_cohort: cloudTrialInferenceCohort(activeConfig.cloudTrialInferenceEnabled), - }, - }); + announcedIdentity = { ...identity }; + identifyWorkspaceGroup(client, activeConfig, identity); capture( client, buildWorkspaceStartedEvent( @@ -312,6 +362,7 @@ export function createPostHogDirectTransport( async shutdown(): Promise { unsubscribeCohortChange(); + unsubscribeIdentityChange(); if (!clientPromise) return; const client = await clientPromise.catch(() => null); if (!client) return;