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(ai-observability): repair lone surrogates in text representations (#95998)

Bernat Torres1c679b87b972
diff --git a/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py b/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py
index c486b209c691..bdf54a117092 100644
--- a/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py
+++ b/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py
@@ -29,6 +29,7 @@ from products.ai_observability.backend.text_repr.formatters import (
FormatterOptions,
format_trace_text_repr,
llm_trace_to_formatter_format,
+ sanitize_surrogates,
)
logger = structlog.get_logger(__name__)
@@ -279,8 +280,14 @@ def _format_generation_text_repr(generation_data: dict, max_length: int | None =
header_parts.append("")
- input_block = _render_generation_messages(generation_data.get("input"))
- output_block = _render_generation_messages(generation_data.get("output"))
+ # This path builds its own text instead of going through the formatters, so it repairs
+ # surrogates itself. Repair before anything is measured: the repair can shorten a section, so
+ # measuring first would make the budget arithmetic below describe text that is never returned.
+ # Repairing first also means `_truncate_section` cannot split a pair, since a repaired
+ # character is a single code point that a slice cannot cut in half.
+ header_parts = [sanitize_surrogates(part) for part in header_parts]
+ input_block = sanitize_surrogates(_render_generation_messages(generation_data.get("input")))
+ output_block = sanitize_surrogates(_render_generation_messages(generation_data.get("output")))
def assemble(in_block: str, out_block: str) -> str:
parts = list(header_parts)
diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py
index 8f31e09e2544..9c7a5117e1d8 100644
--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py
+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py
@@ -80,6 +80,18 @@ class TestFormatGenerationTextRepr:
assert "--- Output ---" in result
assert "DISTINCTIVE_OUTPUT_MARKER" in result
+ def test_stays_within_budget_while_repairing_surrogates(self):
+ generation_data = {
+ "model": "gpt-4",
+ "input": "\ud83d\ude00" * 1000,
+ "output": "short",
+ }
+
+ result = _format_generation_text_repr(generation_data, max_length=200)
+
+ assert len(result) <= 200
+ assert result.encode("utf-8")
+
def test_truncated_input_keeps_head_and_tail(self):
generation_data = {
"input": "SYSTEM_PROMPT_HEAD " + "x" * 5000 + " NEWEST_MESSAGE_TAIL",
diff --git a/products/ai_observability/backend/text_repr/formatters/__init__.py b/products/ai_observability/backend/text_repr/formatters/__init__.py
index fed997e12d9f..c205a27762e2 100644
--- a/products/ai_observability/backend/text_repr/formatters/__init__.py
+++ b/products/ai_observability/backend/text_repr/formatters/__init__.py
@@ -15,7 +15,7 @@ Main entry points:
"""
from .event_formatter import format_event_text_repr, format_event_text_repr_from_ai_events_row
-from .message_formatter import FormatterOptions, add_line_numbers, reduce_by_uniform_sampling
+from .message_formatter import FormatterOptions, add_line_numbers, reduce_by_uniform_sampling, sanitize_surrogates
from .trace_formatter import format_trace_text_repr, llm_trace_to_formatter_format
__all__ = [
@@ -26,4 +26,5 @@ __all__ = [
"format_trace_text_repr",
"llm_trace_to_formatter_format",
"reduce_by_uniform_sampling",
+ "sanitize_surrogates",
]
diff --git a/products/ai_observability/backend/text_repr/formatters/event_formatter.py b/products/ai_observability/backend/text_repr/formatters/event_formatter.py
index d86c27cc7b70..b771511e8e80 100644
--- a/products/ai_observability/backend/text_repr/formatters/event_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/event_formatter.py
@@ -12,7 +12,13 @@ from datetime import date, datetime
from typing import Any
from .constants import SEPARATOR
-from .message_formatter import FormatterOptions, add_line_numbers, format_input_messages, format_output_messages
+from .message_formatter import (
+ FormatterOptions,
+ add_line_numbers,
+ format_input_messages,
+ format_output_messages,
+ sanitize_surrogates,
+)
from .tool_formatter import format_tools
@@ -236,16 +242,16 @@ def format_event_text_repr(event: dict[str, Any], options: FormatterOptions | No
# Import here to avoid circular dependency
from .span_formatter import format_span_text_repr
- return format_span_text_repr(event, options)
-
- if event_type == "$ai_embedding":
- return format_embedding_text_repr(event, options)
-
- if event_type == "$ai_evaluation":
- return format_evaluation_text_repr(event, options)
+ formatted_text = format_span_text_repr(event, options)
+ elif event_type == "$ai_embedding":
+ formatted_text = format_embedding_text_repr(event, options)
+ elif event_type == "$ai_evaluation":
+ formatted_text = format_evaluation_text_repr(event, options)
+ else:
+ # Default to generation formatter for $ai_generation and other events
+ formatted_text = format_generation_text_repr(event, options)
- # Default to generation formatter for $ai_generation and other events
- return format_generation_text_repr(event, options)
+ return sanitize_surrogates(formatted_text)
def _maybe_decode_json(value: Any) -> Any:
diff --git a/products/ai_observability/backend/text_repr/formatters/message_formatter.py b/products/ai_observability/backend/text_repr/formatters/message_formatter.py
index bfc09f7a0773..74d6e75b79d2 100644
--- a/products/ai_observability/backend/text_repr/formatters/message_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/message_formatter.py
@@ -6,6 +6,7 @@ and content blocks. Supports multiple provider formats (OpenAI, Anthropic, etc.)
with truncation and interactive markers for frontend display.
"""
+import re
import json
import base64
from typing import Any, TypedDict
@@ -157,6 +158,30 @@ def reduce_by_uniform_sampling(
return result, True
+# UTF-16 surrogate code points. A well-formed pair survives the round trip in
+# `sanitize_surrogates` and becomes the character it encodes; a lone one becomes U+FFFD.
+SURROGATE_REGEX = re.compile("[\ud800-\udfff]")
+
+
+def sanitize_surrogates(text: str) -> str:
+ """Make `text` encodable as UTF-8.
+
+ Trace content arrives as it was captured, and the truncation and sampling above cut on
+ character counts, so either source can leave an unpaired surrogate -- half of an emoji -- in
+ the result. UTF-8 cannot represent one, so `str.encode("utf-8")` raises and the whole text
+ representation is lost: the Redis write in the batch summarization path and the request body of
+ the summarization LLM call both fail that way. Repair at the formatter exits, so every consumer
+ of a text representation gets the same encodable string.
+
+ Unlike `safe_clickhouse_string`, this does not escape the surrogate into literal `\\ud83c`
+ text. Escaping is right where the bytes must round-trip, but a text representation is read as
+ prose by a model, so a replacement character is the better loss.
+ """
+ if not SURROGATE_REGEX.search(text):
+ return text
+ return text.encode("utf-16", "surrogatepass").decode("utf-16", "replace")
+
+
def truncate_content(content: str, options: FormatterOptions | None = None) -> tuple[list[str], bool]:
"""
Truncate content with middle ellipsis for long text.
diff --git a/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py
index a43bb9995656..c8799936f1d4 100644
--- a/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py
@@ -4,6 +4,8 @@ Tests for message_formatter.py - message input/output formatting logic.
Tests cover multiple LLM provider formats, tool calls, truncation, and edge cases.
"""
+import pytest
+
from parameterized import parameterized
from ..constants import MISSING_REASONING_NOTE, MISSING_TOOL_OUTPUT_NOTE, MISSING_TOOLS_NOTE
@@ -15,6 +17,7 @@ from ..message_formatter import (
format_single_tool_call,
format_tool_calls,
safe_extract_text,
+ sanitize_surrogates,
truncate_content,
)
@@ -711,3 +714,31 @@ class TestResponsesApiItems:
result = "\n".join(format_input_messages(messages))
assert "Run the scout" in result
assert "[INPUT_TEXT]" not in result
+
+
+class TestSanitizeSurrogates:
+ """Test repair of unpaired UTF-16 surrogates."""
+
+ def test_leaves_clean_text_untouched(self):
+ """Should return the same string when there is nothing to repair."""
+ text = "plain text with a valid emoji \U0001f600 and accents \u00e9"
+ assert sanitize_surrogates(text) is text
+
+ def test_replaces_lone_surrogate(self):
+ """Should replace half an emoji with the replacement character."""
+ assert sanitize_surrogates("hi \ud83c world") == "hi \ufffd world"
+
+ def test_result_encodes_as_utf8(self):
+ """Should produce text the summarization and Redis writes can encode."""
+ text = "L001: output \ud83c"
+ with pytest.raises(UnicodeEncodeError):
+ text.encode("utf-8")
+ assert sanitize_surrogates(text).encode("utf-8")
+
+ def test_recombines_a_split_pair(self):
+ """Should rebuild an emoji left as two separate surrogate code points."""
+ assert sanitize_surrogates("hi \ud83d\ude00") == "hi \U0001f600"
+
+ def test_keeps_the_rest_of_the_text(self):
+ """Should only touch the broken character."""
+ assert sanitize_surrogates("before \ud83c after \U0001f600") == "before \ufffd after \U0001f600"
diff --git a/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py
index c29a308840c6..22577551772c 100644
--- a/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py
@@ -821,3 +821,25 @@ class TestLLMTraceToFormatterFormat:
_, hierarchy = llm_trace_to_formatter_format(trace, nest_children=True)
assert [node["event"]["id"] for node in hierarchy] == ["slow-start-first", "quick-start-second"]
+
+
+class TestSurrogateSafety:
+ """Test that a trace holding half an emoji still yields encodable text."""
+
+ def test_trace_text_repr_encodes_as_utf8(self):
+ """Should repair content captured with an unpaired surrogate."""
+ trace = {"properties": {"$ai_span_name": "broken \ud83c"}}
+ hierarchy = [
+ {
+ "event": {
+ "event": "$ai_generation",
+ "properties": {"$ai_input": [{"role": "user", "content": "hello \ud83c"}]},
+ },
+ "children": [],
+ }
+ ]
+
+ text, _ = format_trace_text_repr(trace=trace, hierarchy=hierarchy)
+
+ assert text.encode("utf-8")
+ assert "\ud83c" not in text
diff --git a/products/ai_observability/backend/text_repr/formatters/trace_formatter.py b/products/ai_observability/backend/text_repr/formatters/trace_formatter.py
index 37ba0d57953e..5dfed0b7501d 100644
--- a/products/ai_observability/backend/text_repr/formatters/trace_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/trace_formatter.py
@@ -24,6 +24,7 @@ from .message_formatter import (
format_input_messages,
format_output_messages,
reduce_by_uniform_sampling,
+ sanitize_surrogates,
truncate_content,
)
@@ -548,4 +549,4 @@ def format_trace_text_repr(
if max_length and len(formatted_text) > max_length:
formatted_text, was_sampled = reduce_by_uniform_sampling(formatted_text, max_length)
- return formatted_text, was_sampled
+ return sanitize_surrogates(formatted_text), was_sampled