: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(engineering_analytics): stop OTLP crash dropping all CI job logs (#67003)
Julian Bezc7d973684c66
diff --git a/products/engineering_analytics/backend/logic/job_logs/activity.py b/products/engineering_analytics/backend/logic/job_logs/activity.pyindex a7a304cfe0da..4b4bf11bd041 100644--- a/products/engineering_analytics/backend/logic/job_logs/activity.py+++ b/products/engineering_analytics/backend/logic/job_logs/activity.py@@ -85,7 +85,10 @@ async def fetch_and_emit_job_log_activity(inputs: FetchJobLogInputs) -> dict[str# Failures-only today; pass a different ThinningConfig once all-jobs ingestion lands.thinned = thin_log(archive)with JobLogsEmitter(endpoint=settings.OTLP_LOGS_INGEST_ENDPOINT, token=log_ingest_token) as emitter:- return emitter.emit_log_archive(thinned, attributes=attributes)+ # run_id→trace, job_id→span so the Logs UI can group a whole run and isolate one job.+ return emitter.emit_log_archive(+ thinned, attributes=attributes, trace_id=inputs.run_id, span_id=inputs.job_id+ )lines = await asyncio.to_thread(_thin_and_emit)log.info("github_job_log_emitted", lines=lines)diff --git a/products/engineering_analytics/backend/logic/job_logs/emitter.py b/products/engineering_analytics/backend/logic/job_logs/emitter.pyindex a396177385f9..fdea901b6827 100644--- a/products/engineering_analytics/backend/logic/job_logs/emitter.py+++ b/products/engineering_analytics/backend/logic/job_logs/emitter.py@@ -20,6 +20,7 @@ from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporterfrom opentelemetry.sdk._logs import LoggerProvider, LogRecordfrom opentelemetry.sdk._logs.export import BatchLogRecordProcessor, LogExporterfrom opentelemetry.sdk.resources import Resource+from opentelemetry.trace import TraceFlagslogger = structlog.get_logger(__name__)@@ -52,6 +53,21 @@ def _severity(body: str) -> tuple[str, SeverityNumber]:return "INFO", SeverityNumber.INFO+def _otel_id(value: str | int | None, n_bytes: int) -> int:+ """A GitHub run/job id packed as an OTLP trace/span id — an int the encoder serializes into+ ``n_bytes``. GitHub ids arrive as int or numeric string (warehouse columns are nullable strings),+ so coerce; return 0 (OTLP "unset") when missing, non-numeric, or out of range. Never None — the+ SDK default — and never a str: either would crash serialization of the whole batch.+ """+ if value is None:+ return 0+ try:+ parsed = int(value)+ except (TypeError, ValueError):+ return 0+ return parsed if 0 < parsed < (1 << (n_bytes * 8)) else 0++class JobLogsEmitter:"""One record per line into Logs. Use as a context manager so the batch flushes on exit. Pass``endpoint`` + ``token`` for production, ``exporter`` in tests; with neither it's a safe no-op@@ -71,11 +87,25 @@ class JobLogsEmitter:logger.warning("github_ci_logs_emit_disabled", detail="no endpoint/token configured; skipping export")self._logger = self._provider.get_logger(_SERVICE_NAME)- def emit_log_archive(self, archive_text: str, *, attributes: Mapping[str, object]) -> int:- """Emit one Logs record per non-empty line. Returns the number of records emitted."""+ def emit_log_archive(+ self,+ archive_text: str,+ *,+ attributes: Mapping[str, object],+ trace_id: str | int | None = 0,+ span_id: str | int | None = 0,+ ) -> int:+ """Emit one Logs record per non-empty line. Returns the number of records emitted.++ ``trace_id``/``span_id`` map the GitHub run/job onto OTLP trace/span so the Logs UI can group+ a whole workflow run (trace) and isolate one job (span); unmappable ids fall back to 0+ (unset). They MUST be set: the encoder treats 0 as unset and calls ``int(trace_flags)``, so+ the SDK's None default would crash serialization of the whole batch and nothing would land.+ """if not self._enabled:return 0attrs = {key: value for key, value in attributes.items() if isinstance(value, _SCALAR)}+ trace, span = _otel_id(trace_id, 16), _otel_id(span_id, 8)emitted = 0for raw in archive_text.splitlines():match = _LINE.match(raw)@@ -87,6 +117,9 @@ class JobLogsEmitter:LogRecord(timestamp=timestamp,observed_timestamp=timestamp,+ trace_id=trace,+ span_id=span,+ trace_flags=TraceFlags(TraceFlags.DEFAULT),severity_text=severity_text,severity_number=severity_number,body=body,diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_job_logs_emitter.py b/products/engineering_analytics/backend/logic/job_logs/test/test_job_logs_emitter.pyindex e086d0422ec8..33c6f0930a6e 100644--- a/products/engineering_analytics/backend/logic/job_logs/test/test_job_logs_emitter.py+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_job_logs_emitter.py@@ -1,6 +1,8 @@from datetime import UTC, datetime+from opentelemetry.exporter.otlp.proto.common._internal._log_encoder import encode_logsfrom opentelemetry.sdk._logs.export import InMemoryLogExporter+from parameterized import parameterizedfrom products.engineering_analytics.backend.logic.job_logs.emitter import JobLogsEmitter@@ -14,6 +16,43 @@ def _emit(archive: str, attributes=_ATTRS):return emitted, [d.log_record for d in exporter.get_finished_logs()]+def _encode_one(*, trace_id, span_id):+ exporter = InMemoryLogExporter()+ with JobLogsEmitter(exporter=exporter) as emitter:+ emitter.emit_log_archive(+ "2026-06-25T09:14:02.000000Z ##[error]boom", attributes=_ATTRS, trace_id=trace_id, span_id=span_id+ )+ encoded = encode_logs(exporter.get_finished_logs()) # must not raise+ return encoded.resource_logs[0].scope_logs[0].log_records[0]+++def test_run_and_job_ids_encode_as_trace_and_span():+ # Production ships via the real OTLP HTTP exporter, which protobuf-encodes each batch — the step+ # InMemoryLogExporter skips. The encoder treats trace/span == 0 as "unset" and calls+ # int(trace_flags); leaving them None (the SDK default) or passing a str (run_id is a nullable+ # warehouse column, often numeric string) raises in encode_logs and silently drops the whole+ # batch. This asserts a string run/job id coerces and round-trips into the right-width bytes.+ record = _encode_one(trace_id="7", span_id="42")+ assert record.body.string_value == "##[error]boom"+ assert record.trace_id == (7).to_bytes(16, "big")+ assert record.span_id == (42).to_bytes(8, "big")+++ [+ ("missing", None, None),+ ("non_numeric", "abc", "xyz"),+ ("out_of_range", 1 << 128, 1 << 64), # too wide for trace (16B) / span (8B)+ ]+)+def test_unmappable_ids_fall_back_to_unset(_name, trace_id, span_id):+ # Bad/oversized ids must encode as unset (empty bytes), never crash the batch — int.to_bytes on+ # an over-width id raises OverflowError, and a non-numeric str has no to_bytes at all.+ record = _encode_one(trace_id=trace_id, span_id=span_id)+ assert record.trace_id == b""+ assert record.span_id == b""++def test_emits_per_line_with_parsed_timestamp_severity_and_attributes():# The core contract: one record per line, GitHub timestamp parsed (so build order is kept),# severity derived from ##[error]/##[warning], job attributes attached. A regression in the