: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
feat(error-tracking): [robot] link errors to traces for agents (#116561)
Paul D'Ambra3186542cd6c2
diff --git a/products/error_tracking/skills/linking-errors-to-traces/SKILL.md b/products/error_tracking/skills/linking-errors-to-traces/SKILL.mdnew file mode 100644index 000000000000..2b9bf843a044--- /dev/null+++ b/products/error_tracking/skills/linking-errors-to-traces/SKILL.md@@ -0,0 +1,67 @@+---+name: linking-errors-to-traces+description: >+ Links a PostHog error occurrence or session's errors to OpenTelemetry traces, logs with the+ same trace ID, and Session Replay. Use when the user asks for trace or span IDs on an error,+ same-trace logs, or backend traces for errors in a session. Starts from an occurrence UUID,+ session ID, or error tracking issue URL. For a general issue diagnosis or replay summary,+ use investigating-error-issue or investigating-replay.+---++# Link errors to traces and logs++Use a shared ID to connect records. A matching service and time do not prove+that a log or span belongs to an error.++## Find the exception++For an issue ID or URL, call `posthog:query-error-tracking-issue-events` with+`include: ["exception", "correlation"]`, `filterTestAccounts: false`, and a small+`limit`. Choose one occurrence unless the user asks for several. Say when the+result is a sample.++For an occurrence ID or session ID, read+[finding-exceptions.md](./references/finding-exceptions.md) for the exact lookup.+Use the user's time range when given. If no event appears, state the window+you checked. Do not claim that an event never existed based on a bounded search.++## Follow the IDs++1. **Replay:** If the event has `$session_id`, call+ `posthog:session-recording-get` with that ID. `found: false` means no+ recording was found; the error or session may still exist. Use+ `posthog:generate-app-url` with `/replay/{id}` when a recording exists.+2. **Exact trace:** For each unique, nonzero, 32-character hex `$trace_id`,+ call `posthog:apm-trace-get` with that ID and `excludeAttributes: true`.+ Use its `_posthogUrl` for the trace link. If the event has `$span_id`,+ compare it with returned span IDs as hex, ignoring case. An empty result+ means no retained span was found for that trace ID. Logs may still exist.+3. **Session trace candidates:** If an event lacks `$trace_id` and the user+ asked about session traces, use `posthog:apm-attributes-list` to find a+ span attribute that stores the session ID. If a clear key exists, call+ `posthog:query-apm-spans` with an exact `span_attribute` filter, a short+ window around the error, `flatSpans: true`, and a small `limit`. This finds+ matching child spans as well as root spans. Call `posthog:apm-trace-get`+ for a candidate that needs a link. Label these as session matches. Time+ alone does not prove which request raised the error.+4. **Same-trace logs:** When an event has a trace ID, read+ [finding-trace-logs.md](./references/finding-trace-logs.md) for the bounded+ service lookup and exact log filter. Include every severity, including+ `info`. A trace can have logs even when no span was retained.++Use `posthog:generate-app-url` with `/error_tracking/{id}` when the issue ID is known.+Do not build PostHog links by hand.++## Report the result++For each checked occurrence, show the error time, IDs used for the join, and+links to the issue, replay, and retained trace when available. Summarize+matching logs with their time and severity. Exclude secrets and unneeded+personal data from log excerpts.++Name each gap separately: no trace ID on the event, trace ID but no retained+span, no session attribute on spans, no recording, or no logs with that trace+ID in the checked window. A session-matched span is a candidate until an+exact trace or span ID connects it to the error. State any row limit or time+range that kept the search from being complete. If a lookup fails, say that its+result is unknown instead of reporting that no matching data exists.diff --git a/products/error_tracking/skills/linking-errors-to-traces/references/finding-exceptions.md b/products/error_tracking/skills/linking-errors-to-traces/references/finding-exceptions.mdnew file mode 100644index 000000000000..1b196e0c78ff--- /dev/null+++ b/products/error_tracking/skills/linking-errors-to-traces/references/finding-exceptions.md@@ -0,0 +1,51 @@+# Find exception occurrences++- For an occurrence UUID, use `posthog:execute-sql` to select the exact+ `$exception` event by `uuid`.+- For a UUID-shaped session ID, use `posthog:execute-sql` to select+ `$exception` events with that exact `$session_id`. Start with a 30-day window+ and 21 rows. The extra row shows when the first 20 do not cover the session.+ Narrow or page through the window for a complete list.+- For a custom session ID, use the exact typed filter below. Session IDs do not+ have to be UUIDs.++Use this query for a UUID-shaped session. For an occurrence, replace the+session predicate with `uuid = '<occurrence_uuid>'` and use `LIMIT 1`. Put only+a validated UUID in either SQL literal.++```sql+posthog:execute-sql+SELECT+ uuid,+ issue_id,+ timestamp,+ properties.$session_id AS session_id,+ properties.$trace_id AS trace_id,+ properties.$span_id AS span_id+FROM events+WHERE event = '$exception'+ AND $session_id = '<session_uuid>'+ AND timestamp >= now() - INTERVAL 30 DAY+ORDER BY timestamp DESC+LIMIT 21+```++For a custom session ID, call `posthog:query-error-tracking-issues-list`+without putting the ID in SQL:++```json+{+ "dateRange": { "date_from": "-30d" },+ "status": "all",+ "filterTestAccounts": false,+ "filterGroup": [{ "key": "$session_id", "type": "event", "operator": "exact", "value": "<session_id>" }],+ "limit": 20+}+```++For each returned issue, call `posthog:query-error-tracking-issue-events` with+the same `dateRange` and `filterGroup`, `filterTestAccounts: false`,+`include: ["exception", "correlation"]`, and a small `limit`. Page with+`offset` if `hasMore` is true and more results matter. Otherwise, state the+limit. This path covers grouped issues and sampled events; say that it may+miss ungrouped exceptions.diff --git a/products/error_tracking/skills/linking-errors-to-traces/references/finding-trace-logs.md b/products/error_tracking/skills/linking-errors-to-traces/references/finding-trace-logs.mdnew file mode 100644index 000000000000..83430318603c--- /dev/null+++ b/products/error_tracking/skills/linking-errors-to-traces/references/finding-trace-logs.md@@ -0,0 +1,47 @@+# Find logs with the same trace ID++For each unique trace ID, use the bounded SQL query below to find services+with logs for that trace, even when retained spans name some services. Add any+service names from the retained trace. `logs-attribute-values-list` cannot+filter service values by trace ID. If no service is found, do not make an+unscoped log query.++Raw `logs.trace_id` values use base64. Convert the validated hex ID in the+predicate, and use a short time window around the error. The 21st row shows+when the first 20 services are incomplete. Narrow the window and retry if a+complete list matters; otherwise report the limit.++```sql+posthog:execute-sql+SELECT service_name, count() AS log_count+FROM logs+WHERE trace_id = base64Encode(unhex('<trace_id>'))+ AND timestamp >= '<before_error>'+ AND timestamp < '<after_error>'+GROUP BY service_name+ORDER BY log_count DESC+LIMIT 21+```++Call `posthog:logs-count`, then `posthog:query-logs` with the same trace ID,+services, and time window. Use this filter shape. Use the same filters without+`limit` for `posthog:logs-count`. Keep the row limit small and narrow the+window if the count is large.++```json+{+ "query": {+ "serviceNames": ["<service_name>"],+ "dateRange": { "date_from": "<before_error>", "date_to": "<after_error>" },+ "filterGroup": [+ {+ "key": "trace_id",+ "type": "log",+ "operator": "exact",+ "value": "<trace_id>"+ }+ ],+ "limit": 50+ }+}+```diff --git a/products/posthog_ai/eval_harness/test/test_skill_distribution_scorers.py b/products/posthog_ai/eval_harness/test/test_skill_distribution_scorers.pyindex e577b6955a12..a7e8669029c0 100644--- a/products/posthog_ai/eval_harness/test/test_skill_distribution_scorers.py+++ b/products/posthog_ai/eval_harness/test/test_skill_distribution_scorers.py@@ -6,7 +6,9 @@ import pytestfrom braintrust_core.score import Score, Scorer+from products.posthog_ai.eval_harness.harness.cli import SkillDeliveryfrom products.posthog_ai.evals.cli_mcp.skill_distribution_scorers import (+ ExcludedSkillNotLoaded,ExpectedSkillDiscovered,ExpectedSkillLoaded,NoBundledSkillBypass,@@ -329,3 +331,22 @@ def test_bundled_distribution_accepts_an_alternate_skill(scorer: Scorer) -> None)assert _score(scorer, output, BUNDLED_WITH_ALTERNATE).score == 1.0assert _score(scorer, output, BUNDLED_EXPECTED).score == 0.0+++ "delivery,load_call,expected_score",+ [+ ("exec", _exec("search", "learn -s error trace", "posthog:linking-errors-to-traces"), 1.0),+ ("exec", _exec("load", "learn posthog:linking-errors-to-traces"), 0.0),+ ("exec", _exec("failed", "learn posthog:linking-errors-to-traces", failed=True), 1.0),+ ("bundled", _tool_call("load", "Skill", {"skill": "linking-errors-to-traces"}), 0.0),+ ("bundled", _tool_call("other", "Skill", {"skill": SKILL}), 1.0),+ ],+)+def test_excluded_skill_only_fails_when_it_is_loaded(+ delivery: SkillDelivery, load_call: list[str], expected_score: float+) -> None:+ expected = skill_distribution_expectations(+ SKILL, ["execute-sql"], delivery, excluded_skill="linking-errors-to-traces"+ )+ assert _score(ExcludedSkillNotLoaded(), _output(load_call), expected).score == expected_scorediff --git a/products/posthog_ai/evals/cli_mcp/eval_skill_distribution.py b/products/posthog_ai/evals/cli_mcp/eval_skill_distribution.pyindex 6ed4d234aa85..116b50f68d69 100644--- a/products/posthog_ai/evals/cli_mcp/eval_skill_distribution.py+++ b/products/posthog_ai/evals/cli_mcp/eval_skill_distribution.py@@ -1,10 +1,14 @@from __future__ import annotations+from collections.abc import Callable+from typing import Any+from products.posthog_ai.eval_harness.base import SandboxedPublicEvalfrom products.posthog_ai.eval_harness.config import SandboxedEvalCasefrom products.posthog_ai.eval_harness.harness.cli import SkillDeliveryfrom products.posthog_ai.eval_harness.harness.context import EvalContextfrom products.posthog_ai.evals.cli_mcp.skill_distribution_scorers import (+ ExcludedSkillNotLoaded,ExpectedSkillDiscovered,ExpectedSkillLoaded,NoBundledSkillBypass,@@ -13,7 +17,8 @@ from products.posthog_ai.evals.cli_mcp.skill_distribution_scorers import (SkillSearchFirst,skill_distribution_expectations,)-from products.tasks.backend.facade.agents import EVAL_INTERACTION_ORIGIN+from products.posthog_ai.evals.error_tracking.seeders import seed_error_tracking_issues+from products.tasks.backend.facade.agents import EVAL_INTERACTION_ORIGIN, CustomPromptSandboxContextdef _case(@@ -24,14 +29,21 @@ def _case(skill_delivery: SkillDelivery,*,alternate_skills: list[str] | None = None,+ excluded_skill: str | None = None,+ setup: Callable[[CustomPromptSandboxContext], dict[str, Any]] | None = None,) -> SandboxedEvalCase:return SandboxedEvalCase(name=name,prompt=prompt,expected=skill_distribution_expectations(- skill, downstream_tools, skill_delivery, alternate_skills=alternate_skills+ skill,+ downstream_tools,+ skill_delivery,+ alternate_skills=alternate_skills,+ excluded_skill=excluded_skill,),metadata={"expected_skill": skill, "skill_delivery": skill_delivery},+ setup=setup,# The sandbox identifies as the eval consumer, which the MCP serves `learn` to; the default# (Desktop) consumer is excluded from `learn`, so the exec arm would never exercise it.interaction_origin=EVAL_INTERACTION_ORIGIN,@@ -102,6 +114,61 @@ async def eval_skill_distribution(ctx: EvalContext) -> None:downstream_tools=["query-trends"],skill_delivery=ctx.skill_delivery,),+ _case(+ name="session_errors_to_traces_and_logs",+ prompt=(+ "For session 3db8f93b-4c5d-4f1c-aaf1-9c891632eb18, find the traces for its captured errors "+ "and the logs from each trace. Tell me where a link is missing."+ ),+ skill="linking-errors-to-traces",+ downstream_tools=["execute-sql"],+ skill_delivery=ctx.skill_delivery,+ ),+ _case(+ name="occurrence_to_trace_and_replay",+ prompt=(+ "Find the OpenTelemetry trace, same-trace logs, and replay for error occurrence "+ "c63f0d39-86ea-4a55-9a5b-c25339875390."+ ),+ skill="linking-errors-to-traces",+ downstream_tools=["execute-sql"],+ skill_delivery=ctx.skill_delivery,+ ),+ _case(+ name="replay_summary_without_trace_request",+ prompt=(+ "Summarize what happened in recording 24d9f620-6d35-4b48-91aa-b634b0f15f64 "+ "and the main actions on screen."+ ),+ skill="investigating-replay",+ downstream_tools=["session-recording-get"],+ skill_delivery=ctx.skill_delivery,+ excluded_skill="linking-errors-to-traces",+ ),+ _case(+ name="error_triage_without_trace_request",+ prompt=(+ "Which active error tracking issues are affecting the most users this week? "+ "Give me a short list of what to investigate first."+ ),+ skill="triaging-error-issues",+ downstream_tools=["query-error-tracking-issues-list"],+ skill_delivery=ctx.skill_delivery,+ excluded_skill="linking-errors-to-traces",+ setup=seed_error_tracking_issues,+ ),+ _case(+ name="single_issue_diagnosis_without_trace_request",+ prompt=(+ "Investigate the checkout TimeoutError issue. Who is affected, when did it start, "+ "and what should we check next?"+ ),+ skill="investigating-error-issue",+ downstream_tools=["query-error-tracking-issues-list", "query-error-tracking-issue"],+ skill_delivery=ctx.skill_delivery,+ excluded_skill="linking-errors-to-traces",+ setup=seed_error_tracking_issues,+ ),]await SandboxedPublicEval(@@ -111,6 +178,7 @@ async def eval_skill_distribution(ctx: EvalContext) -> None:SkillSearchFirst(),ExpectedSkillDiscovered(),ExpectedSkillLoaded(),+ ExcludedSkillNotLoaded(),SkillLoadedBeforeTool(),NoBundledSkillBypass(),NoExecSkillBypass(),diff --git a/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py b/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.pyindex edcab296662e..7de604c232d3 100644--- a/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py+++ b/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py@@ -51,6 +51,7 @@ def skill_distribution_expectations(*,source: str = "posthog",alternate_skills: list[str] | None = None,+ excluded_skill: str | None = None,) -> dict[str, dict[str, object]]:"""``alternate_skills`` are other skills that legitimately cover the case, such as asupport front door that wraps the expected skill; loading any of them counts."""@@ -61,6 +62,12 @@ def skill_distribution_expectations("expected_skill_loaded": {**skill_spec, "delivery": skill_delivery},"skill_loaded_before_tool": {**skill_spec, "delivery": skill_delivery, "tools": downstream_tools},}+ if excluded_skill:+ expectations["excluded_skill_not_loaded"] = {+ "skill": excluded_skill,+ "source": source,+ "delivery": skill_delivery,+ }if skill_delivery == "exec":expectations.update({@@ -367,6 +374,36 @@ class ExpectedSkillLoaded(Scorer):)+class ExcludedSkillNotLoaded(Scorer):+ def _name(self) -> str:+ return "excluded_skill_not_loaded"++ def _run_eval_sync(+ self,+ output: dict[str, object] | None,+ expected: dict[str, object] | None = None,+ **kwargs: object,+ ) -> Score:+ spec = _expected_spec(expected, self._name())+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": "Scorer does not apply"})+ skill_spec = _skill_and_delivery(spec)+ if skill_spec is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "Invalid scorer expectation"})+ parser = _parser(output)+ if parser is None:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No raw log"})++ loads = _any_skill_loads(parser, skill_spec.skills, skill_spec.delivery, skill_spec.source)+ if loads:+ return Score(+ name=self._name(),+ score=0.0,+ metadata={"reason": "Excluded skill was loaded", "skill": loads[0].skill, "call_id": loads[0].call_id},+ )+ return Score(name=self._name(), score=1.0)++class SkillLoadedBeforeTool(Scorer):def _name(self) -> str:return "skill_loaded_before_tool"