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(embedding-worker): return 400/403 from ad hoc embedding endpoint (#98560)

Oliver Browne0f6d25d4e735
diff --git a/posthog/api/embedding_worker.py b/posthog/api/embedding_worker.py
index 3713ba9b4092..c47b985db060 100644
--- a/posthog/api/embedding_worker.py
+++ b/posthog/api/embedding_worker.py
@@ -64,12 +64,15 @@ def _build_embedding_payload(team: Team, content: str, model: str | None, no_tru
def _raise_for_embedding_response(response) -> None:
"""raise_for_status() with a clearer hint when the worker rejects ad-hoc requests
because the organization has not opted into AI data processing — a common dev
- foot-gun where the underlying 403 body is hidden behind a generic HTTPStatusError.
+ foot-gun otherwise hidden behind a generic HTTPStatusError.
+
+ The worker returns 403 for the opt-in gate and nothing else, and sends no body
+ with it, so the status alone identifies the case.
"""
- if response.status_code == 403 and "ai" in response.text.lower():
+ if response.status_code == 403:
raise httpx.HTTPStatusError(
- f"Embedding worker returned 403: {response.text}. "
- "Likely the organization has not opted into AI data processing — "
+ "Embedding worker returned 403. "
+ "The organization has not opted into AI data processing — "
"set Organization.is_ai_data_processing_approved=True (Settings > AI, "
"or via SQL in local dev) and retry.",
request=response.request,
diff --git a/posthog/api/test/test_embedding_worker.py b/posthog/api/test/test_embedding_worker.py
index 68acc733d241..87fee414e76d 100644
--- a/posthog/api/test/test_embedding_worker.py
+++ b/posthog/api/test/test_embedding_worker.py
@@ -1,8 +1,11 @@
from datetime import UTC, datetime
+import pytest
from unittest.mock import MagicMock, patch
-from posthog.api.embedding_worker import DocumentKey, get_recently_seen_documents
+import httpx
+
+from posthog.api.embedding_worker import DocumentKey, _raise_for_embedding_response, get_recently_seen_documents
def _doc(document_id: str, product: str = "signals") -> DocumentKey:
@@ -67,3 +70,29 @@ class TestRecentlySeenLookup:
def test_empty_input_makes_no_request(self, mock_requests):
assert get_recently_seen_documents([], team_id=1) == {}
mock_requests.post.assert_not_called()
+
+
+class TestRaiseForEmbeddingResponse:
+ def test_bodyless_403_explains_the_ai_opt_in_gate(self):
+ # The worker sends a bare status with no body, so a helper that looked for
+ # explanatory text in the response would never recognise the opt-in gate.
+ response = MagicMock(status_code=403, text="")
+
+ with pytest.raises(httpx.HTTPStatusError, match="not opted into AI data processing"):
+ _raise_for_embedding_response(response)
+
+ response.raise_for_status.assert_not_called()
+
+ def test_other_errors_fall_through_to_raise_for_status(self):
+ response = MagicMock(status_code=500, text="")
+
+ _raise_for_embedding_response(response)
+
+ response.raise_for_status.assert_called_once()
+
+ def test_success_is_passed_through(self):
+ response = MagicMock(status_code=200, text="")
+
+ _raise_for_embedding_response(response)
+
+ response.raise_for_status.assert_called_once()
diff --git a/rust/embedding-worker/src/ad_hoc.rs b/rust/embedding-worker/src/ad_hoc.rs
index 577c988ba054..a8bd1a68b29b 100644
--- a/rust/embedding-worker/src/ad_hoc.rs
+++ b/rust/embedding-worker/src/ad_hoc.rs
@@ -1,12 +1,13 @@
use std::sync::Arc;
-use anyhow::Result;
+use axum::{extract::Json, http::StatusCode};
use common_types::embedding::EmbeddingModel;
use serde::{Deserialize, Serialize};
+use tracing::{error, warn};
use crate::{
app_context::AppContext, generate_embedding, metrics_utils::RequestLabels,
- organization::apply_ai_opt_in,
+ organization::apply_ai_opt_in, CL100K_ENCODER,
};
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -26,47 +27,133 @@ pub struct AdHocEmbeddingResponse {
pub did_truncate: bool,
}
+/// Callers retry 5xx and give up on 4xx, so the status code has to separate the two:
+/// an opted-out organization and over-long content are permanent and never succeed on
+/// retry, while anything else here is transient enough to be worth retrying.
pub async fn handle_ad_hoc_request(
context: Arc<AppContext>,
request: AdHocEmbeddingRequest,
-) -> Result<AdHocEmbeddingResponse> {
+) -> Result<Json<AdHocEmbeddingResponse>, StatusCode> {
let team_id = request.team_id;
- let Some(request) = apply_ai_opt_in(&context, request, team_id).await? else {
- return Err(anyhow::anyhow!("Organization not opted in to ai features"));
+ let request = match apply_ai_opt_in(&context, request, team_id).await {
+ Ok(Some(request)) => request,
+ Ok(None) => {
+ warn!("Ad hoc embedding request for team {team_id} rejected: organization not opted in to ai features");
+ return Err(StatusCode::FORBIDDEN);
+ }
+ Err(e) => {
+ error!(
+ "Ad hoc embedding request for team {team_id} failed to resolve organization: {:?}",
+ e
+ );
+ return Err(StatusCode::INTERNAL_SERVER_ERROR);
+ }
};
let would_truncate = check_would_truncate(&request.content, &request.model);
if would_truncate && !request.no_truncate {
- return Err(anyhow::anyhow!("Content too long"));
+ warn!("Ad hoc embedding request for team {team_id} rejected: content too long");
+ return Err(StatusCode::BAD_REQUEST);
}
- let (embedding, token_count) = generate_embedding(
+ let (embedding, token_count) = match generate_embedding(
context.clone(),
request.model,
&request.content,
&RequestLabels::from(&request),
)
- .await?;
+ .await
+ {
+ Ok(result) => result,
+ Err(e) => {
+ error!(
+ "Ad hoc embedding request for team {team_id} failed: {:?}",
+ e
+ );
+ return Err(StatusCode::INTERNAL_SERVER_ERROR);
+ }
+ };
- Ok(AdHocEmbeddingResponse {
+ Ok(Json(AdHocEmbeddingResponse {
embedding,
tokens_used: token_count,
did_truncate: would_truncate,
- })
+ }))
}
pub fn check_would_truncate(content: &str, model: &EmbeddingModel) -> bool {
match model {
EmbeddingModel::OpenAITextEmbeddingSmall | EmbeddingModel::OpenAITextEmbeddingLarge => {
- let encoder = tiktoken_rs::cl100k_base().expect("We can construct the encoder");
- let tokens: Vec<_> = encoder
- .encode_with_special_tokens(content)
- .into_iter()
- .take(model.model_input_window())
- .collect();
- let token_count = tokens.len();
+ // Count every token: capping the count at the input window first would make the
+ // comparison below unsatisfiable.
+ let token_count = CL100K_ENCODER.encode_with_special_tokens(content).len();
token_count > model.model_input_window()
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // Build text of an exact token length by decoding that many tokens off a longer
+ // stream. Repeated whole words keep every cut on a token boundary, so the result
+ // re-encodes to the same count.
+ fn content_with_tokens(count: usize) -> String {
+ let encoder = &*CL100K_ENCODER;
+ let stream = "word ".repeat(count + 16);
+ let tokens: Vec<_> = encoder
+ .encode_with_special_tokens(&stream)
+ .into_iter()
+ .take(count)
+ .collect();
+ let content = encoder.decode(tokens).expect("fixture decodes cleanly");
+ assert_eq!(
+ encoder.encode_with_special_tokens(&content).len(),
+ count,
+ "fixture should hold exactly {count} tokens"
+ );
+ content
+ }
+
+ #[test]
+ fn short_content_does_not_truncate() {
+ assert!(!check_would_truncate(
+ "hello world",
+ &EmbeddingModel::OpenAITextEmbeddingSmall
+ ));
+ }
+
+ #[test]
+ fn content_over_the_input_window_truncates() {
+ // The check used to take() the input window's worth of tokens before comparing the
+ // count against that same window, so it could never report a truncation.
+ for model in [
+ EmbeddingModel::OpenAITextEmbeddingSmall,
+ EmbeddingModel::OpenAITextEmbeddingLarge,
+ ] {
+ let content = content_with_tokens(model.model_input_window() + 1);
+ assert!(
+ check_would_truncate(&content, &model),
+ "{model:?} should truncate one token past its input window"
+ );
+ }
+ }
+
+ #[test]
+ fn content_at_the_input_window_does_not_truncate() {
+ // generate_embedding_text only drops tokens beyond the window, so content sitting
+ // exactly on it survives intact.
+ for model in [
+ EmbeddingModel::OpenAITextEmbeddingSmall,
+ EmbeddingModel::OpenAITextEmbeddingLarge,
+ ] {
+ let content = content_with_tokens(model.model_input_window());
+ assert!(
+ !check_would_truncate(&content, &model),
+ "{model:?} should not truncate content exactly at its input window"
+ );
+ }
+ }
+}
diff --git a/rust/embedding-worker/src/main.rs b/rust/embedding-worker/src/main.rs
index 6da00ce71d0d..1da2f7f371cb 100644
--- a/rust/embedding-worker/src/main.rs
+++ b/rust/embedding-worker/src/main.rs
@@ -50,14 +50,7 @@ async fn ad_hoc_handler(
State(context): State<Arc<AppContext>>,
Json(request): Json<AdHocEmbeddingRequest>,
) -> Result<Json<AdHocEmbeddingResponse>, StatusCode> {
- match handle_ad_hoc_request(context, request).await {
- Ok(response) => Ok(Json(response)),
- Err(e) => {
- // TODO - this is a hack until I do a proper pass and add real error enums
- error!("Ad hoc embedding request failed: {:?}", e);
- Err(StatusCode::INTERNAL_SERVER_ERROR)
- }
- }
+ handle_ad_hoc_request(context, request).await
}
#[derive(Deserialize)]