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.

refactor(eng-analytics): reuse span and ownership helpers (#102393)

Raúl Negrón-Otero04bda4e7ebc8
diff --git a/products/engineering_analytics/backend/logic/job_logs/coordinator.py b/products/engineering_analytics/backend/logic/job_logs/coordinator.py
index fd12a132121a..81eeb32b7be1 100644
--- a/products/engineering_analytics/backend/logic/job_logs/coordinator.py
+++ b/products/engineering_analytics/backend/logic/job_logs/coordinator.py
@@ -5,7 +5,7 @@ job's log is fetched and emitted at most once, re-running only after a failed at
Discovery queries the raw ``{prefix}github_workflow_jobs`` table (the curated read layer doesn't
expose jobs yet). The coordinator is registered on the schedule but no-ops until
-``OTLP_LOGS_INGEST_ENDPOINT`` is set (see ``_discover_failed_jobs``), so it activates automatically
+``OTLP_LOGS_INGEST_ENDPOINT`` is set (see ``_discover_jobs_with_diagnostics``), so it activates automatically
once the Logs endpoint is deployed, regardless of deploy order.
"""
@@ -34,6 +34,7 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.common.base import PostHogWorkflow
from products.engineering_analytics.backend.logic.job_logs.activity import FetchGithubJobLogWorkflow, FetchJobLogInputs
+from products.engineering_analytics.backend.logic.queries._test_spans import rerun_recovered_job_attempts
from products.warehouse_sources.backend.facade.models import ExternalDataSource
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
@@ -52,7 +53,7 @@ _PREFIX = re.compile(r"^[A-Za-z0-9_]*$") # warehouse source prefixes; guards th
MAX_DISCOVERED_JOBS = 2000
-def _query_failed_jobs(team: Team, prefix: str, cutoff_iso: str, repo: str) -> list[dict[str, Any]]:
+def _query_jobs_with_diagnostics(team: Team, prefix: str, cutoff_iso: str, repo: str) -> list[dict[str, Any]]:
# Window on completed_at (when the job finished), not created_at: a queued or long-running job
# can be created well before it fails, and a created_at window would miss it. completed_at is an
# ISO-8601 string and is always set for a failed (completed) job, so a lexical comparison against
@@ -65,6 +66,13 @@ def _query_failed_jobs(team: Team, prefix: str, cutoff_iso: str, repo: str) -> l
# limit can never rise back into view and would be silently dropped. Matches
# MAX_DISCOVERED_JOBS; the high-water-mark cursor (deferred) removes the cap concern entirely.
# Run, attempt, and runner restrict successful-job downloads to runners with retry evidence.
+ recovered = rerun_recovered_job_attempts(
+ scan_from=f"""
+ SELECT min(parseDateTimeBestEffort(started_at))
+ FROM {table}
+ WHERE completed_at > {{cutoff}} AND conclusion = 'success'
+ """
+ )
sql = f"""
SELECT id AS job_id, run_id, head_branch AS branch, conclusion,
name AS job_name, workflow_name, run_attempt, head_sha
@@ -73,20 +81,7 @@ def _query_failed_jobs(team: Team, prefix: str, cutoff_iso: str, repo: str) -> l
conclusion = 'failure'
OR (
conclusion = 'success'
- AND (toString(run_id), toString(run_attempt), runner_name) IN (
- SELECT resource_attributes['ci.run_id'], resource_attributes['ci.run_attempt'],
- attributes['test.runner_name']
- FROM posthog.trace_spans
- WHERE service_name = 'ci-backend'
- AND lower(resource_attributes['ci.repository']) = lower({{repo}})
- AND timestamp >= (
- SELECT min(parseDateTimeBestEffort(started_at))
- FROM {table}
- WHERE completed_at > {{cutoff}} AND conclusion = 'success'
- )
- AND attributes['test.outcome'] = 'rerun_passed'
- AND notEmpty(coalesce(attributes['test.runner_name'], ''))
- )
+ AND (toString(run_id), toString(run_attempt), runner_name) IN ({recovered})
)
)
ORDER BY completed_at DESC
@@ -95,7 +90,8 @@ def _query_failed_jobs(team: Team, prefix: str, cutoff_iso: str, repo: str) -> l
with tags_context(product=Product.ENGINEERING_ANALYTICS, feature=Feature.QUERY, team_id=team.pk):
response = execute_hogql_query(
query=parse_select(
- sql, placeholders={"cutoff": ast.Constant(value=cutoff_iso), "repo": ast.Constant(value=repo)}
+ sql,
+ placeholders={"cutoff": ast.Constant(value=cutoff_iso), "repository": ast.Constant(value=repo)},
),
team=team,
query_type="GithubJobLogsDiscovery",
@@ -135,7 +131,7 @@ def _github_source_params(job_inputs: dict[str, Any] | None) -> tuple[int, str]
return None
-def _discover_failed_jobs(cutoff_iso: str) -> list[dict[str, Any]]:
+def _discover_jobs_with_diagnostics(cutoff_iso: str) -> list[dict[str, Any]]:
if not settings.OTLP_LOGS_INGEST_ENDPOINT:
# No Logs sink configured yet (charts sets the endpoint per region): discover nothing so the
# registered schedule is inert until the sink exists, then activates automatically. Mirrors
@@ -159,7 +155,7 @@ def _discover_failed_jobs(cutoff_iso: str) -> list[dict[str, Any]]:
try:
# Row handling stays inside the try so a single bad row (e.g. a null job_id) skips this
# source rather than failing discovery for every team.
- for row in _query_failed_jobs(source.team, prefix, cutoff_iso, repo):
+ for row in _query_jobs_with_diagnostics(source.team, prefix, cutoff_iso, repo):
job_id = row.get("job_id")
if job_id is None:
continue
@@ -210,7 +206,7 @@ def _discover_failed_jobs(cutoff_iso: str) -> list[dict[str, Any]]:
@activity.defn
async def discover_failed_jobs_activity(cutoff_iso: str) -> list[dict[str, Any]]:
"""Failed or retry-recovered CI jobs with a connected GitHub source, as FetchJobLogInputs dicts."""
- return await database_sync_to_async(_discover_failed_jobs, thread_sensitive=False)(cutoff_iso)
+ return await database_sync_to_async(_discover_jobs_with_diagnostics, thread_sensitive=False)(cutoff_iso)
@workflow.defn(name="github-job-logs-coordinator")
diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_coordinator.py b/products/engineering_analytics/backend/logic/job_logs/test/test_coordinator.py
index ddf5fb9c8ca8..efa166027c3a 100644
--- a/products/engineering_analytics/backend/logic/job_logs/test/test_coordinator.py
+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_coordinator.py
@@ -9,9 +9,9 @@ from parameterized import parameterized
from posthog.models.team import Team
from products.engineering_analytics.backend.logic.job_logs.coordinator import (
- _discover_failed_jobs,
+ _discover_jobs_with_diagnostics,
_github_source_params,
- _query_failed_jobs,
+ _query_jobs_with_diagnostics,
)
@@ -42,22 +42,22 @@ class TestGithubSourceParams:
assert _github_source_params(job_inputs) is None
-class TestDiscoverFailedJobs:
+class TestDiscoverJobsWithDiagnostics:
@override_settings(OTLP_LOGS_INGEST_ENDPOINT="")
def test_discovers_nothing_when_logs_endpoint_unset(self):
# The coordinator schedule is registered but must stay inert until the Logs endpoint is
# deployed: discovery returns [] (without querying the warehouse) so no child workflows fan
# out. Drops the guard and this fails by hitting the DB and returning rows.
- assert _discover_failed_jobs("2026-06-29T00:00:00+00:00") == []
+ assert _discover_jobs_with_diagnostics("2026-06-29T00:00:00+00:00") == []
-class TestQueryFailedJobs:
+class TestQueryJobsWithDiagnostics:
@patch("products.engineering_analytics.backend.logic.job_logs.coordinator.execute_hogql_query")
def test_bypasses_warehouse_access_control(self, mock_execute):
# The sweep runs with no request user, so without bypass HogQL marks the team's own
# workflow_jobs warehouse table denied and the query raises "You don't have access to table" —
# the worker then silently emits nothing. Locks in the bypass that makes the trusted query work.
mock_execute.return_value = SimpleNamespace(columns=["job_id"], results=[])
- _query_failed_jobs(Team(pk=1), "devex_", "2026-06-30T00:00:00+00:00", "PostHog/posthog")
+ _query_jobs_with_diagnostics(Team(pk=1), "devex_", "2026-06-30T00:00:00+00:00", "PostHog/posthog")
mock_execute.assert_called_once()
assert mock_execute.call_args.kwargs["bypass_warehouse_access_control"] is True
diff --git a/products/engineering_analytics/backend/logic/ownership.py b/products/engineering_analytics/backend/logic/ownership.py
index 9c1b491592a2..1e6433d238b0 100644
--- a/products/engineering_analytics/backend/logic/ownership.py
+++ b/products/engineering_analytics/backend/logic/ownership.py
@@ -33,7 +33,7 @@ _T = TypeVar("_T")
# The raw host serves a public repo's files off a CDN, so these reads draw on no GitHub API rate
# limit, and the HEAD ref follows the default branch. A private repo answers 404 to all of it, which
-# the root-file guard in _place catches.
+# the root-file guard in _read_root catches.
_RAW_HOST = "https://raw.githubusercontent.com"
_REF = "HEAD"
_EGRESS_SOURCE = "engineering_analytics_ownership"
@@ -216,15 +216,11 @@ def resolve_test_ownership(
def resolve_path_owners(repository: str, paths: Sequence[str], files: RepoFiles | None = None) -> PathOwnership:
- """Name the team that owns each repository path, and hand back the repo's Slack registry.
-
- The paths are resolved exactly as given. There is no candidate-path search: that exists because
- a test suite reports a path relative to its own root, and a caller who already holds a
- repo-relative path has nothing to guess at.
- """
+ """Name the team that owns each repository path, and return the repo's Slack registry. Paths must
+ be repo-relative: unlike reported test paths, they get no candidate-path search."""
reader = files if files is not None else GitHubRepoFiles(repository)
try:
- return _own_paths(repository, reader, list(dict.fromkeys(paths)))
+ return _own_paths(reader, _read_root(repository, reader), list(dict.fromkeys(paths)))
except NoRootOwnersFile:
# Most repositories declare no owners.yaml, so this is no error for a caller to act on.
logger.info("repo_path_ownership_no_root_file", repository=repository)
@@ -234,10 +230,14 @@ def resolve_path_owners(repository: str, paths: Sequence[str], files: RepoFiles
return PathOwnership(team_by_path=dict.fromkeys(paths, UNOWNED_TEAM), registry={}, resolved=False)
-def _own_paths(repository: str, files: RepoFiles, paths: list[str]) -> PathOwnership:
+def _read_root(repository: str, files: RepoFiles) -> str:
root = files.read(_ROOT_OWNERS_FILE)
if root is None:
raise NoRootOwnersFile(f"{repository} has no root {_ROOT_OWNERS_FILE}")
+ return root
+
+
+def _own_paths(files: RepoFiles, root: str, paths: list[str]) -> PathOwnership:
resolver = OwnersResolver(source=files)
files.read_all(resolver.ownership_file_paths(paths))
owners = resolver.map(paths)
@@ -249,22 +249,18 @@ def _own_paths(repository: str, files: RepoFiles, paths: list[str]) -> PathOwner
def _place(repository: str, files: RepoFiles, tests: list[QuarantinedTestFile]) -> list[PlacedTest]:
- if files.read(_ROOT_OWNERS_FILE) is None:
- # Every repo this runs against declares one, so its absence proves the reader is blind
- # (a private or renamed repo answers 404 to everything), not that nobody owns anything.
- raise OwnershipUnavailable(f"{repository} has no root {_ROOT_OWNERS_FILE}")
- resolver = OwnersResolver(source=files)
+ # Every repo this runs against declares one, so its absence proves the reader is blind
+ # (a private or renamed repo answers 404 to everything), not that nobody owns anything.
+ root = _read_root(repository, files)
candidates = [_candidate_paths(test) for test in tests]
present = files.exists_all([path for group in candidates for path in group])
placed = [next((path for path in group if present[path]), None) for group in candidates]
- found = [path for path in placed if path]
- files.read_all(resolver.ownership_file_paths(found))
- owners = resolver.map(found)
+ owned = _own_paths(files, root, [path for path in placed if path])
return [
PlacedTest(
# A Rust crate is placed by its manifest, which is not the test's file.
path="" if path is None or test.crate else path,
- owner_team=_team(owners[path].owners if path else None),
+ owner_team=owned.team_by_path[path] if path else UNOWNED_TEAM,
)
for test, path in zip(tests, placed, strict=True)
]
diff --git a/products/engineering_analytics/backend/logic/queries/_test_spans.py b/products/engineering_analytics/backend/logic/queries/_test_spans.py
index bc410213d746..c92b4a81b4cf 100644
--- a/products/engineering_analytics/backend/logic/queries/_test_spans.py
+++ b/products/engineering_analytics/backend/logic/queries/_test_spans.py
@@ -201,6 +201,24 @@ def scan_placeholders(
return placeholders
+def rerun_recovered_job_attempts(*, scan_from: str) -> str:
+ """``(run_id, run_attempt, runner_name)``, as strings, of every pytest job attempt whose in-process
+ retry recovered a test. That job concludes as a success, but its log still holds the failure.
+
+ ``scan_from`` is a HogQL expression for the earliest span to read. The caller binds ``{repository}``.
+ """
+ return f"""
+ SELECT resource_attributes['ci.run_id'], resource_attributes['ci.run_attempt'],
+ attributes['test.runner_name']
+ FROM posthog.trace_spans
+ WHERE service_name = '{PYTEST_CI_SERVICE_NAME}'
+ AND lower(resource_attributes['ci.repository']) = lower({{repository}})
+ AND timestamp >= ({scan_from})
+ AND attributes['test.outcome'] = 'rerun_passed'
+ AND notEmpty(coalesce(attributes['test.runner_name'], ''))
+ """
+
+
def selector_from_nodeid(nodeid: str) -> str:
"""Best-effort runnable pytest selector for a span the CI reporter emitted before it stamped
``test.selector``. The nodeid folds the file/class boundary into '/' and drops '.py'
diff --git a/products/engineering_analytics/backend/tests/test_flaky_tests.py b/products/engineering_analytics/backend/tests/test_flaky_tests.py
index 3158fc8c81f3..0e7315c1b137 100644
--- a/products/engineering_analytics/backend/tests/test_flaky_tests.py
+++ b/products/engineering_analytics/backend/tests/test_flaky_tests.py
@@ -9,7 +9,7 @@ from rest_framework import status
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.traces.spans import TRACE_SPANS_DISTRIBUTED_TABLE_SQL, TRACE_SPANS_TABLE_SQL
-from products.engineering_analytics.backend.logic.job_logs.coordinator import _query_failed_jobs
+from products.engineering_analytics.backend.logic.job_logs.coordinator import _query_jobs_with_diagnostics
from products.engineering_analytics.backend.logic.queries._test_spans import selector_from_nodeid
from products.engineering_analytics.backend.logic.views.source_schema import WORKFLOW_JOBS_COLUMNS
from products.engineering_analytics.backend.tests._github_fixtures import (
@@ -238,7 +238,7 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):
for job_id, run_id, attempt, runner, conclusion in jobs
],
)
- rows = _query_failed_jobs(
+ rows = _query_jobs_with_diagnostics(
self.team, GITHUB_SOURCE_PREFIX, (now - timedelta(hours=12)).isoformat(), "posthog/POSTHOG"
)
assert {row["job_id"] for row in rows} == {1, 5}