: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(eng-analytics): daily test ownership census task (#92561)
Raúl Negrón-Otero2bfa7fa5e454
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 1958e16be7ca..09ae82067bb7 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -86,6 +86,7 @@ from products.data_warehouse.backend.facade.tasks import (send_external_data_failure_digest_catchup,)from products.endpoints.backend.facade.tasks import deactivate_stale_materializations+from products.engineering_analytics.backend.facade.tasks import TEST_CENSUS_CRONTAB, emit_test_ownership_censusfrom products.feature_flags.backend.tasks import (cleanup_stale_flag_definitions_expiry_tracking_task,cleanup_stale_flags_expiry_tracking_task,@@ -992,6 +993,13 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="prune old streamlit app versions",)+ # Engineering analytics daily test-ownership census fan-out.+ sender.add_periodic_task(+ TEST_CENSUS_CRONTAB,+ emit_test_ownership_census.s(),+ name="engineering analytics daily test ownership census",+ )+# Stamphog daily merged-PR digest fan-out.sender.add_periodic_task(DAILY_DIGEST_CRONTAB,diff --git a/products/engineering_analytics/backend/facade/tasks.py b/products/engineering_analytics/backend/facade/tasks.pynew file mode 100644index 000000000000..3cf9400c47fc--- /dev/null+++ b/products/engineering_analytics/backend/facade/tasks.py@@ -0,0 +1,12 @@+"""Celery wiring facade: the tasks and schedules core registers for this product.++Kept separate from ``api.py`` so beat registration does not import the read layer.+"""++from products.engineering_analytics.backend.tasks.schedules import TEST_CENSUS_CRONTAB+from products.engineering_analytics.backend.tasks.tasks import emit_test_ownership_census++__all__ = [+ "TEST_CENSUS_CRONTAB",+ "emit_test_ownership_census",+]diff --git a/products/engineering_analytics/backend/logic/census.py b/products/engineering_analytics/backend/logic/census.pynew file mode 100644index 000000000000..1dba964aa14b--- /dev/null+++ b/products/engineering_analytics/backend/logic/census.py@@ -0,0 +1,89 @@+"""Static test-file census of a connected repo, resolved through its owners.yaml map.++One tarball request per repo per run (the stream carries both the path list and the+ownership files), captured as one ``eng_analytics_test_census`` event per owning team+into the team's own project.+"""++import shutil+import tarfile+import tempfile+import posixpath+from contextlib import closing+from pathlib import Path++from posthog_owners import TeamTestCensus, census, runner_for_path++from posthog.api.capture import capture_batch_internal+from posthog.egress.github.transport import github_request, raise_if_github_rate_limited+from posthog.models.integration.github import _is_safe_github_repo_path+from posthog.models.team import Team++CENSUS_EVENT = "eng_analytics_test_census"+_GITHUB_API = "https://api.github.com"+# owners.yaml and product.yaml are hand-written config; anything bigger is not one.+_MAX_OWNERSHIP_FILE_BYTES = 512 * 1024+_OWNERSHIP_BASENAMES = {"owners.yaml", "product.yaml"}+++def collect_repo_census(repository: str, access_token: str, *, timeout: int = 300) -> list[TeamTestCensus]:+ """Stream the repo tarball once, keeping only test-file paths and the ownership files."""+ if not _is_safe_github_repo_path(repository):+ raise ValueError(f"Unsafe GitHub repo path: {repository!r}")+ url = f"{_GITHUB_API}/repos/{repository}/tarball"+ with tempfile.TemporaryDirectory(prefix="owners-census-") as tmp:+ root = Path(tmp)+ test_paths: list[str] = []+ with closing(+ github_request(+ "GET",+ url,+ source="owners_census",+ headers={"Authorization": f"Bearer {access_token}"},+ timeout=timeout,+ allow_redirects=True,+ stream=True,+ )+ ) as response:+ raise_if_github_rate_limited(response)+ response.raise_for_status()+ response.raw.decode_content = True+ with tarfile.open(fileobj=response.raw, mode="r|gz") as archive:+ for member in archive:+ if not member.isfile():+ continue+ # GitHub prefixes every entry with `<owner>-<repo>-<sha>/`.+ rel = member.name.split("/", 1)[1] if "/" in member.name else ""+ if not rel or rel != posixpath.normpath(rel) or rel.startswith(("../", "/")):+ continue+ if runner_for_path(rel) is not None:+ test_paths.append(rel)+ if posixpath.basename(rel) not in _OWNERSHIP_BASENAMES:+ continue+ if member.size > _MAX_OWNERSHIP_FILE_BYTES:+ continue+ extracted = archive.extractfile(member)+ if extracted is None:+ continue+ target = root / rel+ target.parent.mkdir(parents=True, exist_ok=True)+ with target.open("wb") as handle:+ shutil.copyfileobj(extracted, handle)+ return census(test_paths, root)+++def emit_census_events(team: Team, repository: str, rows: list[TeamTestCensus]) -> None:+ result = capture_batch_internal(+ events=[+ {+ "event": CENSUS_EVENT,+ "distinct_id": f"eng_analytics_census:{repository}",+ "properties": {"repository": repository, **row.as_payload()},+ }+ for row in rows+ ],+ token=team.api_token,+ event_source="engineering_analytics_census",+ process_person_profile=False,+ )+ result.raise_for_status()diff --git a/products/engineering_analytics/backend/tasks/__init__.py b/products/engineering_analytics/backend/tasks/__init__.pyindex e69de29bb2d1..4f7cb1498390 100644--- a/products/engineering_analytics/backend/tasks/__init__.py+++ b/products/engineering_analytics/backend/tasks/__init__.py@@ -0,0 +1 @@+from products.engineering_analytics.backend.tasks import tasks # noqa: F401diff --git a/products/engineering_analytics/backend/tasks/schedules.py b/products/engineering_analytics/backend/tasks/schedules.pyindex 1e5fe997e719..a4f5cf33d3e9 100644--- a/products/engineering_analytics/backend/tasks/schedules.py+++ b/products/engineering_analytics/backend/tasks/schedules.py@@ -1 +1,9 @@-"""Celery beat schedules for engineering_analytics."""+"""Celery beat schedules for engineering_analytics.++Not auto-collected: posthog/tasks/scheduled.py imports these constants through the facade+and registers them explicitly.+"""++from celery.schedules import crontab++TEST_CENSUS_CRONTAB = crontab(hour="6", minute="45")diff --git a/products/engineering_analytics/backend/tasks/tasks.py b/products/engineering_analytics/backend/tasks/tasks.pyindex 93160cfebba5..c65af45af5e7 100644--- a/products/engineering_analytics/backend/tasks/tasks.py+++ b/products/engineering_analytics/backend/tasks/tasks.py@@ -1 +1,53 @@"""Celery tasks for engineering_analytics."""++import structlog+from celery import shared_task++from posthog.egress.limiter.policies import Priority+from posthog.models.integration.github import GitHubIntegration+from posthog.models.scoping import with_team_scope+from posthog.models.team import Team+from posthog.scoping_audit import skip_team_scope_audit++from products.engineering_analytics.backend.logic.census import collect_repo_census, emit_census_events+from products.engineering_analytics.backend.logic.sources import list_github_sources+from products.warehouse_sources.backend.facade.models import ExternalDataSource+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType++logger = structlog.get_logger(__name__)+++@shared_task(ignore_result=True)+# Fan-out across every team with a GitHub source: cross-team by design, and the model still+# uses a plain manager, so there is no unscoped() to declare it with.+@skip_team_scope_audit+def emit_test_ownership_census() -> None:+ team_ids = (+ ExternalDataSource.objects.filter(source_type=ExternalDataSourceType.GITHUB, deleted=False)+ .values_list("team_id", flat=True)+ .distinct()+ )+ for team_id in team_ids:+ emit_team_test_census.delay(team_id=team_id)+++@shared_task(ignore_result=True)+@with_team_scope()+def emit_team_test_census(team_id: int) -> None:+ team = Team.objects.get(id=team_id)+ seen_repos: set[str] = set()+ for source in list_github_sources(team=team, user_access_control=None):+ # Unsynced sources have no resolvable repository for the roster query, so their+ # events would be unreadable; two sources on one repo would double the tarball fetch.+ if not source.repo or not source.synced or source.repo in seen_repos:+ continue+ seen_repos.add(source.repo)+ integration = GitHubIntegration.first_for_team_repository(+ team.id, source.repo, source="owners_census", priority=Priority.BATCH+ )+ token = integration.installation_access_token if integration else None+ if not token:+ logger.info("owners_census_skipped_no_integration", team_id=team_id, repository=source.repo)+ continue+ rows = collect_repo_census(source.repo, token)+ emit_census_events(team, source.repo, rows)diff --git a/products/engineering_analytics/backend/tests/test_census.py b/products/engineering_analytics/backend/tests/test_census.pynew file mode 100644index 000000000000..ece87d16ec4a--- /dev/null+++ b/products/engineering_analytics/backend/tests/test_census.py@@ -0,0 +1,84 @@+import io+import tarfile+from types import SimpleNamespace++from unittest.mock import patch++from posthog_owners import TeamTestCensus++from products.engineering_analytics.backend.logic.census import CENSUS_EVENT, collect_repo_census, emit_census_events+++def _tarball(files: dict[str, bytes]) -> bytes:+ buffer = io.BytesIO()+ with tarfile.open(fileobj=buffer, mode="w:gz") as archive:+ for name, content in files.items():+ info = tarfile.TarInfo(name=name)+ info.size = len(content)+ archive.addfile(info, io.BytesIO(content))+ return buffer.getvalue()+++class _RawBody(io.BytesIO):+ decode_content = False+++class _FakeTarballResponse:+ status_code = 200+ headers: dict[str, str] = {}++ def __init__(self, body: bytes) -> None:+ self.raw = _RawBody(body)++ def raise_for_status(self) -> None:+ pass++ def close(self) -> None:+ pass+++def test_collect_repo_census_strips_the_tarball_prefix_and_ignores_traversal_members() -> None:+ body = _tarball(+ {+ "PostHog-posthog-abc123/owners.yaml": b"version: 1\nowners: []\n",+ "PostHog-posthog-abc123/products/a/owners.yaml": b"version: 1\nowners: [team-a]\n",+ "PostHog-posthog-abc123/products/a/test_api.py": b"",+ "PostHog-posthog-abc123/products/a/thing.test.tsx": b"",+ "PostHog-posthog-abc123/posthog/test_uncovered.py": b"",+ "PostHog-posthog-abc123/../escape/test_evil.py": b"",+ }+ )+ with patch(+ "products.engineering_analytics.backend.logic.census.github_request",+ return_value=_FakeTarballResponse(body),+ ):+ rows = collect_repo_census("PostHog/posthog", "token")++ assert [(r.owner_team, r.pytest_file_count, r.jest_file_count) for r in rows] == [+ ("team-a", 1, 1),+ ("unowned", 1, 0),+ ]+++def test_emit_census_events_captures_the_contract_layer_4_reads() -> None:+ team = SimpleNamespace(api_token="phc_test")+ rows = [TeamTestCensus(owner_team="team-a", pytest_file_count=1, jest_file_count=0)]++ with patch("products.engineering_analytics.backend.logic.census.capture_batch_internal") as capture:+ emit_census_events(team, "PostHog/posthog", rows) # type: ignore[arg-type]++ kwargs = capture.call_args.kwargs+ assert kwargs["token"] == "phc_test"+ assert kwargs["events"] == [+ {+ "event": CENSUS_EVENT,+ "distinct_id": "eng_analytics_census:PostHog/posthog",+ "properties": {+ "repository": "PostHog/posthog",+ "owner_team": "team-a",+ "pytest_file_count": 1,+ "jest_file_count": 0,+ "test_file_count": 1,+ },+ }+ ]diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex 91b95d8f222f..a9cf8412ba6e 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -813,6 +813,7 @@ warehouse_sources.ExternalDataSource products.engineering_analytics.backend.logiwarehouse_sources.ExternalDataSource products.engineering_analytics.backend.logic.sources instance-many(order_by) 1warehouse_sources.ExternalDataSource products.engineering_analytics.backend.management.commands.seed_engineering_analytics instance-single 1warehouse_sources.ExternalDataSource products.engineering_analytics.backend.management.commands.seed_engineering_analytics write(create) 1+warehouse_sources.ExternalDataSource products.engineering_analytics.backend.tasks.tasks instance-many(distinct) 1warehouse_sources.ExternalDataSource products.managed_warehouse.backend.logic.connection instance-many(exclude) 1warehouse_sources.ExternalDataSource products.managed_warehouse.backend.logic.connection instance-many(filter) 1warehouse_sources.ExternalDataSource products.managed_warehouse.backend.logic.connection write(create) 1