From e32b1b057f4a6cb03bddfc3938c08e922b4a0620 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:37:08 +0000 Subject: [PATCH] fix(telemetry): re-identify PostHog workspace group on Cloud stack claim (#23389) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Managed Paperclip Cloud stacks send direct server telemetry to PostHog and identify each `workspace` group with `stack_slug` and `primary_host` > - Warm-pool stacks boot before a user claims them, so startup `groupIdentify` records the placeholder `pool-` slug and host > - When a user claims a warm-pool stack, `applyCloudRuntimeIdentityAssertion` transitions the stack identity in place without restarting the process, so PostHog group properties stay stuck on `pool-` until a later restart > - This pull request adds an `onCloudRuntimeIdentityChange` listener in `cloud-runtime-identity` and subscribes the PostHog direct transport to re-send `groupIdentify` with the claimed `stack_slug` and `primary_host` > - The benefit is that PostHog workspace analytics and live dashboards immediately reflect the real claimed stack name and host for both browser and server-side events ## Linked Issues or Issue Description **What happened?** When a warm-pool Cloud stack boots, `resolveDirectTransport` announces the workspace to PostHog with its placeholder `pool-` `stack_slug` and `primary_host`. After a user claims the stack via `applyCloudRuntimeIdentityAssertion`, the server updates its runtime identity in place without restarting, so PostHog's `workspace` group keeps the stale `pool-` `stack_slug` and `primary_host` until the container eventually restarts. **Expected behavior** When a Cloud stack's runtime identity transitions from a warm-pool placeholder to its claimed slug and canonical origin, the PostHog direct transport immediately calls `groupIdentify` with the updated `stack_slug` and `primary_host` and flushes. **Steps to reproduce** 1. Start a Paperclip Cloud warm-pool instance with `PAPERCLIP_POSTHOG_PROJECT_TOKEN` and `PAPERCLIP_POSTHOG_ENVIRONMENT` configured and `PAPERCLIP_STACK_SLUG=pool-123`. 2. Apply a signed Cloud runtime identity assertion claiming the stack as `gonzo` (`https://gonzo.staging.paperclip.app`). 3. Observe PostHog `workspace` group properties for the stack: before this fix, `stack_slug` and `primary_host` remain `pool-123` / `pool-123.staging.paperclip.app` until process restart. **Paperclip version or commit** `36c2ad39c8` (`origin/master`) **Deployment mode** Other (Paperclip Cloud managed stack) ## What Changed - Added `onCloudRuntimeIdentityChange` listener registration and best-effort notification in `server/src/services/cloud-runtime-identity.ts` when `applyCloudRuntimeIdentityAssertion` changes the runtime identity (or `initializeCloudRuntimeIdentity` restores one), and cleared listeners in `resetCloudRuntimeIdentityForTests`. - Subscribed `createPostHogDirectTransport` in `server/src/services/posthog-direct/transport.ts` to `onCloudRuntimeIdentityChange` so matching `stackId` claims update any queued `pendingAnnouncement` or immediately send and flush an updated `groupIdentify` with the claimed `stack_slug` and `primary_host`; unsubscribed on `shutdown()`. - Added a regression test in `server/src/__tests__/cloud-runtime-identity.test.ts` verifying initial `pool-*` announcement, immediate `groupIdentify` + flush on claim, and no duplicate calls on idempotent claim retry. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/cloud-runtime-identity.test.ts src/__tests__/posthog-direct-transport.test.ts src/__tests__/posthog-direct-telemetry.test.ts` — 38/38 tests passed. - `pnpm --filter @paperclipai/server typecheck` — passed. ## Risks - Low risk. Listener notifications are wrapped in `try/catch` and the PostHog `groupIdentify` + `flush` call is fire-and-forget with error suppression, matching the existing `onCloudTrialInferenceCohortChange` pattern so telemetry failures can never disrupt runtime identity claims. ## Model Used - Google Gemini (Antigravity agent with tool use, file editing, and local test execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- .../__tests__/cloud-runtime-identity.test.ts | 135 ++++++++++++++++++ server/src/services/cloud-runtime-identity.ts | 30 ++++ .../src/services/posthog-direct/transport.ts | 75 ++++++++-- 3 files changed, 228 insertions(+), 12 deletions(-) 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;