: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(devex): emit one CI trace per job instead of per workflow run (#64302)
Frank Hamand5749a1f18844
diff --git a/.github/scripts/report_test_timings.py b/.github/scripts/report_test_timings.pyindex 852bc778ff02..b6e7f84198ba 100644--- a/.github/scripts/report_test_timings.py+++ b/.github/scripts/report_test_timings.py@@ -11,15 +11,15 @@"""Emit OTLP traces from Backend CI JUnit XML artifacts.Reads `junit-results-*` artifacts (downloaded by the workflow) and emits one-trace per workflow run shaped:+trace per job (shard) shaped:- ci-backend (root)- └── <segment>-<group> (shard)- ├── <pytest nodeid> (test)- └── ...+ <workflow> / <job> (root, one trace per job)+ ├── <pytest nodeid> (test)+ └── ...-Trace ID is deterministic per (run_id, run_attempt) so each workflow attempt-gets its own trace. Failures and errors mark spans Status.ERROR.+Trace ID is deterministic per (run_id, run_attempt, job) so each job in each+workflow attempt gets its own trace. Failures and errors mark spans+Status.ERROR.This script must NEVER fail the workflow: any unexpected error is logged andthe process exits 0. The workflow job is also `continue-on-error: true` as a@@ -360,20 +360,24 @@ def workflow_resource_attributes() -> dict[str, str | int]:# ---------- OTLP export -----------def deterministic_trace_id(run_id: str, run_attempt: str) -> int:- """One trace ID per (run_id, run_attempt). Reruns of the same attempt collide intentionally."""- digest = hashlib.sha256(f"{run_id}:{run_attempt}".encode()).digest()+def deterministic_trace_id(run_id: str, run_attempt: str, job_key: str) -> int:+ """One trace ID per (run_id, run_attempt, job). Reruns of the same attempt collide intentionally."""+ digest = hashlib.sha256(f"{run_id}:{run_attempt}:{job_key}".encode()).digest()return int.from_bytes(digest[:16], "big") # OTLP trace IDs are 128-bit (16 bytes).class _FixedTraceIdGenerator(IdGenerator):- """Force every span in the run to share a deterministic trace ID."""+ """Force every span to share whatever trace ID is currently set.- def __init__(self, trace_id: int) -> None:- self._trace_id = trace_id+ `trace_id` is mutated between jobs so each job's root span (and its inherited+ test children) lands in its own trace while sharing one provider/exporter.+ """++ def __init__(self, trace_id: int = 0) -> None:+ self.trace_id = trace_iddef generate_trace_id(self) -> int:- return self._trace_id+ return self.trace_iddef generate_span_id(self) -> int:span_id = secrets.randbits(64)@@ -386,14 +390,26 @@ def _to_ns(dt: datetime) -> int:return int(dt.timestamp() * 1_000_000_000)+def job_trace_key(info: ArtifactInfo) -> str:+ """Stable per-job identity; folds into the trace ID so each job is its own trace."""+ return f"{info.suite}:{info.segment}:{info.group}"+++def job_trace_name(workflow: str, info: ArtifactInfo) -> str:+ """Human trace name `<workflow> / <job>` derived from the artifact, e.g. `Backend CI / core (29)`."""+ job = f"{info.segment} ({info.group})" if info.group is not None else info.segment+ return f"{workflow} / {job}"++def emit_traces(shards: list[Shard], endpoint: str, token: str) -> None:- """Build root → shard → test span hierarchy and ship via OTLP HTTP."""+ """Emit one trace per job: a `<workflow> / <job>` root span with test children, shipped via OTLP HTTP."""run_id = os.environ.get("GITHUB_RUN_ID", "0")run_attempt = os.environ.get("GITHUB_RUN_ATTEMPT", "1")- trace_id = deterministic_trace_id(run_id, run_attempt)+ workflow = os.environ.get("GITHUB_WORKFLOW", "") or SERVICE_NAME+ id_generator = _FixedTraceIdGenerator()resource = Resource.create({"service.name": SERVICE_NAME, **workflow_resource_attributes()})- provider = TracerProvider(resource=resource, id_generator=_FixedTraceIdGenerator(trace_id))+ provider = TracerProvider(resource=resource, id_generator=id_generator)exporter = OTLPSpanExporter(endpoint=endpoint, headers={"Authorization": f"Bearer {token}"})provider.add_span_processor(BatchSpanProcessor(exporter, max_export_batch_size=SPAN_BATCH_SIZE))tracer = provider.get_tracer(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION)@@ -402,26 +418,19 @@ def emit_traces(shards: list[Shard], endpoint: str, token: str) -> None:provider.shutdown()return- root_start = min(s.start for s in shards)- root_end = max(s.end for s in shards)- root_span = tracer.start_span(SERVICE_NAME, start_time=_to_ns(root_start))- root_has_error = False- with trace.use_span(root_span, end_on_exit=False):- for shard in shards:- if _emit_shard_span(tracer, shard):- root_has_error = True-- if root_has_error:- root_span.set_status(Status(StatusCode.ERROR))- root_span.end(end_time=_to_ns(root_end))+ for shard in shards:+ # Mutate the shared generator before each job so its root span (and the test+ # children that inherit the active parent's trace ID) form a distinct trace.+ id_generator.trace_id = deterministic_trace_id(run_id, run_attempt, job_trace_key(shard.info))+ _emit_shard_span(tracer, shard, job_trace_name(workflow, shard.info))+provider.shutdown()-def _emit_shard_span(tracer: trace.Tracer, shard: Shard) -> bool:- """Emit shard span and its test children. Returns True iff any child has Error."""+def _emit_shard_span(tracer: trace.Tracer, shard: Shard, root_name: str) -> bool:+ """Emit the job's root span and its test children. Returns True iff any child has Error."""info = shard.info- shard_name = f"{info.segment}-{info.group}" if info.group is not None else info.segment- shard_span = tracer.start_span(shard_name, start_time=_to_ns(shard.start))+ shard_span = tracer.start_span(root_name, start_time=_to_ns(shard.start))shard_span.set_attribute("shard.suite", info.suite)shard_span.set_attribute("shard.segment", info.segment)if info.group is not None:diff --git a/.github/scripts/test_report_test_timings.py b/.github/scripts/test_report_test_timings.pyindex c4fa7272051d..ea350ad4970f 100644--- a/.github/scripts/test_report_test_timings.py+++ b/.github/scripts/test_report_test_timings.py@@ -316,10 +316,10 @@ def test_emit_shard_span_uses_stored_test_windows(monkeypatch: pytest.MonkeyPatctracer = _FakeTracer()monkeypatch.setattr(report_test_timings.trace, "use_span", _noop_use_span)- has_error = report_test_timings._emit_shard_span(tracer, shard)+ has_error = report_test_timings._emit_shard_span(tracer, shard, "Backend CI / core (1)")assert has_error is True- assert [span.name for span in tracer.spans] == ["core-1", "m::slow", "m::fail"]+ assert [span.name for span in tracer.spans] == ["Backend CI / core (1)", "m::slow", "m::fail"]assert tracer.spans[0].attributes["shard.setup_seconds"] == 0.0assert tracer.spans[1].start_time == report_test_timings._to_ns(start + timedelta(seconds=0.1))assert tracer.spans[1].end_time == report_test_timings._to_ns(start + timedelta(seconds=2.1))@@ -353,9 +353,9 @@ def test_emit_shard_span_emits_setup_span_when_setup_seconds_positive(monkeypatctracer = _FakeTracer()monkeypatch.setattr(report_test_timings.trace, "use_span", _noop_use_span)- report_test_timings._emit_shard_span(tracer, shard)+ report_test_timings._emit_shard_span(tracer, shard, "Backend CI / core (1)")- assert [span.name for span in tracer.spans] == ["core-1", "setup", "m::slow"]+ assert [span.name for span in tracer.spans] == ["Backend CI / core (1)", "setup", "m::slow"]setup_span = tracer.spans[1]assert setup_span.start_time == report_test_timings._to_ns(start)assert setup_span.end_time == report_test_timings._to_ns(start + timedelta(seconds=3.5))@@ -392,10 +392,40 @@ def test_workflow_resource_attributes_includes_query_and_drilldown_fields(def test_deterministic_trace_id_is_stable_across_processes() -> None:- a = report_test_timings.deterministic_trace_id("25218527467", "1")- b = report_test_timings.deterministic_trace_id("25218527467", "1")+ a = report_test_timings.deterministic_trace_id("25218527467", "1", "backend:core:1")+ b = report_test_timings.deterministic_trace_id("25218527467", "1", "backend:core:1")assert a == b# Different attempt -> different trace id (so reruns of the same workflow run id are isolated).- assert report_test_timings.deterministic_trace_id("25218527467", "2") != a+ assert report_test_timings.deterministic_trace_id("25218527467", "2", "backend:core:1") != a+ # Different job -> different trace id (so each job in a run is its own trace).+ assert report_test_timings.deterministic_trace_id("25218527467", "1", "backend:core:2") != a# Result fits in 128 bits.assert 0 <= a < 2**128+++# ---------- per-job trace naming ----------+++def _artifact(suite: str, segment: str, group: int | None) -> report_test_timings.ArtifactInfo: # type: ignore[name-defined]+ return report_test_timings.ArtifactInfo(+ path=Path(f"junit-results-{suite}"), suite=suite, segment=segment, group=group, total=None+ )+++ "suite,segment,group,expected",+ [+ ("backend", "core", 29, "Backend CI / core (29)"),+ ("backend", "temporal", 1, "Backend CI / temporal (1)"),+ ("async-migrations", "async-migrations", None, "Backend CI / async-migrations"),+ ],+)+def test_job_trace_name(suite: str, segment: str, group: int | None, expected: str) -> None:+ assert report_test_timings.job_trace_name("Backend CI", _artifact(suite, segment, group)) == expected+++def test_job_trace_key_distinguishes_jobs() -> None:+ key = report_test_timings.job_trace_key+ assert key(_artifact("backend", "core", 1)) != key(_artifact("backend", "core", 2))+ assert key(_artifact("backend", "core", 1)) != key(_artifact("backend", "temporal", 1))+ assert key(_artifact("backend", "core", 1)) == key(_artifact("backend", "core", 1))