Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. πŸ”₯

fix(api): address CodeRabbit review on first-surface tracking

rramprakash1a623da6243b
diff --git a/apps/api/src/services/logging/log_job.ts b/apps/api/src/services/logging/log_job.ts
index 5b56778ca..ecc78903c 100644
--- a/apps/api/src/services/logging/log_job.ts
+++ b/apps/api/src/services/logging/log_job.ts
@@ -186,13 +186,16 @@ export async function logRequest(request: LoggedRequest) {
// Emit a one-time PostHog milestone the first time this team uses each
// surface (playground / sdk / mcp / cli / api / ...). Fire-and-forget.
- trackFirstSurfaceUse({
- teamId: request.team_id,
- origin: request.origin,
- kind: request.kind,
- apiVersion: request.api_version,
- apiKeyId: request.api_key_id,
- });
+ // Skip zero-data-retention requests β€” don't send their metadata to PostHog.
+ if (!request.zeroDataRetention) {
+ trackFirstSurfaceUse({
+ teamId: request.team_id,
+ origin: request.origin,
+ kind: request.kind,
+ apiVersion: request.api_version,
+ apiKeyId: request.api_key_id,
+ });
+ }
// Sanitize user-provided fields (most likely sources of null bytes)
const sanitizedOrigin = sanitizeString(request.origin);
diff --git a/apps/api/src/services/posthog.ts b/apps/api/src/services/posthog.ts
index 212a838ac..1558446fd 100644
--- a/apps/api/src/services/posthog.ts
+++ b/apps/api/src/services/posthog.ts
@@ -1,4 +1,4 @@
-import { eq } from "drizzle-orm";
+import { and, eq } from "drizzle-orm";
import { redisEvictConnection } from "./redis";
import { dbRr } from "../db/connection";
import * as schema from "../db/schema";
@@ -90,7 +90,9 @@ async function resolveDistinctId(
.select({ email: schema.users.email })
.from(schema.api_keys)
.leftJoin(schema.users, eq(schema.users.id, schema.api_keys.owner_id))
- .where(eq(schema.api_keys.id, apiKeyId))
+ // Scope to the team so a stale/mismatched apiKeyId can't attribute this
+ // team's milestone to another team's owner email β€” falls back to teamId.
+ .where(and(eq(schema.api_keys.id, apiKeyId), eq(schema.api_keys.team_id, teamId)))
.limit(1);
return rows[0]?.email || teamId;
} catch {
@@ -123,6 +125,11 @@ export function trackFirstSurfaceUse(args: {
}): void {
const { teamId, origin, kind, apiVersion, apiKeyId } = args;
+ // No PostHog key β†’ capture is a no-op. Bail BEFORE the Redis SETNX so we don't
+ // burn the dedup marker without emitting (which would lose the milestone for
+ // good once PostHog is enabled).
+ if (!POSTHOG_API_KEY) return;
+
// Skip anonymous / preview traffic β€” not a real team milestone.
if (!teamId || teamId === "preview" || teamId.startsWith("preview_")) return;