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(slo): trustworthy delivery metric and NUL-safe snapshot writes (#70965)

Vasco de Krijger6e20b95b4065
diff --git a/products/exports/backend/temporal/subscriptions/activities.py b/products/exports/backend/temporal/subscriptions/activities.py
index fe02dd1f9594..8e4b9074be52 100644
--- a/products/exports/backend/temporal/subscriptions/activities.py
+++ b/products/exports/backend/temporal/subscriptions/activities.py
@@ -73,6 +73,8 @@ async def _persist_content_snapshot(
@database_sync_to_async(thread_sensitive=False)
def _merge() -> None:
delivery = SubscriptionDelivery.objects.get(pk=delivery_id)
+ # insight_snapshots must already be NUL-scrubbed at its source (build_insight_delivery_snapshot
+ # → _serialize_insight_result); a NUL reaching content_snapshot fails this save with a DataError.
delivery.content_snapshot = {
**(delivery.content_snapshot or {}),
"total_insight_count": total_insight_count,
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
index b269b18d24e0..33e33d4a5f5b 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
@@ -28,6 +28,7 @@ from products.exports.backend.temporal.subscriptions.delivery_common import (
auto_disable_and_return,
deliver_email,
deliver_slack,
+ strip_null_bytes,
)
from products.exports.backend.temporal.subscriptions.types import (
AI_REPORT_DIAGNOSTICS_KEY,
@@ -105,13 +106,15 @@ async def _persist_ai_report(delivery_id: uuid.UUID, result: AiReportResult, pro
# No DoesNotExist guard: create_delivery_record always writes this row before
# generation runs, so a missing row is a wiring bug — let it raise loudly.
delivery = SubscriptionDelivery.objects.get(pk=delivery_id)
+ # LLM output and the user prompt can carry NUL bytes that Postgres text/jsonb reject;
+ # scrub them here (payloads are small) as they are the untrusted inputs on this write path.
delivery.content_snapshot = {
**(delivery.content_snapshot or {}),
- AI_REPORT_SNAPSHOT_KEY: result.markdown,
- AI_REPORT_DIAGNOSTICS_KEY: [dataclasses.asdict(d) for d in result.diagnostics],
+ AI_REPORT_SNAPSHOT_KEY: strip_null_bytes(result.markdown),
+ AI_REPORT_DIAGNOSTICS_KEY: strip_null_bytes([dataclasses.asdict(d) for d in result.diagnostics]),
AI_REPORT_WINDOW_END_KEY: result.window_end_utc,
# prompt is None for non-AI subs; "" if cleared — omit either.
- **({AI_REPORT_PROMPT_SNAPSHOT_KEY: prompt} if prompt else {}),
+ **({AI_REPORT_PROMPT_SNAPSHOT_KEY: strip_null_bytes(prompt)} if prompt else {}),
}
delivery.save(update_fields=["content_snapshot", "last_updated_at"])
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py
index f81dcd6b48f3..45ca44dd74a4 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_activities.py
@@ -94,6 +94,31 @@ async def test_persist_ai_report_writes_markdown_query_diagnostics_and_prompt(te
assert snapshot[AI_REPORT_PROMPT_SNAPSHOT_KEY] == "weekly adoption + reliability report"
+async def test_persist_ai_report_strips_null_bytes(team, user) -> None:
+ # Regression witness: LLM output, diagnostics, and the prompt are untrusted NUL sources. Without
+ # the scrub, the NUL reaches content_snapshot and Postgres rejects the whole save with a DataError,
+ # so this test would fail on the write itself; with it, the NULs are gone and the rest survives.
+ delivery = await _create_delivery(team, user)
+
+ await _persist_ai_report(
+ delivery.id,
+ AiReportResult(
+ markdown="# Weekly\x00 report",
+ window_end_utc=_WINDOW_END_UTC,
+ diagnostics=(
+ QueryStepDiagnostic(description="adop\x00tion", hogql="SELECT co\x00unt()", ok=True, error_type=None),
+ ),
+ ),
+ prompt="weekly\x00 report",
+ )
+
+ snapshot = await _snapshot(delivery.id)
+ assert snapshot[AI_REPORT_SNAPSHOT_KEY] == "# Weekly report"
+ assert snapshot[AI_REPORT_DIAGNOSTICS_KEY][0]["description"] == "adoption"
+ assert snapshot[AI_REPORT_DIAGNOSTICS_KEY][0]["hogql"] == "SELECT count()"
+ assert snapshot[AI_REPORT_PROMPT_SNAPSHOT_KEY] == "weekly report"
+
+
@pytest.mark.parametrize("prompt", [None, ""])
async def test_persist_ai_report_omits_blank_prompt(team, user, prompt) -> None:
# A non-AI sub passes prompt=None and a cleared prompt passes ""; neither should write the key
diff --git a/products/exports/backend/temporal/subscriptions/delivery_common.py b/products/exports/backend/temporal/subscriptions/delivery_common.py
index c82271df8676..961cf2b1c6c2 100644
--- a/products/exports/backend/temporal/subscriptions/delivery_common.py
+++ b/products/exports/backend/temporal/subscriptions/delivery_common.py
@@ -1,4 +1,5 @@
from collections.abc import Awaitable, Callable
+from typing import Any
from slack_sdk.errors import SlackApiError
from structlog import get_logger
@@ -27,6 +28,26 @@ from ee.tasks.subscriptions.slack_subscriptions import SlackDeliveryResult, get_
LOGGER = get_logger(__name__)
+def strip_null_bytes(value: Any) -> Any:
+ """Recursively remove NUL (\\x00) from strings — Postgres text/jsonb columns cannot store it.
+
+ Anything written to ``SubscriptionDelivery.content_snapshot`` that originates outside a Postgres
+ text column (ClickHouse query results, LLM output, user-supplied prompts) must pass through this
+ first, or the NUL surfaces as a unicode escape that fails the whole delivery write with a DataError.
+ """
+ if isinstance(value, str):
+ return value.replace("\x00", "")
+ if isinstance(value, list):
+ return [strip_null_bytes(v) for v in value]
+ if isinstance(value, tuple):
+ return tuple(strip_null_bytes(v) for v in value)
+ if isinstance(value, dict):
+ # Strip keys too: a Map(String, …) column can produce data-derived keys carrying NUL,
+ # and Postgres rejects it in a jsonb key just as it does in a value.
+ return {strip_null_bytes(k): strip_null_bytes(v) for k, v in value.items()}
+ return value
+
+
async def auto_disable_and_return(
subscription: Subscription,
reason: DisableReason,
diff --git a/products/exports/backend/temporal/subscriptions/insight_snapshot.py b/products/exports/backend/temporal/subscriptions/insight_snapshot.py
index 5bbc61d47d11..a66acd02a9ae 100644
--- a/products/exports/backend/temporal/subscriptions/insight_snapshot.py
+++ b/products/exports/backend/temporal/subscriptions/insight_snapshot.py
@@ -28,6 +28,7 @@ from posthog.models import Team, User
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.exports.backend.models.subscription import Subscription
+from products.exports.backend.temporal.subscriptions.delivery_common import strip_null_bytes
from products.product_analytics.backend.models.insight import Insight
logger = structlog.get_logger(__name__)
@@ -71,22 +72,37 @@ def _serialize_insight_result(result: InsightResult) -> dict[str, Any]:
# json.dumps (Django JSONField's default encoder) emits for non-finite floats.
# `default=str` covers types orjson doesn't serialize natively (notably Decimal) the way
# DjangoJSONEncoder would have, so switching encoders is a no-op for non-finite-float payloads.
- return orjson.loads(
- orjson.dumps(
- {
- "result": result.result,
- "columns": result.columns,
- "types": result.types,
- "resolved_date_range": _json_safe_value(result.resolved_date_range),
- "last_refresh": result.last_refresh.isoformat() if result.last_refresh else None,
- "is_cached": result.is_cached,
- "timezone": result.timezone,
- "has_more": result.has_more,
- "query_status": _json_safe_value(result.query_status),
- },
- default=str,
- )
+ dumped = orjson.dumps(
+ {
+ "result": result.result,
+ "columns": result.columns,
+ "types": result.types,
+ "resolved_date_range": _json_safe_value(result.resolved_date_range),
+ "last_refresh": result.last_refresh.isoformat() if result.last_refresh else None,
+ "is_cached": result.is_cached,
+ "timezone": result.timezone,
+ "has_more": result.has_more,
+ "query_status": _json_safe_value(result.query_status),
+ },
+ default=str,
)
+ parsed = orjson.loads(dumped)
+ # Query results can carry NUL bytes from upstream data, and Django's JSONField serializes a NUL
+ # to a unicode escape that Postgres text/jsonb columns reject — failing the whole delivery write
+ # with a DataError. So we strip NUL before returning, but only when one is actually present:
+ #
+ # - Cost: result.result is arbitrary ClickHouse output and can reach several MB; strip_null_bytes
+ # rebuilds the entire dict/list tree, so running it on every delivery (nearly none carry a NUL)
+ # would be pure waste. The gate is a single byte scan over the buffer we already serialized.
+ # - Correctness: orjson always emits a real NUL as an escape sequence (JSON forbids a raw control
+ # byte), including inside object keys, so the check never misses a genuine NUL. It can only
+ # over-trigger on literal escape text in the data, which is harmless — the walk then finds none.
+ #
+ # The AI-report path scrubs unconditionally instead, since those payloads are small (see
+ # delivery_common.strip_null_bytes callers).
+ if b"\\u0000" in dumped:
+ parsed = strip_null_bytes(parsed)
+ return parsed
def _insight_snapshot_base_metadata(*, insight: Insight, tile: DashboardTile | None) -> dict[str, Any]:
@@ -191,7 +207,8 @@ def _execute_and_serialize_insight_query(
return {
"query_results": None,
"cache_key": None,
- "query_error": {"type": type(e).__name__, "message": str(e)},
+ # str(e) can echo offending query data, so scrub it like the result payload.
+ "query_error": {"type": type(e).__name__, "message": strip_null_bytes(str(e))},
}
if isinstance(insight_result, NothingInCacheResult):
diff --git a/products/exports/backend/temporal/subscriptions/test_insight_snapshot.py b/products/exports/backend/temporal/subscriptions/test_insight_snapshot.py
index cdeb1e0a8de2..d3c9d991f119 100644
--- a/products/exports/backend/temporal/subscriptions/test_insight_snapshot.py
+++ b/products/exports/backend/temporal/subscriptions/test_insight_snapshot.py
@@ -74,6 +74,26 @@ def test_serialize_insight_result_non_finite_floats_become_null():
]
+def test_serialize_insight_result_strips_null_bytes():
+ # Regression witness: ClickHouse result strings can carry NUL (\x00). Django's JSONField
+ # serializes it to a unicode escape that Postgres text/jsonb reject, failing the whole
+ # subscription delivery write. The NUL must be stripped while the rest of the string survives.
+ result = _build_insight_result(
+ # A Map(String, …) column deserializes to a dict, so NUL can land in a key too.
+ result=[["Success?\x00 Yes: Env", {"la\x00bel": "val\x00ue"}], ["\x00leading", "trailing\x00"]],
+ columns=["label\x00", "value"],
+ types=["String", "String"],
+ )
+
+ serialized = _serialize_insight_result(result)
+
+ # Round-trip through stdlib json (what JSONField uses) must not raise and must be NUL-free.
+ reparsed = json.loads(json.dumps(serialized))
+ assert reparsed["result"] == [["Success? Yes: Env", {"label": "value"}], ["leading", "trailing"]]
+ assert reparsed["columns"] == ["label", "value"]
+ assert "\x00" not in json.dumps(serialized)
+
+
def test_serialize_insight_result_handles_decimal_and_date():
# Regression witness: orjson raises on Decimal without a default= hook, and stdlib json
# raises on bare date. Both used to live on the ClickHouse result path for revenue /
diff --git a/terraform/us/project-2/team-analytics-platform/slo-monitoring/insights.tf b/terraform/us/project-2/team-analytics-platform/slo-monitoring/insights.tf
index 2fee7c478409..70c3aafbd617 100644
--- a/terraform/us/project-2/team-analytics-platform/slo-monitoring/insights.tf
+++ b/terraform/us/project-2/team-analytics-platform/slo-monitoring/insights.tf
@@ -341,14 +341,18 @@ resource "posthog_insight" "slo_success_rate" {
source = {
kind = "HogQLQuery"
query = <<-SQL
- -- No correlation_id needed: daily buckets have negligible cross-bucket issues.
- -- Sampled operations are reweighted by 1/sample_rate so the rate reflects
- -- true volume; events without the property coalesce to 1.0 (no sampling).
+ -- Pair starts to completions by correlation_id (same as the burn rate query) so an
+ -- operation that starts late in a day and finishes after midnight is attributed to its
+ -- start day, not miscounted as a failure on the start day and dropped on the next.
+ -- Uncorrelated events (cid = '') fall back to per-day bucket counting with a clamp.
+ -- Sampled operations are reweighted by 1/sample_rate so the rate reflects true volume;
+ -- events without the property coalesce to 1.0 (no sampling).
WITH weighted_events AS (
SELECT
event,
timestamp,
properties.operation AS operation,
+ coalesce(nullIf(properties.correlation_id, ''), '') AS correlation_id,
properties.outcome AS outcome,
1.0 / coalesce(toFloat(properties.sample_rate), 1.0) AS weight
FROM events
@@ -356,21 +360,50 @@ resource "posthog_insight" "slo_success_rate" {
AND properties.operation IN (${local.slo_operation_list})
AND timestamp >= now() - INTERVAL 56 DAY
),
- daily AS (
+ per_cid_day AS (
SELECT
- toDate(timestamp) AS date,
operation,
- sumIf(weight, event = 'slo_operation_started') AS total,
- greatest(
- sumIf(weight, event = 'slo_operation_started')
- - sumIf(weight, event = 'slo_operation_completed' AND outcome = 'success'),
- 0.0
- ) AS failures
+ correlation_id AS cid,
+ toDate(timestamp) AS event_date,
+ sumIf(weight, event = 'slo_operation_started') AS starts,
+ sumIf(weight, event = 'slo_operation_completed' AND outcome = 'success') AS successes,
+ -- One operation per cid, so all its events share a weight; max() collapses them.
+ max(weight) AS cid_weight,
+ min(if(event = 'slo_operation_started', timestamp, NULL)) AS first_start
FROM weighted_events
- GROUP BY date, operation
+ GROUP BY operation, cid, event_date
+ ),
+ daily AS (
+ SELECT operation, date, sum(total) AS total, sum(failures) AS failures
+ FROM (
+ -- Uncorrelated: starts/successes already weighted; 1 row per (operation, day).
+ SELECT
+ operation,
+ event_date AS date,
+ starts AS total,
+ greatest(starts - successes, 0.0) AS failures
+ FROM per_cid_day
+ WHERE cid = ''
+
+ UNION ALL
+
+ -- Correlated: collapse across days per (operation, cid), attribute to start day.
+ SELECT
+ operation,
+ toDate(min(first_start)) AS date,
+ max(cid_weight) AS total,
+ if(max(successes) > 0, 0.0, max(cid_weight)) AS failures
+ FROM per_cid_day
+ WHERE cid != ''
+ GROUP BY operation, cid
+ HAVING date IS NOT NULL
+ )
+ GROUP BY operation, date
),
date_range AS (
- SELECT toDate(now()) - number AS date FROM numbers(28)
+ -- 28 displayed days + 28 days of look-back so every displayed point has a full
+ -- 28-day rolling window (avoids the warm-up ramp at the left edge of the chart).
+ SELECT toDate(now()) - number AS date FROM numbers(56)
),
operations AS (
SELECT arrayJoin([${local.slo_operation_list}]) AS operation
@@ -398,6 +431,7 @@ resource "posthog_insight" "slo_success_rate" {
operation,
if(t28 > 0, round((t28 - f28) / t28 * 100, 2), NULL) AS success_rate
FROM rolling
+ WHERE date >= toDate(now()) - INTERVAL 27 DAY
ORDER BY date ASC, operation ASC
LIMIT ${local.slo_success_rate_limit}
SQL