: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): fetch depot ci job logs (#106114)
Raúl Negrón-Otero3e1b95648d53
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex 0aedaf19e5b8..4b07533de647 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -197,7 +197,7 @@ Warehouse table (Depot source):Other products read as sources:-- Logs: the thinned CI failure lines this product's job-logs pipeline emits (`service.name = github-ci-logs`), keyed by `run_id`.+- Logs: the thinned CI failure lines this product's job-logs pipeline emits (`service.name = github-ci-logs`), keyed by `run_id`, for failed GitHub jobs and failed Depot CI job attempts, whose `run_id` and `job_id` are the decoded integer ids of `depot_ci.py`.- Traces: per-test CI spans emitted by the main Backend pytest and Frontend Jest suites (`trace_spans`), behind flaky tests and team CI health. Jest covers both legacy `frontend/` tests and isolated product frontends through the shared root config; its quarantine adapter records tolerated failures beside JUnit so the trusted reporter can retain that evidence. Package-specific Jest and Vitest jobs are outside this signal.**Freshness caveat:** a run's `conclusion` settles via the `workflow_run` webhook, which can lag or miss deliveries; the read layer surfaces `status` honestly rather than implying a settled conclusion.diff --git a/products/engineering_analytics/backend/logic/job_logs/activity.py b/products/engineering_analytics/backend/logic/job_logs/activity.pyindex d9309d7c81ce..c1e6b1c684ca 100644--- a/products/engineering_analytics/backend/logic/job_logs/activity.py+++ b/products/engineering_analytics/backend/logic/job_logs/activity.py@@ -1,7 +1,9 @@-"""Fetch one GitHub Actions job log under the shared egress budget and emit it into Logs.+"""Fetch one failed CI job's log 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.+A GitHub Actions job log is fetched under the shared GitHub egress budget, and a Depot CI job+attempt's log with the Depot source's own token. 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@@ -17,18 +19,30 @@ from temporalio import activity, workflowfrom temporalio.common import RetryPolicyfrom temporalio.exceptions import ApplicationError+from posthog.dataclasses import frozenfrom posthog.egress.github.limiter import acquire_github_installationfrom posthog.egress.limiter.policies import Priorityfrom posthog.models.integration import GitHubIntegration, Integration+from posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflowfrom 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.fetcher import fetch_depot_job_log, fetch_job_logfrom products.engineering_analytics.backend.logic.job_logs.thinning import thin_log_lines+from products.engineering_analytics.backend.logic.sources import depot_source_api_tokenlogger = structlog.get_logger(__name__)+# The BATCH lane can stay shed for the remainder of an hourly budget window, so the retry horizon+# must outlive a worst-case shed. Otherwise the job's logs are dropped forever (the workflow_job+# webhook never refires).+_FETCH_RETRY_POLICY = RetryPolicy(+ maximum_attempts=10,+ initial_interval=timedelta(seconds=30),+ maximum_interval=timedelta(minutes=15),+)+@dataclasses.dataclass(frozen=True)class FetchJobLogInputs:@@ -45,6 +59,29 @@ class FetchJobLogInputs:head_sha: str | None = None+@frozen+class FetchDepotJobLogInputs:+ """One failed Depot CI job attempt. ``run_id`` and ``job_id`` are the decoded integer ids that+ the curated CI views and the CI traces carry; ``attempt_id`` is Depot's own id, used to fetch."""++ team_id: int+ source_id: str+ attempt_id: str+ run_id: int+ job_id: int+ repo: str+ workflow_name: str+ job_name: str+ run_attempt: int+ head_sha: str+++@frozen+class _DepotCredentials:+ api_token: str = dataclasses.field(repr=False)+ log_ingest_token: str = dataclasses.field(repr=False)++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`` isthe owning team's project API token — the OTLP Bearer that routes emitted logs to that team's Logs.@@ -58,13 +95,43 @@ def _resolve_credentials(team_id: int, integration_id: int) -> tuple[str, str, sreturn 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)+def _resolve_depot_credentials(team_id: int, source_id: str) -> _DepotCredentials:+ team = Team.objects.get(id=team_id)+ api_token = depot_source_api_token(team, source_id)+ if api_token is None:+ raise ValueError(f"No Depot API token for source {source_id}")+ return _DepotCredentials(api_token=api_token, log_ingest_token=team.api_token)+++def _require_logs_endpoint() -> None: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")+++def _thin_and_emit(+ log_text: str, attributes: dict[str, str | int], *, log_ingest_token: str, run_id: int | None, job_id: int+) -> int:+ # 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.+ thinned = thin_log_lines(log_text)+ with JobLogsEmitter(endpoint=settings.OTLP_LOGS_INGEST_ENDPOINT, token=log_ingest_token) as emitter:+ # 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,+ # Total lines in the full log before thinning, which is the denominator for each line's orig_line.+ attributes={**attributes, "orig_total": len(log_text.splitlines())},+ trace_id=run_id,+ span_id=job_id,+ )+++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)+ _require_logs_endpoint()github_token, installation_id, log_ingest_token = await database_sync_to_async(_resolve_credentials, thread_sensitive=False)(inputs.team_id, inputs.integration_id)@@ -90,26 +157,54 @@ async def fetch_and_emit_job_log_activity(inputs: FetchJobLogInputs) -> dict[str"workflow_name": inputs.workflow_name or "","run_attempt": inputs.run_attempt or 0,"head_sha": inputs.head_sha or "",- # Total lines in the full log before thinning — the denominator for each line's orig_line.- "orig_total": len(archive.splitlines()),}-- # 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:- thinned = thin_log_lines(archive)- with JobLogsEmitter(endpoint=settings.OTLP_LOGS_INGEST_ENDPOINT, token=log_ingest_token) as emitter:- # 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)+ lines = await asyncio.to_thread(+ _thin_and_emit,+ archive,+ attributes,+ log_ingest_token=log_ingest_token,+ run_id=inputs.run_id,+ job_id=inputs.job_id,+ )log.info("github_job_log_emitted", lines=lines)return {"status": "emitted", "job_id": inputs.job_id, "lines": lines}+async def fetch_and_emit_depot_job_log_activity(inputs: FetchDepotJobLogInputs) -> dict[str, Any]:+ log = logger.bind(attempt_id=inputs.attempt_id, repo=inputs.repo, team_id=inputs.team_id)+ _require_logs_endpoint()+ credentials = await database_sync_to_async(_resolve_depot_credentials, thread_sensitive=False)(+ inputs.team_id, inputs.source_id+ )+ log_text = await asyncio.to_thread(fetch_depot_job_log, inputs.attempt_id, credentials.api_token)+ if log_text is None:+ log.info("depot_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,+ "repo": inputs.repo,+ # Depot reports no branch, and discovery only takes failed attempts.+ "branch": "",+ "conclusion": "failure",+ "job_name": inputs.job_name,+ "workflow_name": inputs.workflow_name,+ "run_attempt": inputs.run_attempt,+ "head_sha": inputs.head_sha,+ }+ lines = await asyncio.to_thread(+ _thin_and_emit,+ log_text,+ attributes,+ log_ingest_token=credentials.log_ingest_token,+ run_id=inputs.run_id,+ job_id=inputs.job_id,+ )+ log.info("depot_job_log_emitted", lines=lines)+ return {"status": "emitted", "job_id": inputs.job_id, "lines": lines}++@workflow.defn(name="fetch-github-job-log")class FetchGithubJobLogWorkflow(PostHogWorkflow):@staticmethod@@ -122,12 +217,21 @@ class FetchGithubJobLogWorkflow(PostHogWorkflow):fetch_and_emit_job_log_activity,inputs,start_to_close_timeout=timedelta(minutes=5),- # The BATCH lane can stay shed for the remainder of an hourly budget window, so the- # retry horizon must outlive a worst-case shed — otherwise the job's logs are dropped- # forever (the workflow_job webhook never refires).- retry_policy=RetryPolicy(- maximum_attempts=10,- initial_interval=timedelta(seconds=30),- maximum_interval=timedelta(minutes=15),- ),+ retry_policy=_FETCH_RETRY_POLICY,+ )++[email protected](name="fetch-depot-job-log")+class FetchDepotJobLogWorkflow(PostHogWorkflow):+ @staticmethod+ def parse_inputs(inputs: list[str]) -> FetchDepotJobLogInputs:+ return FetchDepotJobLogInputs(**json.loads(inputs[0]))++ @workflow.run+ async def run(self, inputs: FetchDepotJobLogInputs) -> dict[str, Any]:+ return await workflow.execute_activity(+ fetch_and_emit_depot_job_log_activity,+ inputs,+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=_FETCH_RETRY_POLICY,)diff --git a/products/engineering_analytics/backend/logic/job_logs/coordinator.py b/products/engineering_analytics/backend/logic/job_logs/coordinator.pyindex 81eeb32b7be1..2fedb36e5ff4 100644--- a/products/engineering_analytics/backend/logic/job_logs/coordinator.py+++ b/products/engineering_analytics/backend/logic/job_logs/coordinator.py@@ -1,7 +1,10 @@"""Find failed CI jobs and jobs recovered by pytest retries, then fetch their diagnostic logs.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.+job's log is fetched and emitted at most once, re-running only after a failed attempt. Failed Depot+CI job attempts come from each Depot source's ``job_attempts`` table and run as+``depot-logs-{team}-{attempt}``. Only failed Depot attempts are fetched: the retry-recovered path+reads GitHub runner names.Discovery queries the raw ``{prefix}github_workflow_jobs`` table (the curated read layer doesn'texpose jobs yet). The coordinator is registered on the schedule but no-ops until@@ -12,6 +15,7 @@ once the Logs endpoint is deployed, regardless of deploy order.import reimport jsonimport dataclasses+from collections.abc import Iteratorfrom datetime import timedeltafrom typing import Any@@ -28,13 +32,21 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.dataclasses import frozenfrom posthog.models.integration.github import _is_safe_github_repo_pathfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflow-from products.engineering_analytics.backend.logic.job_logs.activity import FetchGithubJobLogWorkflow, FetchJobLogInputs+from products.engineering_analytics.backend.logic.job_logs.activity import (+ FetchDepotJobLogInputs,+ FetchDepotJobLogWorkflow,+ FetchGithubJobLogWorkflow,+ FetchJobLogInputs,+)from products.engineering_analytics.backend.logic.queries._test_spans import rerun_recovered_job_attempts+from products.engineering_analytics.backend.logic.sources import depot_source_job_attempts_table+from products.engineering_analytics.backend.logic.views.depot_ci import depot_github_run_id, depot_id_to_intfrom products.warehouse_sources.backend.facade.models import ExternalDataSourcefrom products.warehouse_sources.backend.facade.types import ExternalDataSourceType@@ -103,6 +115,12 @@ def _query_jobs_with_diagnostics(team: Team, prefix: str, cutoff_iso: str, repo:return [dict(zip(response.columns or [], row)) for row in response.results]+def _live_sources(source_type: ExternalDataSourceType) -> Iterator[ExternalDataSource]:+ """Every team's non-deleted sources of ``source_type``, with the team, for the cross-team sweep."""+ sources = ExternalDataSource.objects.filter(source_type=source_type).exclude(deleted=True).select_related("team")+ return sources.iterator()++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.@@ -140,12 +158,7 @@ def _discover_jobs_with_diagnostics(cutoff_iso: str) -> list[dict[str, Any]]:found: list[dict[str, Any]] = []eligible_sources = 0skipped_sources = 0- sources = (- ExternalDataSource.objects.filter(source_type=ExternalDataSourceType.GITHUB)- .exclude(deleted=True)- .select_related("team")- )- for source in sources.iterator():+ for source in _live_sources(ExternalDataSourceType.GITHUB):params = _github_source_params(source.job_inputs)prefix = source.prefix or ""if params is None or not _PREFIX.match(prefix):@@ -203,12 +216,136 @@ def _discover_jobs_with_diagnostics(cutoff_iso: str) -> list[dict[str, Any]]:return found+@frozen+class DepotAttemptCursor:+ """The last failed attempt of a full discovery page, in ``(finished_at, attempt_id)`` order."""++ finished_at: str+ attempt_id: str+++@frozen+class DepotDiscoveryInputs:+ cutoff_iso: str+ cursors: dict[str, DepotAttemptCursor]+++@frozen+class DepotDiscovery:+ attempts: list[FetchDepotJobLogInputs]+ cursors: dict[str, DepotAttemptCursor]+++def _query_failed_depot_attempts(+ team: Team, table: str, cutoff_iso: str, after: DepotAttemptCursor | None, limit: int+) -> list[dict[str, Any]]:+ # attempt_finished_at is an ISO-8601 string like completed_at above, so the lexical comparison+ # against the cutoff is chronological. The table name comes from the source's synced schema.+ after = after or DepotAttemptCursor(finished_at=cutoff_iso, attempt_id="")+ sql = f"""+ SELECT run_id, run_workflow_count, workflow_id, attempt_id, attempt, repo, head_sha, workflow_name,+ job_display_name, job_key, attempt_finished_at+ FROM {table}+ WHERE attempt_status = 'failed' AND attempt_finished_at > {{cutoff}} AND (+ attempt_finished_at > {{after_finished_at}}+ OR (attempt_finished_at = {{after_finished_at}} AND attempt_id > {{after_attempt_id}})+ )+ ORDER BY attempt_finished_at, attempt_id+ LIMIT {limit}+ """+ placeholders: dict[str, ast.Expr] = {+ "cutoff": ast.Constant(value=cutoff_iso),+ "after_finished_at": ast.Constant(value=after.finished_at),+ "after_attempt_id": ast.Constant(value=after.attempt_id),+ }+ with tags_context(product=Product.ENGINEERING_ANALYTICS, feature=Feature.QUERY, team_id=team.pk):+ response = execute_hogql_query(+ query=parse_select(sql, placeholders=placeholders),+ team=team,+ query_type="DepotJobLogsDiscovery",+ bypass_warehouse_access_control=True,+ )+ return [dict(zip(response.columns or [], row)) for row in response.results]+++def _depot_attempt_inputs(source: ExternalDataSource, row: dict[str, Any]) -> FetchDepotJobLogInputs | None:+ # The same run id the runs view gives this workflow, so the logs join it. A push run's id carries+ # a prefix outside the Depot id alphabet, so it has no integer run id for its logs to join on.+ run_id = depot_github_run_id(row["run_id"] or "", row["workflow_id"] or "", row["run_workflow_count"] or 0)+ job_id = depot_id_to_int(row["attempt_id"] or "")+ if run_id is None or job_id is None:+ return None+ return FetchDepotJobLogInputs(+ team_id=source.team_id,+ source_id=str(source.id),+ attempt_id=row["attempt_id"],+ run_id=run_id,+ job_id=job_id,+ repo=row["repo"] or "",+ workflow_name=row["workflow_name"] or "",+ job_name=row["job_display_name"] or row["job_key"] or "",+ run_attempt=row["attempt"] or 0,+ head_sha=row["head_sha"] or "",+ )+++def _discover_failed_depot_attempts(inputs: DepotDiscoveryInputs) -> DepotDiscovery:+ """Failed attempts oldest first, at most ``MAX_DISCOVERED_JOBS`` across all sources.++ A source whose page fills the remaining cap gets a cursor, and the next tick reads on from it.+ A source whose page does not fill it gets none, so the next tick reads its window from the start+ again and finds rows that landed late.+ """+ if not settings.OTLP_LOGS_INGEST_ENDPOINT:+ return DepotDiscovery(attempts=[], cursors={})+ attempts: list[FetchDepotJobLogInputs] = []+ cursors: dict[str, DepotAttemptCursor] = {}+ for source in _live_sources(ExternalDataSourceType.DEPOT):+ source_id = str(source.id)+ cursor = inputs.cursors.get(source_id)+ limit = MAX_DISCOVERED_JOBS - len(attempts)+ table = depot_source_job_attempts_table(source.team, source)+ if table is None:+ continue+ if limit <= 0:+ if cursor is not None:+ cursors[source_id] = cursor+ continue+ try:+ rows = _query_failed_depot_attempts(source.team, table, inputs.cutoff_iso, cursor, limit)+ except Exception:+ logger.warning("depot_job_logs_discovery_skipped_source", source_id=source_id, exc_info=True)+ if cursor is not None:+ cursors[source_id] = cursor+ continue+ attempts.extend(found for row in rows if (found := _depot_attempt_inputs(source, row)) is not None)+ if len(rows) == limit:+ cursors[source_id] = DepotAttemptCursor(+ finished_at=rows[-1]["attempt_finished_at"], attempt_id=rows[-1]["attempt_id"]+ )+ return DepotDiscovery(attempts=attempts, cursors=cursors)++@activity.defnasync 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_jobs_with_diagnostics, thread_sensitive=False)(cutoff_iso)+async def discover_failed_depot_attempts_activity(inputs: DepotDiscoveryInputs) -> DepotDiscovery:+ return await database_sync_to_async(_discover_failed_depot_attempts, thread_sensitive=False)(inputs)+++def _previous_depot_cursors() -> dict[str, DepotAttemptCursor]:+ # A schedule gives each run the result of the last run that completed. The cursors in it let a+ # backlog larger than one tick's cap page forward across ticks, instead of each tick reading the+ # same first page again while older attempts leave the lookback window without a fetch.+ previous = workflow.get_last_completion_result()+ cursors = previous.get("depot_cursors") if isinstance(previous, dict) else None+ return {source_id: DepotAttemptCursor(**cursor) for source_id, cursor in (cursors or {}).items()}++@workflow.defn(name="github-job-logs-coordinator")class GithubJobLogsCoordinatorWorkflow(PostHogWorkflow):@staticmethod@@ -240,4 +377,30 @@ class GithubJobLogsCoordinatorWorkflow(PostHogWorkflow):except WorkflowAlreadyStartedError:# Already started by a prior tick — reuse policy coalesces it.continue- return {"jobs_discovered": len(jobs), "workflows_started": started}+ depot = DepotDiscovery(attempts=[], cursors={})+ if workflow.patched("depot-job-logs-2026-09"):+ depot = await workflow.execute_activity(+ discover_failed_depot_attempts_activity,+ DepotDiscoveryInputs(cutoff_iso=cutoff_iso, cursors=_previous_depot_cursors()),+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ for attempt in depot.attempts:+ try:+ # No execution timeout, because the retry policy bounds the child. While the child+ # waits out Depot's Retry-After, its id stays taken, so a later tick cannot fetch early.+ await workflow.start_child_workflow(+ FetchDepotJobLogWorkflow.run,+ attempt,+ id=f"depot-logs-{attempt.team_id}-{attempt.attempt_id}",+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,+ )+ started += 1+ except WorkflowAlreadyStartedError:+ continue+ return {+ "jobs_discovered": len(jobs) + len(depot.attempts),+ "workflows_started": started,+ "depot_cursors": depot.cursors,+ }diff --git a/products/engineering_analytics/backend/logic/job_logs/fetcher.py b/products/engineering_analytics/backend/logic/job_logs/fetcher.pyindex ede544f1ef4e..2611252937e4 100644--- a/products/engineering_analytics/backend/logic/job_logs/fetcher.py+++ b/products/engineering_analytics/backend/logic/job_logs/fetcher.py@@ -1,4 +1,4 @@-"""Fetch a GitHub Actions job-log archive.+"""Fetch a failed CI job's log from GitHub Actions or Depot CI.``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@@ -6,17 +6,54 @@ following the redirect is fine (no SSRF surface). Rate limits surface as ``GitHuthe Temporal retry honors the reset."""+import json+import datetime as dtimport contextlib+from typing import Any++import requests+from temporalio.exceptions import ApplicationErrorfrom posthog.egress.github.transport import github_request, raise_if_github_rate_limitedfrom posthog.models.integration.github import _is_safe_github_repo_path_GITHUB_API = "https://api.github.com"+_DEPOT_JOB_ATTEMPT_LOGS = "https://api.depot.dev/depot.ci.v1.CIService/GetJobAttemptLogs"# 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+class _HeadAndTail:+ """The first and the last ``max_bytes // 2`` bytes of a log that arrives in chunks.++ 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.+ """++ def __init__(self, max_bytes: int) -> None:+ self._half = max(1, max_bytes // 2)+ self._head = bytearray()+ self._tail = bytearray()+ self._truncated = False++ def extend(self, chunk: bytes) -> None:+ if len(self._head) < self._half:+ room = self._half - len(self._head)+ self._head.extend(chunk[:room])+ chunk = chunk[room:]+ if chunk:+ self._tail.extend(chunk)+ if len(self._tail) > self._half:+ self._truncated = True+ del self._tail[: -self._half] # keep only the most recent `half` bytes++ def text(self) -> str:+ middle = b"\n... [log truncated] ...\n" if self._truncated else b""+ return (bytes(self._head) + middle + bytes(self._tail)).decode("utf-8", errors="replace")++def fetch_job_log(repo: str, job_id: int, access_token: str, *, timeout: int = 60, max_bytes: int = _MAX_LOG_BYTES) -> str | None:@@ -26,9 +63,6 @@ def fetch_job_log(# 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"- # 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.# Identity-blind on purpose: the activity already gated this call against the installation# budget before dispatch, so gating here again would consume the budget twice.with contextlib.closing(@@ -46,20 +80,84 @@ def fetch_job_log(if response.status_code == 404:return Noneresponse.raise_for_status()- head = bytearray()- tail = bytearray()- half = max(1, max_bytes // 2)- truncated = False+ log = _HeadAndTail(max_bytes)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")+ log.extend(chunk)+ return log.text()+++def _depot_line_text(line: dict[str, Any]) -> str:+ # Rendered as a GitHub log line, `<RFC3339 UTC timestamp> <body>`, so the emitter reads the+ # line's timestamp the same way for both engines. Depot sends the int64 `timestampMs` as a+ # JSON string and omits it when it is zero.+ body = str(line.get("body", ""))+ timestamp_ms = int(line.get("timestampMs") or 0)+ if not timestamp_ms:+ return body+ timestamp = dt.datetime.fromtimestamp(timestamp_ms / 1000, dt.UTC).isoformat(timespec="milliseconds")+ return f"{timestamp.removesuffix('+00:00')}Z {body}"+++def _retry_after(response: requests.Response) -> dt.timedelta | None:+ value = response.headers.get("Retry-After", "")+ return dt.timedelta(seconds=int(value)) if value.isdigit() else None+++def _read_body(response: requests.Response, limit: int) -> bytes | None:+ """The streamed response body, or None as soon as it passes ``limit`` bytes."""+ body = bytearray()+ for chunk in response.iter_content(chunk_size=65536):+ body.extend(chunk)+ if len(body) > limit:+ return None+ return bytes(body)+++def fetch_depot_job_log(+ attempt_id: str,+ api_token: str,+ *,+ timeout: int = 60,+ max_bytes: int = _MAX_LOG_BYTES,+ max_read_bytes: int = 4 * _MAX_LOG_BYTES,+) -> str | None:+ """Return the Depot CI attempt's log text (capped at ``max_bytes``), or None if Depot has none (404).++ ``api_token`` is the team's own Depot organization token, so no shared PostHog egress budget+ applies. A 429 passes Depot's ``Retry-After`` to the Temporal retry instead.++ The pages stop after ``max_read_bytes`` of responses, so a job that prints an unbounded log+ cannot hold a worker in the download. The log then keeps its head and the tail read so far.+ Each page is read as a stream and dropped undecoded once it passes ``_MAX_LOG_BYTES`` or the+ remaining budget, because decoding a page holds all of its JSON in memory at once.+ """+ log = _HeadAndTail(max_bytes)+ read_budget = max_read_bytes+ request = {"attemptId": attempt_id}+ with requests.Session() as session:+ session.headers["Authorization"] = f"Bearer {api_token}"+ while True:+ with contextlib.closing(+ session.post(_DEPOT_JOB_ATTEMPT_LOGS, json=request, timeout=timeout, stream=True)+ ) as response:+ if response.status_code == 404:+ return None+ if response.status_code == 429:+ raise ApplicationError(+ "Depot rate limited the job log fetch",+ type="DepotRateLimited",+ next_retry_delay=_retry_after(response),+ )+ response.raise_for_status()+ body = _read_body(response, min(_MAX_LOG_BYTES, read_budget))+ if body is None:+ log.extend(b"\n... [log download stopped at the read budget] ...\n")+ return log.text()+ read_budget -= len(body)+ page = json.loads(body)+ for line in page.get("lines", []):+ log.extend(f"{_depot_line_text(line)}\n".encode())+ page_token = page.get("nextPageToken")+ if not page_token:+ return log.text()+ request = {"attemptId": attempt_id, "pageToken": page_token}diff --git a/products/engineering_analytics/backend/logic/job_logs/temporal.py b/products/engineering_analytics/backend/logic/job_logs/temporal.pyindex 2f3306712a63..93216213e592 100644--- a/products/engineering_analytics/backend/logic/job_logs/temporal.py+++ b/products/engineering_analytics/backend/logic/job_logs/temporal.py@@ -5,13 +5,21 @@ product facade in ``backend/facade/temporal.py``."""from products.engineering_analytics.backend.logic.job_logs.activity import (+ FetchDepotJobLogWorkflow,FetchGithubJobLogWorkflow,+ fetch_and_emit_depot_job_log_activity,fetch_and_emit_job_log_activity,)from products.engineering_analytics.backend.logic.job_logs.coordinator import (GithubJobLogsCoordinatorWorkflow,+ discover_failed_depot_attempts_activity,discover_failed_jobs_activity,)-WORKFLOWS = [GithubJobLogsCoordinatorWorkflow, FetchGithubJobLogWorkflow]-ACTIVITIES = [discover_failed_jobs_activity, fetch_and_emit_job_log_activity]+WORKFLOWS = [GithubJobLogsCoordinatorWorkflow, FetchGithubJobLogWorkflow, FetchDepotJobLogWorkflow]+ACTIVITIES = [+ discover_failed_jobs_activity,+ discover_failed_depot_attempts_activity,+ fetch_and_emit_job_log_activity,+ fetch_and_emit_depot_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.pyindex 0a3e4e23cb7d..25aac64a8777 100644--- a/products/engineering_analytics/backend/logic/job_logs/test/test_activity.py+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_activity.py@@ -4,7 +4,10 @@ from temporalio.exceptions import ApplicationErrorimport products.engineering_analytics.backend.logic.job_logs.activity as activity_modulefrom products.engineering_analytics.backend.logic.job_logs.activity import (+ FetchDepotJobLogInputs,FetchJobLogInputs,+ _DepotCredentials,+ fetch_and_emit_depot_job_log_activity,fetch_and_emit_job_log_activity,)@@ -22,6 +25,19 @@ _INPUTS = FetchJobLogInputs(head_sha="abc1234",)+_DEPOT_INPUTS = FetchDepotJobLogInputs(+ team_id=1,+ source_id="0192f0c4-0000-7000-8000-000000000001",+ attempt_id="zf6sbbn2wh",+ run_id=80213453736890,+ job_id=579485267642625,+ repo="PostHog/posthog",+ workflow_name="Backend CI on Depot",+ job_name="Product tests (experiments)",+ run_attempt=1,+ head_sha="abc1234",+)+class _FakeEmitter:last_kwargs: dict = {}@@ -51,6 +67,12 @@ def _patch(monkeypatch, *, acquired=True, archive="l1\nl2\nl3"):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,+ "_resolve_depot_credentials",+ lambda _team_id, _source_id: _DepotCredentials(api_token="depot-tok", log_ingest_token="phc_dest"),+ )+ monkeypatch.setattr(activity_module, "fetch_depot_job_log", lambda _attempt_id, _token: archive)monkeypatch.setattr(activity_module, "JobLogsEmitter", _FakeEmitter)monkeypatch.setattr(activity_module.settings, "OTLP_LOGS_INGEST_ENDPOINT", "http://localhost:8010/i/v1/logs")@@ -84,15 +106,55 @@ async def test_raises_and_skips_fetch_when_budget_exhausted(monkeypatch):assert fetched["called"] is False-async def test_log_unavailable_is_benign(monkeypatch):+async def test_depot_attempt_fetches_by_attempt_id_and_emits_decoded_ids(monkeypatch):+ # Logs rows join the curated CI views and traces on the decoded integer ids. Emitting Depot's+ # string ids, or swapping run and attempt, leaves every Depot failure log unreachable by run_id.+ _patch(monkeypatch)+ fetched: dict[str, str] = {}++ def _fetch(attempt_id, token):+ fetched.update(attempt_id=attempt_id, token=token)+ return "##[error]boom"++ monkeypatch.setattr(activity_module, "fetch_depot_job_log", _fetch)+ result = await fetch_and_emit_depot_job_log_activity(_DEPOT_INPUTS)+ assert result == {"status": "emitted", "job_id": 579485267642625, "lines": 1}+ assert fetched == {"attempt_id": "zf6sbbn2wh", "token": "depot-tok"}+ assert (_FakeEmitter.last_kwargs["trace_id"], _FakeEmitter.last_kwargs["span_id"]) == (+ 80213453736890,+ 579485267642625,+ )+ assert _FakeEmitter.last_kwargs["attributes"] == {+ "job_id": 579485267642625,+ "run_id": 80213453736890,+ "repo": "PostHog/posthog",+ "branch": "",+ "conclusion": "failure",+ "job_name": "Product tests (experiments)",+ "workflow_name": "Backend CI on Depot",+ "run_attempt": 1,+ "head_sha": "abc1234",+ "orig_total": 1,+ }+++_ACTIVITIES = [+ (fetch_and_emit_job_log_activity, _INPUTS, "fetch_job_log"),+ (fetch_and_emit_depot_job_log_activity, _DEPOT_INPUTS, "fetch_depot_job_log"),+]++[email protected]("activity_fn, inputs, fetcher", _ACTIVITIES)+async def test_log_unavailable_is_benign(monkeypatch, activity_fn, inputs, fetcher):# 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}+ monkeypatch.setattr(activity_module, fetcher, lambda *_args, **_kwargs: None)+ result = await activity_fn(inputs)+ assert result == {"status": "log_unavailable", "job_id": inputs.job_id, "lines": 0}-async def test_raises_when_export_disabled(monkeypatch):[email protected]("activity_fn, inputs, fetcher", _ACTIVITIES)+async def test_raises_when_export_disabled(monkeypatch, activity_fn, inputs, fetcher):# 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}@@ -103,7 +165,7 @@ async def test_raises_when_export_disabled(monkeypatch):_patch(monkeypatch)monkeypatch.setattr(activity_module.settings, "OTLP_LOGS_INGEST_ENDPOINT", "")- monkeypatch.setattr(activity_module, "fetch_job_log", _fetch)+ monkeypatch.setattr(activity_module, fetcher, _fetch)with pytest.raises(ApplicationError):- await fetch_and_emit_job_log_activity(_INPUTS)+ await activity_fn(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.pyindex efa166027c3a..8623d6e32bb0 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@@ -1,5 +1,6 @@from types import SimpleNamespace+from posthog.test.base import BaseTest, ClickhouseTestMixinfrom unittest.mock import patchfrom django.test import override_settings@@ -8,11 +9,21 @@ from parameterized import parameterizedfrom posthog.models.team import Team+from products.engineering_analytics.backend.logic.job_logs.activity import FetchDepotJobLogInputsfrom products.engineering_analytics.backend.logic.job_logs.coordinator import (+ DepotAttemptCursor,+ DepotDiscovery,+ DepotDiscoveryInputs,+ _discover_failed_depot_attempts,_discover_jobs_with_diagnostics,_github_source_params,_query_jobs_with_diagnostics,)+from products.engineering_analytics.backend.logic.sources import DEPOT_JOB_ATTEMPTS_SCHEMA+from products.engineering_analytics.backend.logic.views.source_schema import DEPOT_JOB_ATTEMPTS_COLUMNS+from products.engineering_analytics.backend.tests._github_fixtures import create_github_warehouse_table, link_schema+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource+from products.warehouse_sources.backend.facade.types import ExternalDataSourceTypeclass TestGithubSourceParams:@@ -49,6 +60,97 @@ class TestDiscoverJobsWithDiagnostics:# 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_jobs_with_diagnostics("2026-06-29T00:00:00+00:00") == []+ assert _discover_failed_depot_attempts(+ DepotDiscoveryInputs(cutoff_iso="2026-06-29T00:00:00+00:00", cursors={})+ ) == DepotDiscovery(attempts=[], cursors={})+++class TestDiscoverFailedDepotAttempts(ClickhouseTestMixin, BaseTest):+ @override_settings(OTLP_LOGS_INGEST_ENDPOINT="http://localhost:8010/i/v1/logs")+ def test_discovers_recent_failed_attempts_with_decoded_ids(self) -> None:+ # Only recent failed attempts are fetched, keyed by the integer ids the curated views and CI+ # traces carry. A push run's id has no integer form, so its logs could never join and it is+ # skipped rather than emitted under a wrong run_id.+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="src-depot",+ connection_id="src-depot",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.DEPOT,+ prefix="ci",+ job_inputs={"api_token": "depot-tok", "repository": "PostHog/posthog"},+ )++ def attempt(+ attempt_id: str, status: str, finished: str, *, run_id: str = "427q556wmn", run_workflow_count: int = 1+ ) -> dict:+ return dict.fromkeys(DEPOT_JOB_ATTEMPTS_COLUMNS) | {+ "run_id": run_id,+ "run_workflow_count": run_workflow_count,+ "workflow_id": "cccccccccc",+ "repo": "PostHog/posthog",+ "head_sha": "abc1234",+ "workflow_name": "Backend CI on Depot",+ "job_key": "ci-backend.yml:turbo-tests:matrix-38",+ "attempt_id": attempt_id,+ "attempt": 1,+ "attempt_status": status,+ "attempt_finished_at": finished,+ }++ table_name = create_github_warehouse_table(+ self,+ "depot_job_attempts",+ DEPOT_JOB_ATTEMPTS_COLUMNS,+ [+ attempt("zf6sbbn2wh", "failed", "2026-09-24T14:55:00.000Z"),+ attempt("3v4pbsqvfc", "finished", "2026-09-24T14:59:00.000Z"),+ attempt("b82nsv77wl", "failed", "2026-09-22T14:52:30.000Z"),+ attempt("q28m5dl5rg", "failed", "2026-09-24T14:53:00.000Z", run_id="ps_59s92fgx6c"),+ # A run with two workflows takes the workflow's id, as the runs view keys it.+ attempt("h8qn5x801q", "failed", "2026-09-24T14:54:00.000Z", run_id="bbbbbbbbbb", run_workflow_count=2),+ ],+ source=source,+ prefix="ci",+ )+ link_schema(+ self.team,+ source,+ name=DEPOT_JOB_ATTEMPTS_SCHEMA,+ table=DataWarehouseTable.objects.get(team=self.team, name=table_name),+ )++ def fetch_inputs(attempt_id: str, run_id: int, job_id: int) -> FetchDepotJobLogInputs:+ return FetchDepotJobLogInputs(+ team_id=self.team.pk,+ source_id=str(source.id),+ attempt_id=attempt_id,+ run_id=run_id,+ job_id=job_id,+ repo="PostHog/posthog",+ workflow_name="Backend CI on Depot",+ job_name="ci-backend.yml:turbo-tests:matrix-38",+ run_attempt=1,+ head_sha="abc1234",+ )++ two_workflow_run = fetch_inputs("h8qn5x801q", run_id=223978965517241, job_id=300989664396052)+ one_workflow_run = fetch_inputs("zf6sbbn2wh", run_id=80213453736890, job_id=579485267642625)+ window_start = DepotDiscoveryInputs(cutoff_iso="2026-09-24T00:00:00+00:00", cursors={})+ assert _discover_failed_depot_attempts(window_start) == DepotDiscovery(+ attempts=[two_workflow_run, one_workflow_run], cursors={}+ )++ # A backlog over the cap pages forward across ticks. Without the cursor every tick reads the+ # same first page, and the attempts after it leave the lookback window without a fetch.+ with patch("products.engineering_analytics.backend.logic.job_logs.coordinator.MAX_DISCOVERED_JOBS", 2):+ first_tick = _discover_failed_depot_attempts(window_start)+ second_tick = _discover_failed_depot_attempts(+ DepotDiscoveryInputs(cutoff_iso=window_start.cutoff_iso, cursors=first_tick.cursors)+ )+ cursor = DepotAttemptCursor(finished_at="2026-09-24T14:54:00.000Z", attempt_id="h8qn5x801q")+ assert first_tick == DepotDiscovery(attempts=[two_workflow_run], cursors={str(source.id): cursor})+ assert second_tick == DepotDiscovery(attempts=[one_workflow_run], cursors={})class TestQueryJobsWithDiagnostics: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.pyindex ccafefa533cc..0ba2f654982d 100644--- a/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.py+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.py@@ -1,12 +1,21 @@+from datetime import timedelta+import pytestimport requests+from temporalio.exceptions import ApplicationErrorfrom posthog.egress.github.transport import GitHubRateLimitError-from products.engineering_analytics.backend.logic.job_logs.fetcher import fetch_job_log+from products.engineering_analytics.backend.logic.job_logs.fetcher import fetch_depot_job_log, fetch_job_log_URL = "https://api.github.com/repos/PostHog/posthog/actions/jobs/123/logs"+_DEPOT_URL = "https://api.depot.dev/depot.ci.v1.CIService/GetJobAttemptLogs"+++def _depot_page(*bodies: str, next_page_token: str = "") -> dict:+ lines = [{"stepKey": "tests", "timestampMs": "1790000000000", "lineNumber": 1, "body": body} for body in bodies]+ return {"lines": lines, "nextPageToken": next_page_token} if next_page_token else {"lines": lines}def test_returns_log_text_on_success(requests_mock):@@ -66,3 +75,87 @@ def test_rejects_unsafe_repo_path(requests_mock, bad_repo):with pytest.raises(ValueError):fetch_job_log(bad_repo, 123, "tok")assert not requests_mock.called+++def test_depot_follows_page_tokens_into_github_shaped_lines(requests_mock):+ # Depot pages an attempt's log. Stopping after the first page drops the failure at the end, and a+ # line without the GitHub timestamp prefix reaches Logs with no timestamp.+ requests_mock.post(+ _DEPOT_URL,+ [+ {"json": _depot_page("##[group]Run tests", next_page_token="page-2")},+ {"json": _depot_page("##[error]Process completed with exit code 1")},+ ],+ )+ assert fetch_depot_job_log("zf6sbbn2wh", "depot-tok") == (+ "2026-09-21T14:13:20.000Z ##[group]Run tests\n"+ "2026-09-21T14:13:20.000Z ##[error]Process completed with exit code 1\n"+ )+ assert [request.json() for request in requests_mock.request_history] == [+ {"attemptId": "zf6sbbn2wh"},+ {"attemptId": "zf6sbbn2wh", "pageToken": "page-2"},+ ]+ assert requests_mock.request_history[0].headers["Authorization"] == "Bearer depot-tok"+++def test_depot_caps_log_but_keeps_failure_tail(requests_mock):+ requests_mock.post(+ _DEPOT_URL,+ [+ {"json": _depot_page(*["noise line"] * 1000, next_page_token="page-2")},+ {"json": _depot_page(*["noise line"] * 1000, "##[error]the real failure")},+ ],+ )+ result = fetch_depot_job_log("zf6sbbn2wh", "depot-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()) < 1000+++ "pages, kept, calls",+ [+ # A page over the remaining budget is dropped before it is decoded into memory.+ ([_depot_page(*["noise line"] * 100, next_page_token="page-2")], [], 1),+ # A job that prints an endless log must not hold the worker in the download.+ (+ [+ _depot_page("##[error]first page", next_page_token="page-2"),+ _depot_page(*["noise line"] * 100, next_page_token="page-3"),+ ],+ ["##[error]first page"],+ 2,+ ),+ ],+)+def test_depot_stops_paging_at_the_read_budget(requests_mock, pages, kept, calls):+ requests_mock.post(_DEPOT_URL, [{"json": page} for page in pages])+ result = fetch_depot_job_log("zf6sbbn2wh", "depot-tok", max_read_bytes=1000)+ assert result is not None+ assert result.endswith("[log download stopped at the read budget] ...\n")+ assert "noise line" not in result+ assert all(line in result for line in kept)+ assert requests_mock.call_count == calls+++ "status, headers, error, retry_delay",+ [+ # A revoked token must fail the attempt, never read as an empty log that is marked done.+ (401, {}, requests.HTTPError, None),+ # Depot's Retry-After must reach Temporal, so the retry waits as long as Depot asked.+ (429, {"Retry-After": "30"}, ApplicationError, timedelta(seconds=30)),+ ],+)+def test_depot_raises_on_error_status_without_leaking_token(requests_mock, status, headers, error, retry_delay):+ requests_mock.post(_DEPOT_URL, status_code=status, headers=headers, json={"code": "unauthenticated"})+ with pytest.raises(error) as raised:+ fetch_depot_job_log("zf6sbbn2wh", "depot-secret-token")+ assert "depot-secret-token" not in str(raised.value)+ assert getattr(raised.value, "next_retry_delay", None) == retry_delay+++def test_depot_returns_none_when_attempt_has_no_log(requests_mock):+ requests_mock.post(_DEPOT_URL, status_code=404, json={"code": "not_found"})+ assert fetch_depot_job_log("zf6sbbn2wh", "depot-tok") is Nonediff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.pyindex f66499e00a87..b49738e01d88 100644--- a/products/engineering_analytics/backend/logic/sources.py+++ b/products/engineering_analytics/backend/logic/sources.py@@ -535,13 +535,27 @@ def resolve_depot_job_attempts_tables(tables: dict[str, depot_ci.DepotJobAttempts] = {}for source in _accessible_sources(team, ExternalDataSourceType.DEPOT, user_access_control):repository = _source_repository(source).casefold()- table = _synced_table_name(team, source, DEPOT_JOB_ATTEMPTS_SCHEMA) if repository else None+ table = depot_source_job_attempts_table(team, source) if repository else Noneattempts = depot_ci.DepotJobAttempts.for_repository(table, repository) if table else Noneif attempts:tables.setdefault(repository, attempts)return tables+def depot_source_api_token(team: Team, source_id: str) -> str | None:+ """The Depot organization API token a team's Depot source syncs with, or None."""+ source = _accessible_sources(team, ExternalDataSourceType.DEPOT, None).filter(id=source_id).first()+ # job_inputs is an EncryptedJSONField and can hold any JSON shape.+ inputs = source.job_inputs if source is not None and isinstance(source.job_inputs, dict) else {}+ api_token = inputs.get("api_token")+ return api_token if isinstance(api_token, str) and api_token else None+++def depot_source_job_attempts_table(team: Team, source: ExternalDataSource) -> str | None:+ """The synced ``job_attempts`` table of one Depot source, or None."""+ return _synced_table_name(team, source, DEPOT_JOB_ATTEMPTS_SCHEMA)++def _synced_table_name(team: Team, source: ExternalDataSource, schema_name: str) -> str | None:"""The warehouse table a source syncs for ``schema_name``, or None. Only a plain identifierqualifies, because callers interpolate the name into HogQL."""diff --git a/products/engineering_analytics/backend/logic/views/depot_ci.py b/products/engineering_analytics/backend/logic/views/depot_ci.pyindex 3028a4229da7..8a674f095945 100644--- a/products/engineering_analytics/backend/logic/views/depot_ci.py+++ b/products/engineering_analytics/backend/logic/views/depot_ci.py@@ -64,6 +64,21 @@ def _is_id(column: str) -> str:return f"match(ifNull({column}, ''), '^[{_ID_ALPHABET}]{{1,{_MAX_ID_LENGTH}}}$')"+def depot_id_to_int(depot_id: str) -> int | None:+ """The integer ``_id_to_int`` renders for ``depot_id``, or None when it is not a Depot CI id."""+ if not 0 < len(depot_id) <= _MAX_ID_LENGTH or any(char not in _ID_ALPHABET for char in depot_id):+ return None+ value = 0+ for char in depot_id:+ value = value * len(_ID_ALPHABET) + _ID_ALPHABET.index(char)+ return value+++def depot_github_run_id(run_id: str, workflow_id: str, run_workflow_count: int) -> int | None:+ """The integer ``_attempts`` gives a Depot workflow's runs row, or None when it has none."""+ return depot_id_to_int(run_id if run_workflow_count == 1 else workflow_id)++def _id_to_int(column: str) -> str:# ClickHouse cannot sum an array of Nullable values, so the Nullable column is unwrapped first.value = f"ifNull({column}, '')"