: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cli): make posthog-cli api failures diagnosable and attributable (#72327)
Chris Volzerf3a3420b951b
diff --git a/cli/.sampo/changesets/api-command-error-telemetry.md b/cli/.sampo/changesets/api-command-error-telemetry.mdnew file mode 100644index 000000000000..277bacf003cb--- /dev/null+++ b/cli/.sampo/changesets/api-command-error-telemetry.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: patch+---++`posthog-cli api` failures are now diagnosable and attributable. Launch failures report the specific cause (bundle not embedded in the build, no home directory, install-directory write failure with the underlying IO error kind, Node.js missing) both in the error message and in error telemetry, instead of one generic bundle-not-found error. When the proxied Node process fails, the CLI now exits through its normal path — flushing telemetry and honoring `--no-fail` — instead of terminating immediately, and the bundled API CLI flushes its own analytics before exiting non-zero so failed calls are no longer silently dropped. The `api` command also emits the standard command-run usage event and attaches the project id from `POSTHOG_CLI_PROJECT_ID`/`POSTHOG_CLI_ENV_ID` to telemetry when stored credentials are not used.diff --git a/cli/src/api_proxy.rs b/cli/src/api_proxy.rsindex bffd3eea86b9..3380342e4bd1 100644--- a/cli/src/api_proxy.rs+++ b/cli/src/api_proxy.rs@@ -1,11 +1,12 @@+use std::io;use std::path::{Path, PathBuf};use std::process::Command;use std::{env, fs};-use anyhow::{bail, Context, Result};+use thiserror::Error;use crate::error::CapturedError;-use crate::invocation_context::InvocationContext;+use crate::invocation_context::{current_invocation_id, InvocationContext};use crate::utils::homedir::posthog_home_dir_if_available;const API_CLI_BUNDLE: &str = "posthog-api-cli.mjs";@@ -13,6 +14,99 @@ const ANALYTICS_HOST: &str = "https://us.i.posthog.com";include!(concat!(env!("OUT_DIR"), "/api_cli_bundle.rs"));+/// Which step of writing the embedded bundle to disk failed. Variant names are+/// sent to telemetry (they carry no paths or user data), so keep them stable.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum MaterializeStep {+ CreateDir,+ Write,+ Canonicalize,+}++impl MaterializeStep {+ fn as_str(self) -> &'static str {+ match self {+ MaterializeStep::CreateDir => "create_dir",+ MaterializeStep::Write => "write",+ MaterializeStep::Canonicalize => "canonicalize",+ }+ }+}++#[derive(Error, Debug)]+pub enum ApiProxyError {+ #[error("POSTHOG_API_CLI_PATH is set but empty.")]+ ConfiguredPathEmpty,+ #[error("POSTHOG_API_CLI_PATH is set to `{path}`, but that file could not be found.")]+ ConfiguredPathMissing {+ path: String,+ #[source]+ source: io::Error,+ },+ #[error("POSTHOG_API_CLI_PATH is set to `{path}`, but it is not a file.")]+ ConfiguredPathNotAFile { path: String },+ #[error(+ "This posthog-cli build does not embed the PostHog API CLI bundle, and no previously \+ installed bundle was found. Reinstall posthog-cli from an official release, or set \+ POSTHOG_API_CLI_PATH to a trusted bundle."+ )]+ BundleNotEmbedded,+ #[error(+ "Could not determine a home directory to install the PostHog API CLI bundle into. Set \+ POSTHOG_HOME to a writable directory, or POSTHOG_API_CLI_PATH to a trusted bundle."+ )]+ HomeDirUnavailable,+ #[error(+ "Failed to install the PostHog API CLI bundle to `{path}`. Make sure the directory is \+ writable (sandboxed environments often block writes to the home directory), set \+ POSTHOG_HOME to a writable directory, or set POSTHOG_API_CLI_PATH to a trusted bundle."+ )]+ MaterializeFailed {+ step: MaterializeStep,+ path: String,+ #[source]+ source: io::Error,+ },+ #[error("Failed to execute `node`. The `api` command needs Node.js installed and on PATH.")]+ NodeSpawnFailed {+ #[source]+ source: io::Error,+ },+}++impl ApiProxyError {+ /// Coarse failure class for telemetry. Never contains paths or user data.+ pub fn telemetry_kind(&self) -> &'static str {+ match self {+ ApiProxyError::ConfiguredPathEmpty+ | ApiProxyError::ConfiguredPathMissing { .. }+ | ApiProxyError::ConfiguredPathNotAFile { .. } => "configured_path_invalid",+ ApiProxyError::BundleNotEmbedded => "bundle_not_embedded",+ ApiProxyError::HomeDirUnavailable => "home_dir_unavailable",+ ApiProxyError::MaterializeFailed { .. } => "materialize_failed",+ ApiProxyError::NodeSpawnFailed { .. } => "node_spawn_failed",+ }+ }++ pub fn telemetry_step(&self) -> Option<&'static str> {+ match self {+ ApiProxyError::MaterializeFailed { step, .. } => Some(step.as_str()),+ _ => None,+ }+ }++ /// The underlying `io::ErrorKind` as a stable identifier (e.g. `PermissionDenied`).+ pub fn telemetry_io_error_kind(&self) -> Option<String> {+ let source = match self {+ ApiProxyError::ConfiguredPathMissing { source, .. } => source,+ ApiProxyError::MaterializeFailed { source, .. } => source,+ ApiProxyError::NodeSpawnFailed { source } => source,+ _ => return None,+ };+ Some(format!("{:?}", source.kind()))+ }+}+fn canonicalize_file(path: &Path) -> Option<PathBuf> {let resolved = path.canonicalize().ok()?;if resolved.is_file() {@@ -36,12 +130,41 @@ fn embedded_bundle_path(install_dir: &Path) -> PathBuf {fn materialize_embedded_script(bundle: Option<&[u8]>,install_dir: Option<&Path>,-) -> Option<PathBuf> {- let bundle = bundle?;- let path = embedded_bundle_path(install_dir?);- fs::create_dir_all(path.parent()?).ok()?;- fs::write(&path, bundle).ok()?;- canonicalize_file(&path)+) -> Result<PathBuf, ApiProxyError> {+ let Some(bundle) = bundle else {+ return Err(ApiProxyError::BundleNotEmbedded);+ };+ let Some(install_dir) = install_dir else {+ return Err(ApiProxyError::HomeDirUnavailable);+ };+ let path = embedded_bundle_path(install_dir);+ let materialize_failed =+ |step: MaterializeStep, source: io::Error| ApiProxyError::MaterializeFailed {+ step,+ path: path.display().to_string(),+ source,+ };++ let parent = path+ .parent()+ .expect("embedded bundle path always has a parent directory");+ fs::create_dir_all(parent)+ .map_err(|source| materialize_failed(MaterializeStep::CreateDir, source))?;+ fs::write(&path, bundle)+ .map_err(|source| materialize_failed(MaterializeStep::Write, source))?;+ let resolved = path+ .canonicalize()+ .map_err(|source| materialize_failed(MaterializeStep::Canonicalize, source))?;+ if !resolved.is_file() {+ return Err(materialize_failed(+ MaterializeStep::Canonicalize,+ io::Error::new(+ io::ErrorKind::InvalidData,+ "materialized bundle is not a regular file",+ ),+ ));+ }+ Ok(resolved)}fn legacy_bundle_candidates(install_dir: Option<&Path>, development_dir: &Path) -> Vec<PathBuf> {@@ -60,45 +183,52 @@ fn legacy_bundle_candidates(install_dir: Option<&Path>, development_dir: &Path)candidates}-fn find_script() -> Result<PathBuf> {+/// Resolves the bundle: prefer the embedded copy, fall back to legacy install+/// layouts, and if everything misses report the materialization failure (the+/// specific cause) rather than a generic not-found error.+fn resolve_script(+ bundle: Option<&[u8]>,+ install_dir: Option<&Path>,+ development_dir: &Path,+) -> Result<PathBuf, ApiProxyError> {+ let materialize_error = match materialize_embedded_script(bundle, install_dir) {+ Ok(resolved) => return Ok(resolved),+ Err(error) => error,+ };++ for candidate in legacy_bundle_candidates(install_dir, development_dir) {+ if let Some(resolved) = canonicalize_file(&candidate) {+ return Ok(resolved);+ }+ }++ Err(materialize_error)+}++fn find_script() -> Result<PathBuf, ApiProxyError> {if let Some(path) = env::var_os("POSTHOG_API_CLI_PATH") {if path.is_empty() {- bail!("POSTHOG_API_CLI_PATH is set but empty.");+ return Err(ApiProxyError::ConfiguredPathEmpty);}let path = PathBuf::from(path);- let resolved = path.canonicalize().with_context(|| {- format!(- "POSTHOG_API_CLI_PATH is set to `{}`, but that file could not be found.",- path.display()- )- })?;+ let resolved =+ path.canonicalize()+ .map_err(|source| ApiProxyError::ConfiguredPathMissing {+ path: path.display().to_string(),+ source,+ })?;if !resolved.is_file() {- bail!(- "POSTHOG_API_CLI_PATH is set to `{}`, but it is not a file.",- resolved.display()- );+ return Err(ApiProxyError::ConfiguredPathNotAFile {+ path: resolved.display().to_string(),+ });}return Ok(resolved);}- let install_dir = default_install_dir();- if let Some(resolved) =- materialize_embedded_script(EMBEDDED_API_CLI_BUNDLE, install_dir.as_deref())- {- return Ok(resolved);- }-- for candidate in legacy_bundle_candidates(- install_dir.as_deref(),+ resolve_script(+ EMBEDDED_API_CLI_BUNDLE,+ default_install_dir().as_deref(),Path::new(env!("CARGO_MANIFEST_DIR")),- ) {- if let Some(resolved) = canonicalize_file(&candidate) {- return Ok(resolved);- }- }-- bail!(- "Could not find the PostHog API CLI bundle. Reinstall posthog-cli, or set POSTHOG_API_CLI_PATH to a trusted bundle.")}@@ -144,16 +274,22 @@ fn inject_analytics_env(cmd: &mut Command) {}}+/// Runs the embedded Node API CLI. A non-zero child exit is returned as+/// `Ok(Some(code))` — not `process::exit` — so the caller can flush telemetry+/// and honor `--no-fail` before terminating with the same code.pub fn run(args: Vec<String>,host_override: Option<String>,invocation_context: Option<&InvocationContext>,-) -> Result<(), CapturedError> {- let script = find_script().map_err(CapturedError::from)?;+) -> Result<Option<i32>, CapturedError> {+ let script = find_script().map_err(|error| CapturedError::from(anyhow::Error::new(error)))?;let mut cmd = Command::new("node");cmd.arg(script);cmd.args(args);cmd.env("POSTHOG_CLI_VERSION", env!("CARGO_PKG_VERSION"));+ // Lets the Node script tag its analytics with this invocation, joining them+ // to the Rust-side telemetry for the same run.+ cmd.env("POSTHOG_CLI_INVOCATION_ID", current_invocation_id());inject_credentials(&mut cmd, invocation_context);inject_analytics_env(&mut cmd);@@ -162,21 +298,17 @@ pub fn run(cmd.env("POSTHOG_CLI_HOST", host);}- let status = cmd- .status()- .with_context(|| {- format!(- "Failed to execute `{}`. Is Node.js installed?",- Path::new("node").display()- )- })- .map_err(CapturedError::from)?;-- if !status.success() {- std::process::exit(status.code().unwrap_or(1));- }+ let status = cmd.status().map_err(|source| {+ CapturedError::from(anyhow::Error::new(ApiProxyError::NodeSpawnFailed {+ source,+ }))+ })?;- Ok(())+ if status.success() {+ Ok(None)+ } else {+ Ok(Some(status.code().unwrap_or(1)))+ }}#[cfg(test)]@@ -272,12 +404,75 @@ mod tests {fn embedded_bundle_is_ignored_when_it_was_not_built() {let temp_dir = tempfile::tempdir().expect("create temp dir");- assert_eq!(+ assert!(matches!(materialize_embedded_script(None, Some(temp_dir.path())),- None+ Err(ApiProxyError::BundleNotEmbedded)+ ));+ }++ #[test]+ fn missing_install_dir_reports_home_dir_unavailable() {+ assert!(matches!(+ materialize_embedded_script(Some(b"embedded bundle"), None),+ Err(ApiProxyError::HomeDirUnavailable)+ ));+ }++ #[test]+ fn materialize_failure_reports_step_and_io_error_kind() {+ let temp_dir = tempfile::tempdir().expect("create temp dir");+ // A file where the `api-cli` directory should go makes create_dir_all fail.+ fs::write(temp_dir.path().join("api-cli"), "not a directory").expect("write blocking file");++ let error = materialize_embedded_script(Some(b"embedded bundle"), Some(temp_dir.path()))+ .expect_err("materialization should fail");++ assert!(matches!(+ error,+ ApiProxyError::MaterializeFailed {+ step: MaterializeStep::CreateDir,+ ..+ }+ ));+ assert_eq!(error.telemetry_kind(), "materialize_failed");+ assert_eq!(error.telemetry_step(), Some("create_dir"));+ assert!(error.telemetry_io_error_kind().is_some());+ }++ #[test]+ fn resolve_script_falls_back_to_legacy_bundle_when_embedded_is_missing() {+ let temp_dir = tempfile::tempdir().expect("create temp dir");+ let install_dir = temp_dir.path().join("home").join(".posthog");+ let legacy_bundle = install_dir.join("lib").join(API_CLI_BUNDLE);+ fs::create_dir_all(legacy_bundle.parent().expect("legacy parent"))+ .expect("create legacy lib dir");+ fs::write(&legacy_bundle, "legacy").expect("write legacy bundle");++ let resolved = resolve_script(None, Some(&install_dir), Path::new("/nonexistent-dev-dir"))+ .expect("fall back to legacy bundle");++ assert_eq!(+ resolved,+ legacy_bundle.canonicalize().expect("canonicalize legacy"));}+ #[test]+ fn resolve_script_reports_the_materialize_error_when_no_fallback_exists() {+ let temp_dir = tempfile::tempdir().expect("create temp dir");+ // Block materialization and provide no legacy bundle anywhere.+ fs::write(temp_dir.path().join("api-cli"), "not a directory").expect("write blocking file");++ let error = resolve_script(+ Some(b"embedded bundle"),+ Some(temp_dir.path()),+ Path::new("/nonexistent-dev-dir"),+ )+ .expect_err("resolution should fail");++ assert!(matches!(error, ApiProxyError::MaterializeFailed { .. }));+ }+#[test]fn materialized_embedded_bundle_is_used_before_legacy_install() {let temp_dir = tempfile::tempdir().expect("create temp dir");diff --git a/cli/src/commands.rs b/cli/src/commands.rsindex da7b2f21accf..bc643ab9b884 100644--- a/cli/src/commands.rs+++ b/cli/src/commands.rs@@ -10,7 +10,10 @@ use crate::{dsym::DsymSubcommand,error::CapturedError,experimental::{endpoints::EndpointCommand, query::command::QueryCommand, tasks::TaskCommand},- invocation_context::{context, init_context, set_telemetry_command_name, INVOCATION_CONTEXT},+ invocation_context::{+ capture_command_run_without_context, context, init_context, set_telemetry_command_name,+ set_telemetry_env_id_from_environment, INVOCATION_CONTEXT,+ },proguard::ProguardSubcommand,sourcemaps::{hermes::HermesSubcommand, plain::SourcemapCommand},};@@ -323,7 +326,10 @@ impl ExpCommand {}impl Cli {- pub fn run() -> Result<(), CapturedError> {+ /// `Ok(Some(code))` means the command completed by delegating to a child+ /// process that exited non-zero; the caller should exit with that code+ /// after flushing telemetry.+ pub fn run() -> Result<Option<i32>, CapturedError> {let command = Cli::parse();let no_fail = command.no_fail;set_telemetry_command_name(command.command.telemetry_command_name());@@ -335,14 +341,14 @@ impl Cli {}match result {- Ok(_) => Ok(()),+ Ok(exit_code) => Ok(if no_fail { None } else { exit_code }),Err(e) => {if no_fail {match &e.exception_id {Some(id) => eprintln!("Oops! {} (ID: {})", e.inner, id),None => eprintln!("Oops! {:?}", e.inner),};- Ok(())+ Ok(None)} else {Err(e)}@@ -350,7 +356,7 @@ impl Cli {}}- fn run_impl(self) -> Result<(), CapturedError> {+ fn run_impl(self) -> Result<Option<i32>, CapturedError> {if self.dry_run {if let Some(kind) = dry_run_skipped_command(&self.command) {warn!(@@ -358,7 +364,7 @@ impl Cli {Nothing was sent to PostHog and no credentials were used. \Do not use --dry-run for release builds.");- return Ok(());+ return Ok(None);}}@@ -378,6 +384,8 @@ impl Cli {)?;}+ let mut api_exit_code: Option<i32> = None;+match self.command {Commands::Login => {// Notably login doesn't have a context set up going it - it sets one up@@ -436,6 +444,15 @@ impl Cli {}},Commands::Api { args } => {+ // The proxy often runs without stored credentials (env-var auth,+ // metadata subcommands), so attach the project id from the+ // environment for telemetry attribution; init_context overrides+ // it with the stored value when it runs.+ set_telemetry_env_id_from_environment();+ // No InvocationContext on this path, so capture the usage event+ // directly — without it the `api` command has no telemetry+ // denominator to compute failure rates against.+ let usage_capture = capture_command_run_without_context();let api_context = if api_command_needs_stored_credentials(&args) {match init_context(self.host.clone(),@@ -452,7 +469,9 @@ impl Cli {} else {None};- api_proxy::run(args, self.host, api_context)?;+ let run_result = api_proxy::run(args, self.host, api_context);+ let _ = usage_capture.join();+ api_exit_code = run_result?;}Commands::Exp { cmd } => match cmd {ExpCommand::Task {@@ -500,7 +519,7 @@ impl Cli {},}- Ok(())+ Ok(api_exit_code)}}diff --git a/cli/src/error.rs b/cli/src/error.rsindex 6d661fa174dd..61ddc84095de 100644--- a/cli/src/error.rs+++ b/cli/src/error.rs@@ -8,7 +8,10 @@ use posthog_rs::CaptureExceptionOptions;use serde::Deserialize;use tracing::debug;-use crate::{api::client::ClientError, invocation_context::current_telemetry_command_name};+use crate::{+ api::client::ClientError, api_proxy::ApiProxyError,+ invocation_context::current_telemetry_command_name,+};pub struct CapturedError {pub inner: Error,@@ -50,6 +53,9 @@ struct ErrorTelemetryMetadata {api_error_code: Option<String>,is_timeout: Option<bool>,is_connect: Option<bool>,+ proxy_error_kind: Option<&'static str>,+ proxy_step: Option<&'static str>,+ io_error_kind: Option<String>,}impl ErrorTelemetryMetadata {@@ -58,50 +64,54 @@ impl ErrorTelemetryMetadata {current_telemetry_command_name().unwrap_or_else(|| "unknown".to_string());let chain_depth = error.chain().count();+ let mut metadata = Self {+ error_kind: "other",+ command_name,+ chain_depth,+ http_status: None,+ api_error_code: None,+ is_timeout: None,+ is_connect: None,+ proxy_error_kind: None,+ proxy_step: None,+ io_error_kind: None,+ };++ if let Some(proxy_error) = error+ .chain()+ .find_map(|source| source.downcast_ref::<ApiProxyError>())+ {+ metadata.error_kind = "proxy_launch_error";+ metadata.proxy_error_kind = Some(proxy_error.telemetry_kind());+ metadata.proxy_step = proxy_error.telemetry_step();+ metadata.io_error_kind = proxy_error.telemetry_io_error_kind();+ return metadata;+ }+let Some(client_error) = error.chain().find_map(|source| source.downcast_ref::<ClientError>())else {- return Self {- error_kind: "other",- command_name,- chain_depth,- http_status: None,- api_error_code: None,- is_timeout: None,- is_connect: None,- };+ return metadata;};match client_error {- ClientError::ApiError(status, _, body) => Self {- error_kind: "api_error",- command_name,- chain_depth,- http_status: Some(*status),- api_error_code: safe_api_error_code(body),- is_timeout: None,- is_connect: None,- },- ClientError::RequestError(err) => Self {- error_kind: "request_error",- command_name,- chain_depth,- http_status: None,- api_error_code: None,- is_timeout: Some(err.is_timeout()),- is_connect: Some(err.is_connect()),- },- ClientError::InvalidUrl(_) => Self {- error_kind: "invalid_url",- command_name,- chain_depth,- http_status: None,- api_error_code: None,- is_timeout: None,- is_connect: None,- },+ ClientError::ApiError(status, _, body) => {+ metadata.error_kind = "api_error";+ metadata.http_status = Some(*status);+ metadata.api_error_code = safe_api_error_code(body);+ }+ ClientError::RequestError(err) => {+ metadata.error_kind = "request_error";+ metadata.is_timeout = Some(err.is_timeout());+ metadata.is_connect = Some(err.is_connect());+ }+ ClientError::InvalidUrl(_) => {+ metadata.error_kind = "invalid_url";+ }}++ metadata}fn fingerprint(&self) -> String {@@ -111,6 +121,18 @@ impl ErrorTelemetryMetadata {self.error_kind.to_string(),];+ if let Some(proxy_error_kind) = self.proxy_error_kind {+ parts.push(proxy_error_kind.to_string());+ }++ if let Some(proxy_step) = self.proxy_step {+ parts.push(proxy_step.to_string());+ }++ if let Some(io_error_kind) = &self.io_error_kind {+ parts.push(io_error_kind.clone());+ }+if let Some(status) = self.http_status {parts.push(status.to_string());}@@ -196,7 +218,92 @@ fn capture_exception(metadata: ErrorTelemetryMetadata) {};}+ if let Some(proxy_error_kind) = metadata.proxy_error_kind {+ options = match options.property("proxy_error_kind", proxy_error_kind) {+ Ok(options) => options,+ Err(err) => {+ debug!("Failed to attach exception proxy error kind: {err:?}");+ return;+ }+ };+ }++ if let Some(proxy_step) = metadata.proxy_step {+ options = match options.property("proxy_step", proxy_step) {+ Ok(options) => options,+ Err(err) => {+ debug!("Failed to attach exception proxy step: {err:?}");+ return;+ }+ };+ }++ if let Some(io_error_kind) = metadata.io_error_kind {+ options = match options.property("io_error_kind", io_error_kind) {+ Ok(options) => options,+ Err(err) => {+ debug!("Failed to attach exception io error kind: {err:?}");+ return;+ }+ };+ }+if let Err(err) = posthog_rs::capture_exception_with(&SanitizedCliError, options) {debug!("Failed to capture exception: {err:?}");}}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::api_proxy::{ApiProxyError, MaterializeStep};++ #[test]+ fn proxy_launch_errors_produce_structured_telemetry() {+ let error = anyhow::Error::new(ApiProxyError::MaterializeFailed {+ step: MaterializeStep::Write,+ path: "/home/user/.posthog/api-cli".to_string(),+ source: std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied"),+ })+ .context("wrapped for good measure");++ let metadata = ErrorTelemetryMetadata::from_error(&error);++ assert_eq!(metadata.error_kind, "proxy_launch_error");+ assert_eq!(metadata.proxy_error_kind, Some("materialize_failed"));+ assert_eq!(metadata.proxy_step, Some("write"));+ assert_eq!(metadata.io_error_kind.as_deref(), Some("PermissionDenied"));+ // command_name comes from mutable global telemetry state, so only pin+ // the parts of the fingerprint this test controls.+ assert!(metadata.fingerprint().starts_with("posthog-cli:"));+ assert!(metadata+ .fingerprint()+ .ends_with(":proxy_launch_error:materialize_failed:write:PermissionDenied"));+ }++ #[test]+ fn bundle_not_embedded_has_no_io_details() {+ let error = anyhow::Error::new(ApiProxyError::BundleNotEmbedded);++ let metadata = ErrorTelemetryMetadata::from_error(&error);++ assert_eq!(metadata.error_kind, "proxy_launch_error");+ assert_eq!(metadata.proxy_error_kind, Some("bundle_not_embedded"));+ assert_eq!(metadata.proxy_step, None);+ assert_eq!(metadata.io_error_kind, None);+ assert!(metadata+ .fingerprint()+ .ends_with(":proxy_launch_error:bundle_not_embedded"));+ }++ #[test]+ fn unclassified_errors_stay_other() {+ let error = anyhow::anyhow!("something else entirely");++ let metadata = ErrorTelemetryMetadata::from_error(&error);++ assert_eq!(metadata.error_kind, "other");+ assert_eq!(metadata.proxy_error_kind, None);+ assert!(metadata.fingerprint().ends_with(":other"));+ }+}diff --git a/cli/src/invocation_context.rs b/cli/src/invocation_context.rsindex 2bbfb22428eb..ff0f0ca7f2ce 100644--- a/cli/src/invocation_context.rs+++ b/cli/src/invocation_context.rs@@ -62,6 +62,31 @@ fn set_telemetry_env_id(env_id: &str) {}}+/// Attaches the project id from the environment to telemetry, for commands that+/// never load stored credentials (notably `api` with env-var auth). Values that+/// don't look like a real project id are ignored so telemetry can never pick up+/// an arbitrary string from a misconfigured environment.+pub fn set_telemetry_env_id_from_environment() {+ const ENV_ID_ENV_VARS: &[&str] = &[+ "POSTHOG_CLI_PROJECT_ID",+ "POSTHOG_CLI_ENV_ID",+ "POSTHOG_PROJECT_ID",+ ];++ let Some(env_id) = ENV_ID_ENV_VARS+ .iter()+ .find_map(|name| std::env::var(name).ok().filter(|value| !value.is_empty()))+ else {+ return;+ };++ if !matches!(env_id_validator(&env_id), Ok(Validation::Valid)) {+ return;+ }++ set_telemetry_env_id(&env_id);+}+fn apply_telemetry_properties(event: &mut Event) {let _ = event.insert_prop("cli_version", env!("CARGO_PKG_VERSION"));let _ = event.insert_prop("invocation_id", telemetry_invocation_id());@@ -86,6 +111,22 @@ fn telemetry_invocation_id() -> String {.unwrap_or_else(|_| "unknown".to_string())}+pub fn current_invocation_id() -> String {+ telemetry_invocation_id()+}++/// Captures the `posthog cli command run` usage event without requiring an+/// `InvocationContext` — the `api` command usually runs without one, which left+/// it with no usage telemetry at all. Callers must join the handle before the+/// process exits so the event reaches the queue ahead of the final flush.+pub fn capture_command_run_without_context() -> JoinHandle<()> {+ std::thread::spawn(|| {+ debug!("Capturing command run event");+ posthog_rs::capture(Event::new_anon("posthog cli command run"));+ debug!("Event queued successfully");+ })+}+fn telemetry_command_name() -> Option<String> {telemetry_context().lock()diff --git a/cli/src/main.rs b/cli/src/main.rsindex 0289ec33eeef..4e8b02f2c3c0 100644--- a/cli/src/main.rs+++ b/cli/src/main.rs@@ -17,6 +17,9 @@ fn main() {posthog_rs::flush();match result {+ // A child process (the `api` proxy) failed: telemetry is flushed above,+ // so exiting with the child's code here no longer loses events.+ Ok(Some(code)) if code != 0 => std::process::exit(code),Ok(_) => {}Err(e) => {match e.exception_id {diff --git a/services/mcp/src/cli/context.ts b/services/mcp/src/cli/context.tsindex a65c073ab693..effed858f605 100644--- a/services/mcp/src/cli/context.ts+++ b/services/mcp/src/cli/context.ts@@ -18,9 +18,30 @@ function cliIdentityKey(apiKey: string | undefined): string {return createHash('sha256').update(apiKey).digest('hex').slice(0, 16)}+const pendingAnalytics = new Set<Promise<void>>()++/**+ * Flush queued analytics before the process exits. `process.exit()` does not+ * wait for in-flight requests, so the error path must call this explicitly —+ * without it, errored `$mcp_tool_call` events are enqueued but never sent.+ */+export async function flushAnalytics(timeoutMs = 2000): Promise<void> {+ try {+ await Promise.race([+ Promise.allSettled([...pendingAnalytics]),+ new Promise((resolve) => setTimeout(resolve, timeoutMs).unref()),+ ])+ await getPostHogClient().shutdown(timeoutMs)+ } catch {+ // Analytics must never fail or block the CLI.+ }+}+export async function buildCliContext(config: CliConfig): Promise<Context> {const identityKey = cliIdentityKey(config.apiKey)const fallbackDistinctId = `posthog-cli:${identityKey}`+ // Set by the Rust wrapper; joins these events to its telemetry for the same run.+ const cliInvocationId = process.env.POSTHOG_CLI_INVOCATION_IDconst cache = new MemoryCache<State>(`cli:${identityKey}:${config.host}`)await cache.setMany({...(config.organizationId ? { orgId: config.organizationId } : {}),@@ -46,31 +67,37 @@ export async function buildCliContext(config: CliConfig): Promise<Context> {stateManager,sessionManager,getDistinctId: () => stateManager.getDistinctId(),- trackEvent: async (event: AnalyticsEvent, properties: Record<string, unknown> = {}) => {- try {- const [distinctId, analyticsContext] = await Promise.all([- stateManager.getDistinctId().catch(() => undefined),- stateManager.getAnalyticsContext().catch(() => undefined),- ])- const groups = analyticsContext ? buildMCPAnalyticsGroups(analyticsContext) : {}+ trackEvent: (event: AnalyticsEvent, properties: Record<string, unknown> = {}) => {+ const capture = (async (): Promise<void> => {+ try {+ const [distinctId, analyticsContext] = await Promise.all([+ stateManager.getDistinctId().catch(() => undefined),+ stateManager.getAnalyticsContext().catch(() => undefined),+ ])+ const groups = analyticsContext ? buildMCPAnalyticsGroups(analyticsContext) : {}- getPostHogClient().capture({- distinctId: distinctId ?? fallbackDistinctId,- event,- ...(Object.keys(groups).length > 0 ? { groups } : {}),- properties: {- $ai_product: 'mcp',- $mcp_source: 'posthog_cli',- $mcp_client_name: 'posthog-cli',- $mcp_consumer: 'posthog-cli',- $mcp_mode: 'cli',- $mcp_version: config.version,- ...(analyticsContext ? buildMCPContextProperties(analyticsContext) : {}),- $session_id: await sessionManager.getSessionUuid(sessionId),- ...properties,- },- })- } catch {}+ getPostHogClient().capture({+ distinctId: distinctId ?? fallbackDistinctId,+ event,+ ...(Object.keys(groups).length > 0 ? { groups } : {}),+ properties: {+ $ai_product: 'mcp',+ $mcp_source: 'posthog_cli',+ $mcp_client_name: 'posthog-cli',+ $mcp_consumer: 'posthog-cli',+ $mcp_mode: 'cli',+ $mcp_version: config.version,+ ...(cliInvocationId ? { cli_invocation_id: cliInvocationId } : {}),+ ...(analyticsContext ? buildMCPContextProperties(analyticsContext) : {}),+ $session_id: await sessionManager.getSessionUuid(sessionId),+ ...properties,+ },+ })+ } catch {}+ })()+ pendingAnalytics.add(capture)+ void capture.finally(() => pendingAnalytics.delete(capture))+ return capture},}diff --git a/services/mcp/src/cli/index.ts b/services/mcp/src/cli/index.tsindex 3b289deb31d1..bd8d6d6eeb2b 100644--- a/services/mcp/src/cli/index.ts+++ b/services/mcp/src/cli/index.ts@@ -8,8 +8,9 @@ import { installAgentsMdSnippet } from './agents-md'import { takeOption } from './args'import type { CliConfig } from './config'import { resolveCliConfig, requireApiKey } from './config'-import { buildCliContext } from './context'+import { buildCliContext, flushAnalytics } from './context'import { installSkill, listSkills } from './skills'+import { buildToolCallProperties } from './tool-call-properties'import { getCliTools } from './tools'const COMMAND_REFERENCE = `CLI-style command string. Supported commands:@@ -92,15 +93,7 @@ async function buildExec(config: CliConfig = resolveCliConfig()): Promise<BuiltECOMMAND_REFERENCE,'posthog-cli',(toolName, properties) => {- const toolCallProperties = {- tool_name: toolName,- $mcp_tool_name: toolName,- $mcp_duration_ms: properties.duration_ms,- $mcp_is_error: !properties.success,- output_format: properties.output_format,- ...(properties.error_message ? { error_message: properties.error_message } : {}),- }- void context.trackEvent(AnalyticsEvent.MCP_TOOL_CALL, toolCallProperties)+ void context.trackEvent(AnalyticsEvent.MCP_TOOL_CALL, buildToolCallProperties(toolName, properties))},[],{ requireDestructiveConfirmation: true }@@ -269,8 +262,11 @@ async function main(): Promise<void> {}}-main().catch((error: unknown) => {+main().catch(async (error: unknown) => {const message = error instanceof Error ? error.message : String(error)process.stderr.write(`Error: ${message}\n`)+ // process.exit() kills in-flight requests, which silently dropped every+ // errored $mcp_tool_call event; flush analytics before exiting non-zero.+ await flushAnalytics()process.exit(1)})diff --git a/services/mcp/src/cli/tool-call-properties.ts b/services/mcp/src/cli/tool-call-properties.tsnew file mode 100644index 000000000000..175b7d19faf7--- /dev/null+++ b/services/mcp/src/cli/tool-call-properties.ts@@ -0,0 +1,33 @@+import type { ExecInnerCallProperties } from '@/tools/exec'++/**+ * `$mcp_tool_call` properties for the CLI. Value-free by design: raw error+ * messages and inputs can carry caller-supplied content and API response+ * bodies, which must never reach usage analytics. Mirrors the hosted server,+ * whose tool-call events carry only the error flag — plus a bounded+ * classification so failures stay diagnosable.+ */+export function buildToolCallProperties(+ toolName: string,+ properties: ExecInnerCallProperties+): Record<string, unknown> {+ return {+ tool_name: toolName,+ $mcp_tool_name: toolName,+ $mcp_duration_ms: properties.duration_ms,+ $mcp_is_error: !properties.success,+ output_format: properties.output_format,+ ...(properties.success ? {} : { error_class: errorClass(properties) }),+ ...(properties.error_status !== undefined ? { error_status: properties.error_status } : {}),+ }+}++function errorClass(properties: ExecInnerCallProperties): 'validation_error' | 'api_error' | 'error' {+ if (properties.validation_error) {+ return 'validation_error'+ }+ if (properties.error_status !== undefined) {+ return 'api_error'+ }+ return 'error'+}diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex a534016fa0aa..f855283adbb6 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -3,7 +3,7 @@ import { z } from 'zod'import { markExecPayload, buildToolResultPayload, estimateResponseTokens } from '@/lib/build-tool-result'import { isPostHogCodeConsumer } from '@/lib/client-detection'-import { ToolInputValidationError } from '@/lib/errors'+import { findRecoverableApiError, PostHogApiError, ToolInputValidationError } from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'import { formatResponse } from '@/lib/response'@@ -35,6 +35,11 @@ export interface ExecInnerCallProperties {success: booleanoutput_format: 'json' | 'text' | 'structured'error_message?: string+ /**+ * HTTP status when the failure was a typed PostHog API error — value-free,+ * safe for consumers that must not forward raw error messages.+ */+ error_status?: number/** Input rejected by the tool's schema before dispatch — no handler ran. */validation_error?: boolean/**@@ -562,11 +567,16 @@ export function createExecTool(try {result = await tool.handler(context, input)} catch (err) {+ // PostHogValidationError is the API's 400 validation_error body.+ const apiError = findRecoverableApiError(err)trackInnerCall?.(tool.name, {duration_ms: Date.now() - startedAt,success: false,output_format: useJson ? 'json' : 'text',error_message: err instanceof Error ? err.message : String(err),+ ...(apiError+ ? { error_status: apiError instanceof PostHogApiError ? apiError.status : 400 }+ : {}),input,})throw errdiff --git a/services/mcp/tests/cli/tool-call-properties.test.ts b/services/mcp/tests/cli/tool-call-properties.test.tsnew file mode 100644index 000000000000..70ff22093c6d--- /dev/null+++ b/services/mcp/tests/cli/tool-call-properties.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest'++import { buildToolCallProperties } from '@/cli/tool-call-properties'+import type { ExecInnerCallProperties } from '@/tools/exec'++// The CLI flushes these events on the error path, so anything value-carrying+// here (raw error messages, inputs) would ship caller content and API response+// bodies to usage analytics. `toEqual` pins the exact shape: reintroducing+// `error_message` or `input` fails every case below.+describe('buildToolCallProperties', () => {+ const base: ExecInnerCallProperties = {+ duration_ms: 42,+ success: false,+ output_format: 'text',+ error_message: 'API error: {"detail": "secret notebook content …"}',+ input: { markdown: 'private caller-supplied text' },+ }++ it('never forwards error_message or input, only a value-free classification', () => {+ expect(buildToolCallProperties('notebook-edit', base)).toEqual({+ tool_name: 'notebook-edit',+ $mcp_tool_name: 'notebook-edit',+ $mcp_duration_ms: 42,+ $mcp_is_error: true,+ output_format: 'text',+ error_class: 'error',+ })+ })++ it.each([+ ['schema rejection', { validation_error: true }, { error_class: 'validation_error' }],+ ['typed API failure', { error_status: 429 }, { error_class: 'api_error', error_status: 429 }],+ ])('classifies a %s without carrying the message', (_name, extra, expected) => {+ expect(buildToolCallProperties('feature-flag-get-all', { ...base, ...extra })).toEqual({+ tool_name: 'feature-flag-get-all',+ $mcp_tool_name: 'feature-flag-get-all',+ $mcp_duration_ms: 42,+ $mcp_is_error: true,+ output_format: 'text',+ ...expected,+ })+ })++ it('omits error fields entirely on success', () => {+ expect(buildToolCallProperties('feature-flag-get-all', { ...base, success: true })).toEqual({+ tool_name: 'feature-flag-get-all',+ $mcp_tool_name: 'feature-flag-get-all',+ $mcp_duration_ms: 42,+ $mcp_is_error: false,+ output_format: 'text',+ })+ })+})diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex a48746573487..a4123cc99d38 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'import { parse as parseYaml } from 'yaml'import { z } from 'zod'-import { ToolInputValidationError } from '@/lib/errors'+import { PostHogApiError, ToolInputValidationError } from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'import { buildQueryToolsBlock, buildToolDomainsCompact } from '@/lib/instructions'import { InstructionsFormatter } from '@/lib/instructions-formatter'@@ -580,12 +580,44 @@ describe('exec tool', () => {expect(calls).toHaveLength(1)expect(calls[0]!.properties.success).toBe(false)expect(calls[0]!.properties.error_message).toBe('boom')+ // A plain Error is not a typed API failure, so no status is attached.+ expect(calls[0]!.properties.error_status).toBeUndefined()expect(calls[0]!.properties.output_format).toBe('text')// Token estimates are success-only — nothing useful to measure on a throw.expect(calls[0]!.properties.input_tokens).toBeUndefined()expect(calls[0]!.properties.output_tokens).toBeUndefined()})+ it('attaches error_status when the inner tool throws a typed API error', async () => {+ const calls: { toolName: string; properties: ExecInnerCallProperties }[] = []+ const tracker = (toolName: string, properties: ExecInnerCallProperties): void => {+ calls.push({ toolName, properties })+ }+ const failing = makeMockTool({+ handler: async () => {+ throw new PostHogApiError({+ status: 429,+ statusText: 'Too Many Requests',+ body: 'rate limited',+ url: 'https://example.com/api/projects/1/insights/',+ method: 'GET',+ })+ },+ })+ const exec = createExecTool(+ [failing],+ mockContext,+ 'test description',+ 'test command reference',+ undefined,+ tracker+ )+ await expect(exec.handler(mockContext, { command: 'call mock-tool' })).rejects.toThrow()+ expect(calls).toHaveLength(1)+ expect(calls[0]!.properties.success).toBe(false)+ expect(calls[0]!.properties.error_status).toBe(429)+ })+it('invokes the inner-call tracker with validation_error=true when input fails validation', async () => {const calls: { toolName: string; properties: ExecInnerCallProperties }[] = []const tracker = (toolName: string, properties: ExecInnerCallProperties): void => {