: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(engineering-analytics): add GitHub CI job-logs worker (fetch + emit to Logs) (#66245)
Julian Bez3bb0cadff494
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex 30199a13dc95..56f4cff6f177 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -342,7 +342,7 @@ jobs:- name: Check for changes that affect general purpose temporal workerid: check_changes_general_purpose_temporal_workerrun: |- if git diff --name-only HEAD^ HEAD | grep -qE '^products/exports/backend/temporal/subscriptions|^products/experiments/backend/temporal/|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/(ai_observability|llm_analytics)|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/delete_teams|^posthog/temporal/ingestion_acceptance_test|^posthog/temporal/backfill_group_type_created_at|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then+ if git diff --name-only HEAD^ HEAD | grep -qE '^products/exports/backend/temporal/subscriptions|^products/experiments/backend/temporal/|^products/engineering_analytics/backend/logic/job_logs/|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/(ai_observability|llm_analytics)|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/delete_teams|^posthog/temporal/ingestion_acceptance_test|^posthog/temporal/backfill_group_type_created_at|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; thenecho "changed=true" >> $GITHUB_OUTPUTelseecho "changed=false" >> $GITHUB_OUTPUTdiff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 0a4193428d8c..f9a00240c470 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -177,6 +177,7 @@ from products.conversations.backend.temporal import (ACTIVITIES as CONVERSATIONS_ACTIVITIES,WORKFLOWS as CONVERSATIONS_WORKFLOWS,)+from products.engineering_analytics.backend.facade.temporal import JOB_LOGS_ACTIVITIES, JOB_LOGS_WORKFLOWSfrom products.error_tracking.backend.facade.temporal import (ACTIVITIES as ERROR_TRACKING_ACTIVITIES,WORKFLOWS as ERROR_TRACKING_WORKFLOWS,@@ -272,7 +273,8 @@ _task_queue_specs = [+ BACKFILL_GROUP_TYPE_CREATED_AT_WORKFLOWS+ INGESTION_ACCEPTANCE_TEST_WORKFLOWS+ WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS- + SYNC_EVENTS_RETENTION_WORKFLOWS,+ + SYNC_EVENTS_RETENTION_WORKFLOWS+ + JOB_LOGS_WORKFLOWS,PROXY_SERVICE_ACTIVITIES+ DELETE_PERSONS_ACTIVITIES+ DELETE_TEAMS_ACTIVITIES@@ -288,7 +290,8 @@ _task_queue_specs = [+ BACKFILL_GROUP_TYPE_CREATED_AT_ACTIVITIES+ INGESTION_ACCEPTANCE_TEST_ACTIVITIES+ WAREHOUSE_SOURCES_QUEUE_PARTITION_ACTIVITIES- + SYNC_EVENTS_RETENTION_ACTIVITIES,+ + SYNC_EVENTS_RETENTION_ACTIVITIES+ + JOB_LOGS_ACTIVITIES,),(settings.HEALTH_CHECK_TASK_QUEUE,diff --git a/posthog/settings/ingestion.py b/posthog/settings/ingestion.pyindex 336621999f56..be3e1b218a03 100644--- a/posthog/settings/ingestion.py+++ b/posthog/settings/ingestion.py@@ -53,6 +53,12 @@ REPLAY_CAPTURE_ENDPOINT = os.getenv("REPLAY_CAPTURE_ENDPOINT", "/s/")CAPTURE_INTERNAL_URL = os.getenv("CAPTURE_INTERNAL_URL", "http://localhost:8010")CAPTURE_REPLAY_INTERNAL_URL = os.getenv("CAPTURE_REPLAY_INTERNAL_URL", "http://localhost:8010")++# Internal OTLP/HTTP endpoint for first-party log emission into Logs (the `capture-logs` service,+# path `/i/v1/logs`). The OTLP Bearer (a project token) routes records to a team's Logs. Defaults to+# empty = emission disabled (the activity skips/raises rather than shipping to the wrong place); set+# per-region via charts in prod, and to the local capture proxy when testing locally.+OTLP_LOGS_INGEST_ENDPOINT = os.getenv("OTLP_LOGS_INGEST_ENDPOINT", "")# Thread-pool size for capture_internal batch chunk fan-out (default 8, was per-event fan-out pre-v1).CAPTURE_INTERNAL_MAX_WORKERS = get_from_env("CAPTURE_INTERNAL_MAX_WORKERS", type_cast=int, default=8)diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex e2db363f8b64..63d57f960edb 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -75,6 +75,7 @@ from posthog.temporal.weekly_digest.types import WeeklyDigestInputfrom products.business_knowledge.backend.temporal.schedule import create_business_knowledge_refresh_coordinator_schedulefrom products.conversations.backend.temporal.schedule import create_support_reply_coordinator_schedule+from products.engineering_analytics.backend.facade.temporal import create_github_job_logs_coordinator_schedulefrom products.error_tracking.backend.facade.temporal import (RecommendationsRefreshInputs,create_error_tracking_spike_event_cleanup_schedule,@@ -734,6 +735,7 @@ schedules = [create_replay_vision_reconciler_schedule,create_replay_vision_estimates_schedule,create_evaluate_code_workstreams_schedule,+ create_github_job_logs_coordinator_schedule,]if settings.CLOUD_DEPLOYMENT:diff --git a/products/engineering_analytics/backend/facade/temporal.py b/products/engineering_analytics/backend/facade/temporal.pynew file mode 100644index 000000000000..5773030e54c8--- /dev/null+++ b/products/engineering_analytics/backend/facade/temporal.py@@ -0,0 +1,19 @@+"""Temporal wiring exposed across the product boundary.++Core registers these on the general-purpose worker and the schedule registry — see+``posthog/management/commands/start_temporal_worker.py`` and ``posthog/temporal/schedule.py``. The+internals live under ``backend/logic/job_logs/`` (isolated); this facade is the only import surface+core may use.+"""++from products.engineering_analytics.backend.logic.job_logs.schedule import create_github_job_logs_coordinator_schedule+from products.engineering_analytics.backend.logic.job_logs.temporal import (+ ACTIVITIES as JOB_LOGS_ACTIVITIES,+ WORKFLOWS as JOB_LOGS_WORKFLOWS,+)++__all__ = [+ "JOB_LOGS_ACTIVITIES",+ "JOB_LOGS_WORKFLOWS",+ "create_github_job_logs_coordinator_schedule",+]diff --git a/products/engineering_analytics/backend/logic/job_logs/__init__.py b/products/engineering_analytics/backend/logic/job_logs/__init__.pynew file mode 100644index 000000000000..01618f5eb003--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/__init__.py@@ -0,0 +1,9 @@+"""Fetch GitHub Actions failure logs and ship them into the Logs product.++A scheduled coordinator finds recently-failed CI jobs, and a per-job workflow fetches each job's+log from GitHub (under the shared egress limiter) and emits it line-by-line into the Logs product.+"""++from products.engineering_analytics.backend.logic.job_logs.emitter import JobLogsEmitter++__all__ = ["JobLogsEmitter"]diff --git a/products/engineering_analytics/backend/logic/job_logs/activity.py b/products/engineering_analytics/backend/logic/job_logs/activity.pynew file mode 100644index 000000000000..a7a304cfe0da--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/activity.py@@ -0,0 +1,112 @@+"""Fetch one GitHub Actions job log under the shared egress budget and emit it into Logs.++Returns small counts only; the log content never flows back through the workflow (Temporal's payload+limit). A budget denial raises so Temporal retries with backoff instead of blocking a worker.+"""++import json+import asyncio+import dataclasses+from datetime import timedelta+from typing import Any++from django.conf import settings++import structlog+from temporalio import activity, workflow+from temporalio.common import RetryPolicy+from temporalio.exceptions import ApplicationError++from posthog.models.integration import GitHubIntegration, Integration+from posthog.rate_limiting.github import acquire_github_installation+from posthog.sync import database_sync_to_async+from posthog.temporal.common.base import PostHogWorkflow++from products.engineering_analytics.backend.logic.job_logs.emitter import JobLogsEmitter+from products.engineering_analytics.backend.logic.job_logs.fetcher import fetch_job_log+from products.engineering_analytics.backend.logic.job_logs.thinning import thin_log++logger = structlog.get_logger(__name__)++[email protected](frozen=True)+class FetchJobLogInputs:+ team_id: int+ integration_id: int+ repo: str+ job_id: int+ run_id: int | None = None+ branch: str | None = None+ conclusion: str | None = None+++def _resolve_credentials(team_id: int, integration_id: int) -> tuple[str, str, str]:+ """Return ``(github_access_token, installation_id, log_ingest_token)``. ``log_ingest_token`` is+ the owning team's project API token — the OTLP Bearer that routes emitted logs to that team's Logs.+ """+ integration = Integration.objects.get(id=integration_id, team_id=team_id, kind="github")+ github = GitHubIntegration(integration)+ if github.access_token_expired():+ github.refresh_access_token()+ if not integration.access_token:+ raise ValueError(f"No GitHub access token for integration {integration_id}")+ return integration.access_token, str(github.github_installation_id), integration.team.api_token+++async def fetch_and_emit_job_log_activity(inputs: FetchJobLogInputs) -> dict[str, Any]:+ log = logger.bind(job_id=inputs.job_id, repo=inputs.repo, team_id=inputs.team_id)+ if not settings.OTLP_LOGS_INGEST_ENDPOINT:+ # No Logs sink configured: don't fetch (wastes the egress budget) and don't mark the job done+ # (a no-op emit would never retry). Raise so Temporal retries once the endpoint is set.+ raise ApplicationError("Logs export endpoint not configured", type="LogsExportDisabled")+ github_token, installation_id, log_ingest_token = await database_sync_to_async(+ _resolve_credentials, thread_sensitive=False+ )(inputs.team_id, inputs.integration_id)+ if not await acquire_github_installation(installation_id):+ # Over budget — raise so Temporal retries with backoff instead of blocking a worker.+ raise ApplicationError("GitHub egress budget exhausted", type="GithubEgressBudgetExhausted")+ archive = await asyncio.to_thread(fetch_job_log, inputs.repo, inputs.job_id, github_token)+ if archive is None:+ log.info("github_job_log_unavailable")+ return {"status": "log_unavailable", "job_id": inputs.job_id, "lines": 0}+ attributes: dict[str, str | int] = {+ "job_id": inputs.job_id,+ "run_id": inputs.run_id or 0,+ "repo": inputs.repo,+ "branch": inputs.branch or "",+ "conclusion": inputs.conclusion or "",+ }++ # CI failure logs are team-level operational data: they ride the owning team's project Logs+ # (visible to any logs:read holder) by design and intentionally do NOT inherit the GitHub+ # source's resource-level access control. Don't emit anything a logs:read holder shouldn't see.+ def _thin_and_emit() -> int:+ # 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)++ lines = await asyncio.to_thread(_thin_and_emit)+ log.info("github_job_log_emitted", lines=lines)+ return {"status": "emitted", "job_id": inputs.job_id, "lines": lines}++[email protected](name="fetch-github-job-log")+class FetchGithubJobLogWorkflow(PostHogWorkflow):+ @staticmethod+ def parse_inputs(inputs: list[str]) -> FetchJobLogInputs:+ return FetchJobLogInputs(**json.loads(inputs[0]))++ @workflow.run+ async def run(self, inputs: FetchJobLogInputs) -> dict[str, Any]:+ return await workflow.execute_activity(+ fetch_and_emit_job_log_activity,+ inputs,+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=RetryPolicy(+ maximum_attempts=5,+ initial_interval=timedelta(seconds=30),+ maximum_interval=timedelta(minutes=5),+ ),+ )diff --git a/products/engineering_analytics/backend/logic/job_logs/coordinator.py b/products/engineering_analytics/backend/logic/job_logs/coordinator.pynew file mode 100644index 000000000000..29ad18a7870b--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/coordinator.py@@ -0,0 +1,187 @@+"""Find recently-failed CI jobs and fan out one idempotent log-fetch workflow per job.++Per-job workflow id (``gh-logs-{team}-{job}``, reuse ``ALLOW_DUPLICATE_FAILED_ONLY``) means each+job's log is fetched and emitted at most once, re-running only after a failed attempt.++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+once the Logs endpoint is deployed, regardless of deploy order.+"""++import re+import json+import dataclasses+from datetime import timedelta+from typing import Any++from django.conf import settings++import structlog+from temporalio import activity, workflow+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.models.integration import _is_safe_github_repo_path+from posthog.models.team import Team+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.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++logger = structlog.get_logger(__name__)++# How far back to look each tick. With the per-job workflow id (one fetch per job) this bounds+# re-scanning without a separate "already fetched" store.+DEFAULT_LOOKBACK = timedelta(hours=2)+_PREFIX = re.compile(r"^[A-Za-z0-9_]*$") # warehouse source prefixes; guards the table identifier+# Cap total jobs returned per tick — the activity hands them back as one Temporal payload (~2 MiB+# limit), so an incident across many sources mustn't return an unbounded list.+MAX_DISCOVERED_JOBS = 2000+++def _query_failed_jobs(team: Team, prefix: str, cutoff_iso: 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+ # the cutoff is chronological. The table name is a trusted identifier (validated prefix + fixed+ # suffix); user values flow through the placeholder, never the f-string.+ table = f"{prefix}github_workflow_jobs"+ sql = f"""+ SELECT id AS job_id, run_id, head_branch AS branch, conclusion+ FROM {table}+ WHERE conclusion = 'failure' AND completed_at > {{cutoff}}+ ORDER BY completed_at DESC+ LIMIT 500+ """+ 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)}),+ team=team,+ query_type="GithubJobLogsDiscovery",+ )+ return [dict(zip(response.columns or [], row)) for row in response.results]+++def _github_source_params(job_inputs: dict[str, Any] | None) -> tuple[int, str] | None:+ """``(integration_id, repo)`` from a GitHub source's ``job_inputs``, or None if unusable.++ job_inputs is team-writable, so guard its shape: a non-dict ``auth_method`` or a repo that isn't a+ plain ``owner/repo`` (which would steer the authenticated fetch elsewhere) yields None, not a crash.+ """+ # job_inputs is an EncryptedJSONField and can hold any JSON value; a non-dict (list/str/None)+ # would crash the .get below, outside the per-source try — skip it instead.+ if not isinstance(job_inputs, dict):+ return None+ auth_method = job_inputs.get("auth_method")+ auth = auth_method if isinstance(auth_method, dict) else {}+ # Accept both source-config shapes: nested ({"auth_method": {"github_integration_id": ...}}) and+ # flat ({"auth_method": "oauth", "github_integration_id": ...}). The isinstance guard keeps a+ # non-dict auth_method from crashing; the fallback reads the flat top-level id.+ integration_id = auth.get("github_integration_id") or job_inputs.get("github_integration_id")+ repo = job_inputs.get("repository")+ # PAT-auth sources have no github_integration_id and fall through to None here — intentionally+ # skipped: the worker fetches under the App installation token + per-installation egress budget,+ # which PAT has no equivalent for. Supporting PAT would need a separate fetch path (deferred).+ if not integration_id or not isinstance(repo, str) or not _is_safe_github_repo_path(repo):+ return None+ try:+ return int(integration_id), repo+ except (TypeError, ValueError):+ return None+++def _discover_failed_jobs(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+ # the activity's fail-closed guard, but here it also skips the per-source warehouse queries.+ return []+ found: list[dict[str, Any]] = []+ sources = (+ ExternalDataSource.objects.filter(source_type=ExternalDataSourceType.GITHUB)+ .exclude(deleted=True)+ .select_related("team")+ )+ for source in sources.iterator():+ params = _github_source_params(source.job_inputs)+ prefix = source.prefix or ""+ if params is None or not _PREFIX.match(prefix):+ continue+ integration_id, repo = params+ 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):+ job_id = row.get("job_id")+ if job_id is None:+ continue+ found.append(+ dataclasses.asdict(+ FetchJobLogInputs(+ team_id=source.team_id,+ integration_id=integration_id,+ repo=repo,+ job_id=int(job_id),+ run_id=row.get("run_id"),+ branch=row.get("branch"),+ conclusion=row.get("conclusion"),+ )+ )+ )+ if len(found) >= MAX_DISCOVERED_JOBS:+ logger.warning("github_job_logs_discovery_capped", cap=MAX_DISCOVERED_JOBS)+ return found+ except Exception:+ # A source whose jobs table isn't synced (most teams don't enable the workflow_jobs+ # schema) or a transient query error shouldn't fail the whole sweep — skip it.+ logger.warning("github_job_logs_discovery_skipped_source", source_id=str(source.id), exc_info=True)+ continue+ return found+++async def discover_failed_jobs_activity(cutoff_iso: str) -> list[dict[str, Any]]:+ """Failed CI jobs across teams with a connected GitHub source, as FetchJobLogInputs dicts."""+ return await database_sync_to_async(_discover_failed_jobs, thread_sensitive=False)(cutoff_iso)++[email protected](name="github-job-logs-coordinator")+class GithubJobLogsCoordinatorWorkflow(PostHogWorkflow):+ @staticmethod+ def parse_inputs(inputs: list[str]) -> dict[str, Any]:+ return json.loads(inputs[0]) if inputs else {}++ @workflow.run+ async def run(self, _state: dict[str, Any] | None = None) -> dict[str, Any]:+ cutoff_iso = (workflow.now() - DEFAULT_LOOKBACK).isoformat()+ jobs = await workflow.execute_activity(+ discover_failed_jobs_activity,+ cutoff_iso,+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ started = 0+ for job in jobs:+ inputs = FetchJobLogInputs(**job)+ try:+ await workflow.start_child_workflow(+ FetchGithubJobLogWorkflow.run,+ inputs,+ id=f"gh-logs-{inputs.team_id}-{inputs.job_id}",+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ execution_timeout=timedelta(minutes=15),+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,+ )+ started += 1+ except WorkflowAlreadyStartedError:+ # Already started by a prior tick — reuse policy coalesces it.+ continue+ return {"jobs_discovered": len(jobs), "workflows_started": started}diff --git a/products/engineering_analytics/backend/logic/job_logs/emitter.py b/products/engineering_analytics/backend/logic/job_logs/emitter.pynew file mode 100644index 000000000000..a396177385f9--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/emitter.py@@ -0,0 +1,112 @@+"""Ship fetched CI log content into Logs via OTLP — one record per line so each line is+independently searchable, countable, and groupable. Emits through the OpenTelemetry SDK to the+internal ``capture-logs`` endpoint (``/i/v1/logs``) with the destination team's project token as the+``Authorization: Bearer`` — the token is what routes records to that team's Logs, so there's no+public-internet round-trip. Each record carries the job attributes, the line's GitHub timestamp, and+a severity from GitHub's ``##[error]`` / ``##[warning]`` markers.++A Temporal activity is short-lived, so callers MUST ``flush()`` before returning (use the context+manager) — the batch processor would otherwise drop buffered records.+"""++import re+from collections.abc import Mapping+from datetime import datetime+from types import TracebackType++import structlog+from opentelemetry._logs import SeverityNumber+from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter+from opentelemetry.sdk._logs import LoggerProvider, LogRecord+from opentelemetry.sdk._logs.export import BatchLogRecordProcessor, LogExporter+from opentelemetry.sdk.resources import Resource++logger = structlog.get_logger(__name__)++_SERVICE_NAME = "github-ci-logs"++# GitHub prefixes every raw log line with an RFC3339 UTC timestamp, then the content:+# 2026-06-25T09:14:02.1234567Z ##[error]Process completed with exit code 1+_LINE = re.compile(r"^(?P<ts>\d{4}-\d{2}-\d{2}T[0-9:.]+Z)\s?(?P<body>.*)$")+_SCALAR = (str, int, float, bool)+++def _parse_ns(ts: str) -> int | None:+ """RFC3339 with GitHub's 7-digit fraction + ``Z`` → epoch nanoseconds, or None if unparseable.++ ``fromisoformat`` accepts at most 6 fractional digits, so trim GitHub's extra precision first.+ """+ try:+ normalized = re.sub(r"(\.\d{6})\d+Z$", r"\1Z", ts).replace("Z", "+00:00")+ return int(datetime.fromisoformat(normalized).timestamp() * 1_000_000_000)+ except (ValueError, OverflowError):+ return None+++def _severity(body: str) -> tuple[str, SeverityNumber]:+ lowered = body.lower()+ if "##[error]" in lowered:+ return "ERROR", SeverityNumber.ERROR+ if "##[warning]" in lowered:+ return "WARN", SeverityNumber.WARN+ return "INFO", SeverityNumber.INFO+++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+ (harmless until the Logs lane is configured).+ """++ def __init__(+ self, *, endpoint: str | None = None, token: str | None = None, exporter: LogExporter | None = None+ ) -> None:+ self._provider = LoggerProvider(resource=Resource.create({"service.name": _SERVICE_NAME}))+ if exporter is None and endpoint and token:+ exporter = OTLPLogExporter(endpoint=endpoint, headers={"authorization": f"Bearer {token}"})+ self._enabled = exporter is not None+ if exporter is not None:+ self._provider.add_log_record_processor(BatchLogRecordProcessor(exporter))+ else:+ 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."""+ if not self._enabled:+ return 0+ attrs = {key: value for key, value in attributes.items() if isinstance(value, _SCALAR)}+ emitted = 0+ for raw in archive_text.splitlines():+ match = _LINE.match(raw)+ body, timestamp = (match.group("body"), _parse_ns(match.group("ts"))) if match else (raw, None)+ if not body.strip():+ continue+ severity_text, severity_number = _severity(body)+ self._logger.emit(+ LogRecord(+ timestamp=timestamp,+ observed_timestamp=timestamp,+ severity_text=severity_text,+ severity_number=severity_number,+ body=body,+ attributes=attrs,+ )+ )+ emitted += 1+ return emitted++ def flush(self, timeout_millis: int = 5000) -> None:+ # Best-effort. BatchLogRecordProcessor.force_flush returns False even on success in our SDK+ # version, so its bool is not a reliable failure signal — don't gate on it (gating would+ # fail every job). OTLP emission is fire-and-forget; downstream Kafka gives at-least-once.+ self._provider.force_flush(timeout_millis=timeout_millis)++ def __enter__(self) -> "JobLogsEmitter":+ return self++ def __exit__(+ self, _exc_type: type[BaseException] | None, _exc: BaseException | None, _tb: TracebackType | None+ ) -> None:+ self.flush()+ self._provider.shutdown()diff --git a/products/engineering_analytics/backend/logic/job_logs/fetcher.py b/products/engineering_analytics/backend/logic/job_logs/fetcher.pynew file mode 100644index 000000000000..0511630ba61d--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/fetcher.py@@ -0,0 +1,54 @@+"""Fetch a GitHub Actions job-log archive.++``GET /repos/{repo}/actions/jobs/{job_id}/logs`` 302-redirects to a short-lived+``githubusercontent.com`` archive (plain text, can be MBs). The host is fixed and trusted, so+following the redirect is fine (no SSRF surface). Rate limits surface as ``GitHubRateLimitError`` so+the Temporal retry honors the reset.+"""++import requests++from posthog.models.integration import GITHUB_API_VERSION, _is_safe_github_repo_path, raise_if_github_rate_limited++_GITHUB_API = "https://api.github.com"+_BASE_HEADERS = {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": GITHUB_API_VERSION}+# A connected repo's failed job can print an arbitrarily large log; cap the bytes we pull into memory+# before thinning (the thinner only caps line count, after the bytes are already decoded).+_MAX_LOG_BYTES = 20 * 1024 * 1024+++def fetch_job_log(+ repo: str, job_id: int, access_token: str, *, timeout: int = 60, max_bytes: int = _MAX_LOG_BYTES+) -> str | None:+ """Return the job's log text (capped at ``max_bytes``), or None if GitHub purged it (404)."""+ if not _is_safe_github_repo_path(repo):+ # repo is team-writable source config; reject anything but plain owner/repo so a crafted+ # value can't steer this authenticated request to a different GitHub endpoint.+ raise ValueError(f"Unsafe GitHub repo path: {repo!r}")+ url = f"{_GITHUB_API}/repos/{repo}/actions/jobs/{job_id}/logs"+ headers = {**_BASE_HEADERS, "Authorization": f"Bearer {access_token}"}+ # Stream within the byte budget so a pathological log can't OOM the worker. Keep a bounded head+ # AND a rolling tail: failures surface at the end (the run summary), so a head-only cap could drop+ # the very lines thin_log needs if a job pads the start with noise.+ with requests.get(url, headers=headers, timeout=timeout, allow_redirects=True, stream=True) as response:+ raise_if_github_rate_limited(response)+ if response.status_code == 404:+ return None+ response.raise_for_status()+ head = bytearray()+ tail = bytearray()+ half = max(1, max_bytes // 2)+ truncated = False+ for chunk in response.iter_content(chunk_size=65536):+ if len(head) < half:+ room = half - len(head)+ head.extend(chunk[:room])+ chunk = chunk[room:]+ if chunk:+ tail.extend(chunk)+ if len(tail) > half:+ truncated = True+ del tail[:-half] # keep only the most recent `half` bytes+ if truncated:+ return (bytes(head) + b"\n... [log truncated] ...\n" + bytes(tail)).decode("utf-8", errors="replace")+ return (bytes(head) + bytes(tail)).decode("utf-8", errors="replace")diff --git a/products/engineering_analytics/backend/logic/job_logs/schedule.py b/products/engineering_analytics/backend/logic/job_logs/schedule.pynew file mode 100644index 000000000000..7f9fb41056c5--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/schedule.py@@ -0,0 +1,41 @@+"""Temporal schedule for the GitHub job-logs coordinator (~2 min, SKIP overlap).++Registered in ``posthog/temporal/schedule.py`` via the product facade. The coordinator no-ops until+``OTLP_LOGS_INGEST_ENDPOINT`` is set, so registering the schedule is inert until the Logs sink exists.+"""++from datetime import timedelta++from django.conf import settings++from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleIntervalSpec,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleSpec,+)++from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule++SCHEDULE_ID = "github-job-logs-coordinator-schedule"+SCHEDULE_INTERVAL = timedelta(minutes=2)+++async def create_github_job_logs_coordinator_schedule(client: Client) -> None:+ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ "github-job-logs-coordinator",+ id=SCHEDULE_ID,+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,+ ),+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=SCHEDULE_INTERVAL)]),+ # SKIP so a slow tick doesn't stack; the egress limiter (not cron frequency) caps spend.+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP, catchup_window=SCHEDULE_INTERVAL),+ )+ if await a_schedule_exists(client, SCHEDULE_ID):+ await a_update_schedule(client, SCHEDULE_ID, schedule)+ else:+ await a_create_schedule(client, SCHEDULE_ID, schedule, trigger_immediately=False)diff --git a/products/engineering_analytics/backend/logic/job_logs/temporal.py b/products/engineering_analytics/backend/logic/job_logs/temporal.pynew file mode 100644index 000000000000..2f3306712a63--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/temporal.py@@ -0,0 +1,17 @@+"""Workflow + activity registration lists for the job-logs worker.++Registered on ``settings.GENERAL_PURPOSE_TASK_QUEUE`` (the queue the schedule targets) via the+product facade in ``backend/facade/temporal.py``.+"""++from products.engineering_analytics.backend.logic.job_logs.activity import (+ FetchGithubJobLogWorkflow,+ fetch_and_emit_job_log_activity,+)+from products.engineering_analytics.backend.logic.job_logs.coordinator import (+ GithubJobLogsCoordinatorWorkflow,+ discover_failed_jobs_activity,+)++WORKFLOWS = [GithubJobLogsCoordinatorWorkflow, FetchGithubJobLogWorkflow]+ACTIVITIES = [discover_failed_jobs_activity, fetch_and_emit_job_log_activity]diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_activity.py b/products/engineering_analytics/backend/logic/job_logs/test/test_activity.pynew file mode 100644index 000000000000..dcf186adf3cf--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_activity.py@@ -0,0 +1,88 @@+import pytest++from temporalio.exceptions import ApplicationError++import products.engineering_analytics.backend.logic.job_logs.activity as activity_module+from products.engineering_analytics.backend.logic.job_logs.activity import (+ FetchJobLogInputs,+ fetch_and_emit_job_log_activity,+)++_INPUTS = FetchJobLogInputs(+ team_id=1, integration_id=2, repo="PostHog/posthog", job_id=3, run_id=4, branch="main", conclusion="failure"+)+++class _FakeEmitter:+ def __init__(self, *_args, **_kwargs):+ self.archive = None++ def __enter__(self):+ return self++ def __exit__(self, *_args):+ return None++ def emit_log_archive(self, archive, **_kwargs):+ self.archive = archive+ return len(archive.splitlines())+++def _patch(monkeypatch, *, acquired=True, archive="l1\nl2\nl3"):+ async def _acquire(_installation_id):+ return acquired++ monkeypatch.setattr(activity_module, "acquire_github_installation", _acquire)+ monkeypatch.setattr(+ activity_module, "_resolve_credentials", lambda _team_id, _integration_id: ("tok", "inst-99", "phc_dest")+ )+ monkeypatch.setattr(activity_module, "fetch_job_log", lambda _repo, _job_id, _token: archive)+ monkeypatch.setattr(activity_module, "JobLogsEmitter", _FakeEmitter)+ monkeypatch.setattr(activity_module.settings, "OTLP_LOGS_INGEST_ENDPOINT", "http://localhost:8010/i/v1/logs")+++async def test_emits_and_returns_line_count(monkeypatch):+ _patch(monkeypatch, archive="line one\nline two")+ result = await fetch_and_emit_job_log_activity(_INPUTS)+ assert result == {"status": "emitted", "job_id": 3, "lines": 2}+++async def test_raises_and_skips_fetch_when_budget_exhausted(monkeypatch):+ # The gate must stop us before the GitHub call when over the shared budget, and raise (retryable)+ # so Temporal backs off — never silently proceed.+ fetched = {"called": False}++ def _fetch(*_args, **_kwargs):+ fetched["called"] = True+ return "x"++ _patch(monkeypatch, acquired=False)+ monkeypatch.setattr(activity_module, "fetch_job_log", _fetch)+ with pytest.raises(ApplicationError):+ await fetch_and_emit_job_log_activity(_INPUTS)+ assert fetched["called"] is False+++async def test_log_unavailable_is_benign(monkeypatch):+ # An expired/purged log (fetch returns None) must report log_unavailable, not crash or emit.+ _patch(monkeypatch)+ monkeypatch.setattr(activity_module, "fetch_job_log", lambda *_args, **_kwargs: None)+ result = await fetch_and_emit_job_log_activity(_INPUTS)+ assert result == {"status": "log_unavailable", "job_id": 3, "lines": 0}+++async def test_raises_when_export_disabled(monkeypatch):+ # No Logs endpoint configured: raise (retryable) before fetching, so the failure isn't marked+ # done-and-unretryable and we don't spend egress budget on a job we can't emit.+ fetched = {"called": False}++ def _fetch(*_args, **_kwargs):+ fetched["called"] = True+ return "x"++ _patch(monkeypatch)+ monkeypatch.setattr(activity_module.settings, "OTLP_LOGS_INGEST_ENDPOINT", "")+ monkeypatch.setattr(activity_module, "fetch_job_log", _fetch)+ with pytest.raises(ApplicationError):+ await fetch_and_emit_job_log_activity(_INPUTS)+ assert fetched["called"] is Falsediff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_coordinator.py b/products/engineering_analytics/backend/logic/job_logs/test/test_coordinator.pynew file mode 100644index 000000000000..04e3279dc609--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_coordinator.py@@ -0,0 +1,44 @@+from django.test import override_settings++from parameterized import parameterized++from products.engineering_analytics.backend.logic.job_logs.coordinator import (+ _discover_failed_jobs,+ _github_source_params,+)+++class TestGithubSourceParams:+ def test_extracts_integration_and_repo(self):+ job_inputs = {"auth_method": {"github_integration_id": "42"}, "repository": "PostHog/posthog"}+ assert _github_source_params(job_inputs) == (42, "PostHog/posthog")++ def test_extracts_from_flat_auth_shape(self):+ job_inputs = {"auth_method": "oauth", "github_integration_id": "42", "repository": "PostHog/posthog"}+ assert _github_source_params(job_inputs) == (42, "PostHog/posthog")++ @parameterized.expand(+ [+ ("auth_method_not_dict", {"auth_method": "oauth", "repository": "PostHog/posthog"}),+ ("missing_integration_id", {"auth_method": {}, "repository": "PostHog/posthog"}),+ ("missing_repo", {"auth_method": {"github_integration_id": "42"}}),+ (+ "unsafe_repo",+ {"auth_method": {"github_integration_id": "42"}, "repository": "PostHog/posthog/contents/x?ref=y"},+ ),+ ("none_job_inputs", None),+ ("string_job_inputs", "not a dict"),+ ("list_job_inputs", ["not", "a", "dict"]),+ ]+ )+ def test_returns_none_for_unusable_source(self, _name, job_inputs):+ assert _github_source_params(job_inputs) is None+++class TestDiscoverFailedJobs:+ @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") == []diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.py b/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.pynew file mode 100644index 000000000000..595bb49e954a--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.py@@ -0,0 +1,68 @@+import pytest++import requests++from posthog.models.integration import GitHubRateLimitError++from products.engineering_analytics.backend.logic.job_logs.fetcher import fetch_job_log++_URL = "https://api.github.com/repos/PostHog/posthog/actions/jobs/123/logs"+++def test_returns_log_text_on_success(requests_mock):+ requests_mock.get(_URL, status_code=200, text="2026-06-25T09:14:02.0Z line one")+ assert fetch_job_log("PostHog/posthog", 123, "tok") == "2026-06-25T09:14:02.0Z line one"+++def test_returns_none_when_log_expired(requests_mock):+ # GitHub purges Actions logs after retention — a 404 is expected for old jobs and must be a+ # benign "nothing to emit", not a crash that retries the activity forever.+ requests_mock.get(_URL, status_code=404, text="Not Found")+ assert fetch_job_log("PostHog/posthog", 123, "tok") is None+++def test_raises_on_rate_limit(requests_mock):+ # A 429 must surface as GitHubRateLimitError so the Temporal retry honors the reset rather than+ # treating the body as a log or hammering the shared installation budget.+ requests_mock.get(_URL, status_code=429, headers={"retry-after": "30"}, text="rate limit exceeded")+ with pytest.raises(GitHubRateLimitError):+ fetch_job_log("PostHog/posthog", 123, "tok")+++def test_raises_on_unexpected_error(requests_mock):+ # A genuine non-rate-limit failure (e.g. 500) must propagate so the activity retries, not be+ # silently returned as log content.+ requests_mock.get(_URL, status_code=500, text="boom")+ with pytest.raises(requests.HTTPError):+ fetch_job_log("PostHog/posthog", 123, "tok")+++def test_caps_log_but_keeps_failure_tail(requests_mock):+ # A connected repo's job can print an arbitrarily large log; the fetch must bound the bytes+ # pulled into memory AND keep the tail, where the failure surfaces — a job padding the start+ # with noise must not push its real error past the cap and out of the emitted text.+ body = ("noise line\n" * 2000) + "##[error]the real failure\n"+ requests_mock.get(_URL, status_code=200, text=body)+ result = fetch_job_log("PostHog/posthog", 123, "tok", max_bytes=400)+ assert result is not None+ assert "##[error]the real failure" in result+ assert "log truncated" in result+ assert len(result.encode()) < len(body.encode())+++ "bad_repo",+ [+ "PostHog/posthog/contents/secret?ref=main", # extra path + query steers to another endpoint+ "../../other/repo", # traversal+ "PostHog/posthog#frag",+ "owner", # no slash+ "owner/repo/extra", # too many segments+ ],+)+def test_rejects_unsafe_repo_path(requests_mock, bad_repo):+ # repo is team-writable; a crafted value must be rejected before the authenticated request is+ # built, so it can't fetch a different GitHub endpoint with the installation token.+ with pytest.raises(ValueError):+ fetch_job_log(bad_repo, 123, "tok")+ assert not requests_mock.calleddiff --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.pynew file mode 100644index 000000000000..e086d0422ec8--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_job_logs_emitter.py@@ -0,0 +1,63 @@+from datetime import UTC, datetime++from opentelemetry.sdk._logs.export import InMemoryLogExporter++from products.engineering_analytics.backend.logic.job_logs.emitter import JobLogsEmitter++_ATTRS = {"job_id": 42, "run_id": 7, "branch": "main", "conclusion": "failure"}+++def _emit(archive: str, attributes=_ATTRS):+ exporter = InMemoryLogExporter()+ with JobLogsEmitter(exporter=exporter) as emitter:+ emitted = emitter.emit_log_archive(archive, attributes=attributes)+ return emitted, [d.log_record for d in exporter.get_finished_logs()]+++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+ # line regex, the ns timestamp parse, or the severity map would surface here.+ archive = (+ "2026-06-25T09:14:02.1234567Z Running tests\n"+ "2026-06-25T09:14:03.0000000Z ##[warning]deprecated API\n"+ "2026-06-25T09:14:04.0000000Z ##[error]Process completed with exit code 1\n"+ )+ emitted, records = _emit(archive)+ assert emitted == 3+ assert [r.body for r in records] == [+ "Running tests",+ "##[warning]deprecated API",+ "##[error]Process completed with exit code 1",+ ]+ assert [r.severity_text for r in records] == ["INFO", "WARN", "ERROR"]+ assert all(dict(r.attributes) == _ATTRS for r in records)+ expected_ns = int(datetime(2026, 6, 25, 9, 14, 2, 123456, tzinfo=UTC).timestamp() * 1_000_000_000)+ assert records[0].timestamp == expected_ns+++def test_skips_blank_lines():+ # Blank/whitespace-only lines must not become empty Logs records (noise in the corpus).+ emitted, records = _emit("2026-06-25T09:14:02.000000Z real line\n\n \n")+ assert emitted == 1+ assert records[0].body == "real line"+++def test_drops_non_scalar_attributes():+ # OTEL attributes accept scalars only; a Mapping-valued attribute must be dropped, not crash+ # or serialize garbage, while scalar attributes survive.+ _, records = _emit("2026-06-25T09:14:02.000000Z x", attributes={"job_id": 1, "nested": {"a": 1}})+ assert dict(records[0].attributes) == {"job_id": 1}+++def test_noop_when_unconfigured():+ # With no exporter, endpoint, or token, the emitter must be a safe no-op (return 0, no crash)+ # so the worker is harmless until the Logs lane is wired in.+ assert JobLogsEmitter().emit_log_archive("2026-06-25T09:14:02.000000Z x", attributes=_ATTRS) == 0+++def test_noop_when_token_missing():+ # Endpoint set but no token must also no-op — we never emit unauthenticated (it would 401 and+ # the records would be lost), and a half-configured lane shouldn't crash the worker.+ emitter = JobLogsEmitter(endpoint="http://localhost:8010/i/v1/logs", token=None)+ assert emitter.emit_log_archive("2026-06-25T09:14:02.000000Z x", attributes=_ATTRS) == 0diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_thinning.py b/products/engineering_analytics/backend/logic/job_logs/test/test_thinning.pynew file mode 100644index 000000000000..46aa3d436880--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_thinning.py@@ -0,0 +1,48 @@+from parameterized import parameterized++from products.engineering_analytics.backend.logic.job_logs.thinning import ThinningConfig, thin_log++_CAP = ThinningConfig().max_lines+++class TestThinLog:+ def test_returns_small_log_unchanged(self):+ text = "\n".join(f"step {i}" for i in range(_CAP))+ assert thin_log(text) == text++ def test_keeps_failure_region_warning_and_summary(self):+ noise = [f"downloading package {i}" for i in range(2000)]+ failure = [+ "##[warning]GeoIP database not found, continuing without it",+ "FAILED tests/test_widget.py::test_render - AssertionError: 1 != 2",+ "test result: FAILED. 412 passed; 1 failed",+ "##[error]Process completed with exit code 1.",+ ]+ out = thin_log("\n".join(noise + failure))++ content = [line for line in out.splitlines() if "lines omitted" not in line]+ assert len(content) <= _CAP+ assert "lines omitted" in out+ for line in failure:+ assert line in out+ assert "downloading package 500" not in out++ @parameterized.expand(+ [+ ("errortracking_migration", "Applying posthog.0879_migrate_error_tracking_models... OK"),+ ("zero_failed_summary", "0 failed, 4210 passed"),+ ("error_substring", "set error_code on the row"),+ ]+ )+ def test_substring_noise_is_not_a_marker(self, _name, noise_line):+ middle = [f"{noise_line} #{i}" for i in range(1500)]+ out = thin_log("\n".join([*middle, "##[error]Process completed with exit code 1."]))++ assert f"{noise_line} #700" not in out+ assert "##[error]Process completed with exit code 1." in out++ def test_caps_pathological_log_with_many_markers(self):+ out = thin_log("\n".join(["##[error]boom"] * 5000))++ content = [line for line in out.splitlines() if "lines omitted" not in line]+ assert len(content) <= _CAPdiff --git a/products/engineering_analytics/backend/logic/job_logs/thinning.py b/products/engineering_analytics/backend/logic/job_logs/thinning.pynew file mode 100644index 000000000000..0253d48b4c27--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/thinning.py@@ -0,0 +1,86 @@+"""Thin a GitHub Actions job log down to its failure-relevant lines.++A failed job's log is mostly noise (dependency downloads, hundreds of passing migrations) around a+small failure region. We keep that region — lines matching a high-precision failure marker plus+context — and a short tail fallback; everything else collapses to a ``... N lines omitted ...``+marker, turning multi-MB logs into a few hundred lines without losing the cause.++Pure transform, decoupled from fetch/emit: all-jobs ingestion can later thin *non-failure* logs by+passing a different ``ThinningConfig``. (A structured alternative — the check-run annotations API or+JUnit XML — is a cleaner future upgrade but depends on per-workflow instrumentation we don't control.)++Markers are exact, case-sensitive substrings, deliberately high-precision: bare ``error`` / ``failed``+are NOT markers — real logs are full of them (``errortracking`` migrations, ``0 failed`` summaries)+and they would defeat the thinning.+"""++import dataclasses++# Failure anchors. First two are GitHub's own ::error / ::warning annotations; the rest are framework+# fallbacks for steps that emit no annotation. Substring match, case-sensitive.+DEFAULT_FAILURE_MARKERS: tuple[str, ...] = (+ "##[error]", # GitHub step failure — emitted on every failed step+ "##[warning]", # GitHub warning annotation — non-fatal but worth surfacing+ "Traceback (most recent call last)", # Python+ "AssertionError", # Python / JS+ "FAILED ", # pytest per-test failure line+ "test result: FAILED", # cargo test summary+ "panic:", # Go / Rust panic+ "--- FAIL", # go test+)++[email protected](frozen=True)+class ThinningConfig:+ """Knobs for :func:`thin_log`. Defaults target failure logs; other log types pass their own."""++ markers: tuple[str, ...] = DEFAULT_FAILURE_MARKERS+ leading_context: int = 15 # lines kept before a marker (the cause usually precedes the marker)+ trailing_context: int = 10 # lines kept after a marker (a traceback's frames follow it)+ # Fallback for the rare marker-less log; the summary itself is already caught by the ##[error]+ # window (Actions appends cleanup steps after the test step, so the literal tail is mostly noise).+ tail_lines: int = 50+ max_lines: int = 400 # hard cap on kept lines; logs at or under this pass through untouched+++FAILURE_THINNING = ThinningConfig()+++def _matches_marker(line: str, markers: tuple[str, ...]) -> bool:+ return any(marker in line for marker in markers)+++def thin_log(text: str, config: ThinningConfig = FAILURE_THINNING) -> str:+ """Return the failure-relevant slice of ``text`` with omitted gaps marked. Pure; no I/O.++ Logs at or under ``config.max_lines`` are returned unchanged — thinning only kicks in once a log+ is large enough to be worth trimming, so small failures keep full fidelity.+ """+ lines = text.splitlines()+ total = len(lines)+ if total <= config.max_lines:+ return text++ keep: set[int] = set()+ for index, line in enumerate(lines):+ if _matches_marker(line, config.markers):+ start = max(0, index - config.leading_context)+ stop = min(total, index + config.trailing_context + 1)+ keep.update(range(start, stop))+ keep.update(range(max(0, total - config.tail_lines), total))++ selected = sorted(keep)+ if len(selected) > config.max_lines:+ # Bias to the end: the final summary matters more than the first of many failures.+ selected = selected[-config.max_lines :]++ out: list[str] = []+ if selected and selected[0] > 0:+ out.append(f"... {selected[0]} lines omitted ...")+ previous: int | None = None+ for index in selected:+ if previous is not None and index > previous + 1:+ out.append(f"... {index - previous - 1} lines omitted ...")+ out.append(lines[index])+ previous = index+ return "\n".join(out)diff --git a/products/engineering_analytics/package.json b/products/engineering_analytics/package.jsonindex 0797eab8a4b9..3ecd3d3ba016 100644--- a/products/engineering_analytics/package.json+++ b/products/engineering_analytics/package.json@@ -1,7 +1,7 @@{"name": "@posthog/products-engineering-analytics","scripts": {- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests backend/logic/job_logs/test -v --tb=short","backend:contract-check": "echo 'Contract files unchanged'"},"dependencies": {diff --git a/tach.toml b/tach.tomlindex cc8dba7e4a78..b401fd3bb657 100644--- a/tach.toml+++ b/tach.toml@@ -83,6 +83,7 @@ depends_on = ["products.data_warehouse","products.early_access_features","products.endpoints",+ "products.engineering_analytics","products.error_tracking","products.event_definitions","products.experiments",