Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tasks): restore infrastructure release reads and clarify status (#111738)

Alessandro Pogliaghi7663de95a9d1
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index a456d009d314..dd39bde464ab 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -401,12 +401,16 @@ in a production app. A new app name has to be a class attribute for that to keep
### Sandbox templates
Staff can inspect the agent release pipeline at `/admin/tasks/task/infrastructure/` in each region.
+Release reads use the configured GitHub App installation for `PostHog/posthog`, with a temporary token restricted to Contents and Actions reads on that repository. No integration record or installation ID setting is needed. Deployments without GitHub App credentials use `GITHUB_TOKEN` when set.
The read-only page compares the published package, master version pin, registry platforms, custom-image bases, and the last recorded dev-stack bake.
Release evidence separates workflow status from image build and base promotion results, including skipped builds.
Select a custom image to inspect its latest Temporal execution. A failed refresh can leave a ready image on an older base.
Missing or stale sources remain unverified. This view does not measure versions inside running sandboxes or reconstruct historical rollout completion.
The Data sources tab lists each source's status and last successful read in UTC. Registry coverage remains unverified when the release source is unavailable or stale.
Graph release badges compare observed versions with npm latest; cached observations say "Last seen". Select an image for its separate version-pin and base-lineage assessment.
+Source failures include a safe diagnostic; a rejected GitHub credential requires checking the server's App configuration or shared token. Build-history failures leave a successfully read version pin available and show a separate warning.
+Individual job-read failures retain run links and other build results. If the workflow list cannot be read, previous runs remain visible with their original read timestamp. Retained source values are identified as the last successful read, and shared GitHub request-budget limits have a separate diagnostic.
+The dev-stack graph and details share a base-adoption status. "Awaiting refresh" means the last successful bake uses a different digest from the current VM image; the details show both references. A fresh source read does not establish that a bake has finished.
Each sandbox is created from a template that determines its base image and capabilities.
diff --git a/posthog/egress/github/README.md b/posthog/egress/github/README.md
index 09d6a0dfef0d..c66c3d3ff1e5 100644
--- a/posthog/egress/github/README.md
+++ b/posthog/egress/github/README.md
@@ -30,7 +30,7 @@ The warehouse source's page fetches run on `BATCH`, while its repository validat
The ownership file reader (`posthog/ownership/`, source `ownership_github_api`) runs on `NORMAL` where a person waits for a board or a snapshot list, and on `BATCH` for the scheduled digests and report generation. Its GraphQL reads charge `core`, as every GraphQL call does, and so does the one compare call per new head commit that lets it reuse cached files.
Stamphog reads the author-familiarity blame and history (GraphQL) and the pull request's commit messages on `BATCH`, because both signals are advisory: a shed call leaves them out of that review.
Its merge base read (compare) stays on the default lane, because the review checkout needs it.
-The Tasks infrastructure admin reads the sandbox version pin and recent image build runs on `NORMAL`, using the shared token and a regional cache.
+The Tasks infrastructure admin reads the sandbox version pin and recent image build runs on `NORMAL`, using a regional cache. When the GitHub App is configured, it discovers the `PostHog/posthog` installation and mints an ephemeral token restricted to that repository with Contents and Actions read permissions. Calls share the installation budget. Deployments without App credentials retain the shared-token behavior.
The `BATCH` floor on the `core` resource is **demand-responsive**, because a reserve is only worth holding against traffic that exists.
An installation whose only consumer is a bulk one (a warehouse backfill of a repository nothing else touches) would otherwise forfeit 30% of its hourly budget to contention that never arrives, and the hourly budget is what decides whether a large backfill finishes in one run.
@@ -90,4 +90,5 @@ The caches it counts are installation-scoped, so a row can record a hit on an en
## Sources
- [Rate limits for the REST API](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api): installation limits and the `x-ratelimit-*` headers.
+- [GitHub App endpoints](https://docs.github.com/en/rest/apps/apps): repository installation lookup and restricted installation tokens.
- [Search](https://docs.github.com/en/rest/search/search): the search and code search limits per minute.
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index f0031869821d..2b83c39e93cf 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -240,7 +240,7 @@ class GitHubIntegrationBase:
# --- App-level JWT authentication ---
@classmethod
- def client_request(
+ def app_request(
cls,
endpoint: str,
method: str = "GET",
@@ -285,7 +285,7 @@ class GitHubIntegrationBase:
# gating them under an installation budget would be wrong — but volume telemetry still counts.
return github_request(
method,
- f"https://api.github.com/app/{endpoint}",
+ f"https://api.github.com/{endpoint.lstrip('/')}",
source=_OBSERVABILITY_SOURCE,
headers={"Authorization": f"Bearer {jwt_token}"},
timeout=timeout,
@@ -293,6 +293,16 @@ class GitHubIntegrationBase:
json=json_body,
)
+ @classmethod
+ def client_request(
+ cls,
+ endpoint: str,
+ method: str = "GET",
+ timeout: float | None = 10,
+ json_body: dict[str, Any] | None = None,
+ ) -> requests.Response:
+ return cls.app_request(f"app/{endpoint}", method=method, timeout=timeout, json_body=json_body)
+
# --- App installation lifecycle (uninstall) ---
@staticmethod
diff --git a/products/tasks/backend/logic/services/infrastructure_status.py b/products/tasks/backend/logic/services/infrastructure_status.py
index f6127ac5cbcc..79678c09c4f5 100644
--- a/products/tasks/backend/logic/services/infrastructure_status.py
+++ b/products/tasks/backend/logic/services/infrastructure_status.py
@@ -5,6 +5,7 @@ import logging
from collections.abc import Callable
from contextlib import suppress
from datetime import datetime, timedelta
+from functools import cached_property
from typing import Literal, cast
from urllib.parse import quote
@@ -19,8 +20,9 @@ from redis.exceptions import LockNotOwnedError
from temporalio.api.enums.v1 import PendingActivityState
from temporalio.service import RPCError, RPCStatusCode
-from posthog.egress.github.transport import github_request
+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, github_request
from posthog.egress.limiter.policies import Priority
+from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.temporal.common.client import async_connect
from products.tasks.backend.constants import DEV_STACK_IMAGE_NAME
@@ -38,6 +40,7 @@ class SourceSnapshot(BaseModel):
status: Literal["ok", "error", "refreshing"]
observed_at: datetime | None = None
data: JsonValue = None
+ error: str | None = None
class CustomImageStatus(BaseModel):
@@ -62,19 +65,54 @@ def workflow_url(workflow_id: str) -> str:
class InfrastructureStatus:
+ def error_message(self, error: Exception) -> str:
+ if isinstance(error, GitHubEgressBudgetExhausted):
+ return "GitHub reads reached the shared request budget. Retry after the budget resets."
+ if isinstance(error, requests.HTTPError) and error.response is not None:
+ if error.response.status_code == 401:
+ return "The source rejected the server credential (HTTP 401). Check the configured credential."
+ if error.response.status_code == 403:
+ return "The source denied access (HTTP 403). Check permissions and rate limits."
+ if error.response.status_code == 429:
+ return "The source rate limit was reached (HTTP 429). Retry after the limit resets."
+ if isinstance(error, requests.Timeout):
+ return "The source request timed out. Refresh to retry."
+ return "The source read failed. Check the server logs and refresh to retry."
+
def _json(self, url: str, *, headers: dict[str, str] | None = None) -> requests.Response:
response = requests.get(url, headers=headers, timeout=5)
response.raise_for_status()
return response
+ @cached_property
+ def _github_installation_id(self) -> str | None:
+ if not (settings.GITHUB_APP_CLIENT_ID and settings.GITHUB_APP_PRIVATE_KEY):
+ return None
+ response = GitHubIntegrationBase.app_request("repos/PostHog/posthog/installation", timeout=5)
+ response.raise_for_status()
+ return str(response.json()["id"])
+
+ @cached_property
+ def _github_headers(self) -> dict[str, str]:
+ if self._github_installation_id is None:
+ return {"Authorization": f"Bearer {settings.GITHUB_TOKEN}"} if settings.GITHUB_TOKEN else {}
+ response = GitHubIntegrationBase.client_request(
+ f"installations/{self._github_installation_id}/access_tokens",
+ method="POST",
+ timeout=5,
+ json_body={"repositories": ["posthog"], "permissions": {"contents": "read", "actions": "read"}},
+ )
+ response.raise_for_status()
+ return {"Authorization": f"Bearer {response.json()['token']}"}
+
def _github(self, path: str) -> dict[str, JsonValue]:
- headers = {"Authorization": f"Bearer {settings.GITHUB_TOKEN}"} if settings.GITHUB_TOKEN else {}
response = github_request(
"GET",
f"https://api.github.com/repos/PostHog/posthog/{path}",
source="tasks_infrastructure_admin",
priority=Priority.NORMAL,
- headers=headers,
+ headers=self._github_headers,
+ installation_id=self._github_installation_id,
timeout=5,
)
response.raise_for_status()
@@ -108,27 +146,61 @@ class InfrastructureStatus:
if job.get("name") in names
]
- def release(self) -> JsonValue:
- content = self._github("contents/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base?ref=master")
- dockerfile = base64.b64decode(str(content["content"])).decode()
- pin = re.search(r"^ARG AGENT_VERSION=(\S+)", dockerfile, re.MULTILINE)
- if pin is None:
- raise ValueError("Missing agent version")
- runs = self._github("actions/workflows/cd-sandbox-base-image.yml/runs?branch=master&event=push&per_page=5")
- return {
- "pin": pin.group(1),
- "runs": [
+ def release_runs(self) -> dict[str, JsonValue]:
+ try:
+ response = self._github(
+ "actions/workflows/cd-sandbox-base-image.yml/runs?branch=master&event=push&per_page=5"
+ )
+ except Exception as error:
+ logger.exception("tasks_infrastructure_release_runs_failed")
+ cached = get_tasks_cache().get("tasks:infrastructure-admin:v1:release")
+ previous = SourceSnapshot.model_validate_json(cached) if isinstance(cached, str) else None
+ data = previous.data if previous and isinstance(previous.data, dict) else {}
+ return {
+ "runs": data.get("runs", []),
+ "runs_error": self.error_message(error),
+ "runs_stale": True,
+ "runs_observed_at": data.get(
+ "runs_observed_at",
+ previous.observed_at.isoformat() if previous and previous.observed_at else None,
+ ),
+ }
+ runs: list[JsonValue] = []
+ runs_error = None
+ for run in cast(list[dict[str, JsonValue]], response["workflow_runs"]):
+ jobs: list[JsonValue] = []
+ jobs_error = None
+ try:
+ jobs = self.build_jobs(run["id"])
+ except Exception as error:
+ logger.exception("tasks_infrastructure_release_jobs_failed", extra={"run_id": run["id"]})
+ jobs_error = self.error_message(error)
+ runs_error = jobs_error
+ runs.append(
{
**{
key: run.get(key)
for key in ("id", "head_sha", "status", "conclusion", "html_url", "created_at")
},
- "build_jobs": self.build_jobs(run["id"]),
+ "build_jobs": jobs,
+ "build_jobs_error": jobs_error,
}
- for run in cast(list[dict[str, JsonValue]], runs["workflow_runs"])
- ],
+ )
+ return {
+ "runs": runs,
+ "runs_error": runs_error,
+ "runs_stale": False,
+ "runs_observed_at": timezone.now().isoformat(),
}
+ def release(self) -> JsonValue:
+ content = self._github("contents/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base?ref=master")
+ dockerfile = base64.b64decode(str(content["content"])).decode()
+ pin = re.search(r"^ARG AGENT_VERSION=(\S+)", dockerfile, re.MULTILINE)
+ if pin is None:
+ raise ValueError("Missing agent version")
+ return {"pin": pin.group(1), **self.release_runs()}
+
def registry(self, name: str) -> JsonValue:
repo = f"posthog/posthog-sandbox-{name}"
token = self._json(f"https://ghcr.io/token?service=ghcr.io&scope=repository:{repo}:pull").json()["token"]
@@ -259,9 +331,14 @@ class InfrastructureStatus:
snapshot = SourceSnapshot(status="ok", observed_at=timezone.now(), data=data)
cache.set(key, snapshot.model_dump_json(), timeout=3600)
return snapshot
- except Exception:
+ except Exception as error:
logger.exception("tasks_infrastructure_source_failed", extra={"source": name})
- return previous.model_copy(update={"status": "error"}) if previous else SourceSnapshot(status="error")
+ message = self.error_message(error)
+ return (
+ previous.model_copy(update={"status": "error", "error": message})
+ if previous
+ else SourceSnapshot(status="error", error=message)
+ )
finally:
with suppress(LockNotOwnedError):
lock.release()
diff --git a/products/tasks/backend/tests/test_infrastructure_admin.py b/products/tasks/backend/tests/test_infrastructure_admin.py
index 47fda0d8b6ac..f3fc6c55fed9 100644
--- a/products/tasks/backend/tests/test_infrastructure_admin.py
+++ b/products/tasks/backend/tests/test_infrastructure_admin.py
@@ -13,9 +13,12 @@ from django.utils import timezone
import requests
import fakeredis
+import requests_mock
from parameterized import parameterized
from posthog.csp_middleware import CSPMiddleware
+from posthog.egress.github.transport import GitHubEgressBudgetExhausted
+from posthog.egress.limiter.policies import Priority
from posthog.models import User
from products.tasks.backend.logic.services.infrastructure_status import InfrastructureStatus, SourceSnapshot
@@ -38,7 +41,12 @@ class TestInfrastructureAdminPermissions(SimpleTestCase):
infrastructure_admin(request)
-@override_settings(TASKS_REDIS_URL="", CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})
+@override_settings(
+ TASKS_REDIS_URL="",
+ GITHUB_APP_CLIENT_ID="",
+ GITHUB_APP_PRIVATE_KEY="",
+ CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}},
+)
class TestInfrastructureSourceCache(SimpleTestCase):
def setUp(self) -> None:
get_tasks_cache().clear()
@@ -117,6 +125,95 @@ class TestInfrastructureSourceCache(SimpleTestCase):
],
)
+ @parameterized.expand(
+ [
+ ("pin", "http"),
+ ("runs", "http"),
+ ("jobs_first", "http"),
+ ("jobs_middle", "http"),
+ ("jobs_last", "http"),
+ ("pin", "budget"),
+ ("jobs_middle", "budget"),
+ ]
+ )
+ def test_github_failure_reports_safe_error_and_preserves_available_evidence(
+ self, failed_read: str, failure_kind: str
+ ) -> None:
+ response = requests.Response()
+ response.status_code = 401
+ failure = (
+ GitHubEgressBudgetExhausted("private upstream response", scope="example-installation")
+ if failure_kind == "budget"
+ else requests.HTTPError("private upstream response", response=response)
+ )
+ diagnostic = "shared request budget" if failure_kind == "budget" else "HTTP 401"
+ jobs = [
+ {"name": "Build and push Tasks Sandbox container image", "status": "completed", "conclusion": "success"}
+ ]
+ reads: list[Mock | Exception] = [
+ Mock(json=lambda: {"content": base64.b64encode(b"ARG AGENT_VERSION=1.0.0").decode()}),
+ Mock(
+ json=lambda: {
+ "workflow_runs": [{"id": i, "html_url": f"https://example.com/runs/{i}"} for i in range(1, 4)]
+ }
+ ),
+ *[Mock(json=lambda: {"jobs": jobs}) for _ in range(3)],
+ ]
+ reads[["pin", "runs", "jobs_first", "jobs_middle", "jobs_last"].index(failed_read)] = failure
+ collector = InfrastructureStatus()
+ with patch("products.tasks.backend.logic.services.infrastructure_status.github_request", side_effect=reads):
+ result = collector.read("release", collector.release).model_dump(mode="json")
+ if failed_read == "pin":
+ self.assertEqual(result["status"], "error")
+ self.assertIsNone(result["data"])
+ self.assertIn(diagnostic, result["error"])
+ else:
+ self.assertEqual(result["status"], "ok")
+ self.assertEqual(result["data"]["pin"], "1.0.0")
+ self.assertIn(diagnostic, result["data"]["runs_error"])
+ if failed_read == "runs":
+ self.assertEqual(result["data"]["runs"], [])
+ else:
+ self.assertEqual([run["id"] for run in result["data"]["runs"]], [1, 2, 3])
+ failed_id = ["jobs_first", "jobs_middle", "jobs_last"].index(failed_read) + 1
+ for run in result["data"]["runs"]:
+ self.assertEqual(run["html_url"], f"https://example.com/runs/{run['id']}")
+ if run["id"] == failed_id:
+ self.assertEqual(run["build_jobs"], [])
+ self.assertIn(diagnostic, run["build_jobs_error"])
+ else:
+ self.assertEqual(run["build_jobs"][0]["conclusion"], "success")
+ self.assertIsNone(run["build_jobs_error"])
+ self.assertNotIn("private upstream response", str(result))
+ self.assertNotIn("example-installation", str(result))
+
+ def test_workflow_list_failures_retain_history_without_refreshing_its_timestamp(self) -> None:
+ with (
+ time_machine.travel("2026-01-01T12:00:00Z", tick=False) as clock,
+ patch("products.tasks.backend.logic.services.infrastructure_status.github_request") as request,
+ ):
+ request.side_effect = [
+ Mock(json=lambda: {"content": base64.b64encode(b"ARG AGENT_VERSION=1.0.0").decode()}),
+ Mock(json=lambda: {"workflow_runs": [{"id": 1, "html_url": "https://example.com/runs/1"}]}),
+ Mock(json=lambda: {"jobs": []}),
+ ]
+ collector = InfrastructureStatus()
+ original = collector.read("release", collector.release).model_dump(mode="json")
+ for _ in range(2):
+ clock.shift(timedelta(minutes=2))
+ request.side_effect = [
+ Mock(json=lambda: {"content": base64.b64encode(b"ARG AGENT_VERSION=1.1.0").decode()}),
+ requests.Timeout(),
+ ]
+ retained = collector.read("release", collector.release).model_dump(mode="json")
+ self.assertEqual(retained["status"], "ok")
+ self.assertEqual(retained["data"]["pin"], "1.1.0")
+ self.assertEqual(retained["data"]["runs"], original["data"]["runs"])
+ self.assertEqual(retained["data"]["runs_observed_at"], original["data"]["runs_observed_at"])
+ self.assertTrue(retained["data"]["runs_stale"])
+ self.assertIn("timed out", retained["data"]["runs_error"])
+ self.assertNotEqual(retained["observed_at"], original["observed_at"])
+
def test_failed_refresh_preserves_evidence_without_claiming_freshness(self) -> None:
collector = InfrastructureStatus()
now = timezone.now()
@@ -134,6 +231,7 @@ class TestInfrastructureSourceCache(SimpleTestCase):
self.assertEqual(stale.status, "error")
self.assertEqual(stale.data, first.data)
self.assertEqual(stale.observed_at, first.observed_at)
+ self.assertIn("timed out", stale.error or "")
def test_partial_registry_publication_is_not_healthy(self) -> None:
responses = [
@@ -146,6 +244,74 @@ class TestInfrastructureSourceCache(SimpleTestCase):
self.assertEqual(result.status, "error")
self.assertIsNone(result.data)
+ @parameterized.expand([("success", 200, 201), ("installation_rejected", 401, 201), ("token_rejected", 200, 403)])
+ @override_settings(
+ GITHUB_APP_CLIENT_ID="example-app",
+ GITHUB_APP_PRIVATE_KEY="example-private-key",
+ GITHUB_TOKEN="example-rejected-shared-token",
+ )
+ def test_release_uses_repository_scoped_app_reads(
+ self, _name: str, installation_status: int, token_status: int
+ ) -> None:
+ with (
+ requests_mock.Mocker() as http,
+ patch("posthog.models.github_integration_base.jwt.encode", return_value="example-app-jwt"),
+ patch("posthog.egress.github.transport.consume_github_installation_sync", return_value=True) as budget,
+ ):
+ http.get(
+ "https://api.github.com/repos/PostHog/posthog/installation",
+ request_headers={"Authorization": "Bearer example-app-jwt"},
+ json={"id": 12345},
+ status_code=installation_status,
+ )
+ mint = http.post(
+ "https://api.github.com/app/installations/12345/access_tokens",
+ request_headers={"Authorization": "Bearer example-app-jwt"},
+ json={"token": "example-read-only-token"},
+ status_code=token_status,
+ )
+ headers = {"Authorization": "Bearer example-read-only-token"}
+ pin = http.get(
+ "https://api.github.com/repos/PostHog/posthog/contents/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base?ref=master",
+ request_headers=headers,
+ json={"content": base64.b64encode(b"ARG AGENT_VERSION=1.0.0").decode()},
+ )
+ http.get(
+ "https://api.github.com/repos/PostHog/posthog/actions/workflows/cd-sandbox-base-image.yml/runs?branch=master&event=push&per_page=5",
+ request_headers=headers,
+ json={"workflow_runs": [{"id": 1}]},
+ )
+ http.get(
+ "https://api.github.com/repos/PostHog/posthog/actions/runs/1/jobs?per_page=100",
+ request_headers=headers,
+ json={"jobs": []},
+ )
+ collector = InfrastructureStatus()
+ result = collector.read("release", collector.release).model_dump(mode="json")
+
+ if installation_status != 200 or token_status != 201:
+ self.assertEqual(result["status"], "error")
+ self.assertIsNone(result["data"])
+ self.assertIn(
+ f"HTTP {installation_status if installation_status != 200 else token_status}", result["error"]
+ )
+ self.assertFalse(pin.called)
+ else:
+ self.assertEqual(result["status"], "ok")
+ self.assertEqual(result["data"]["pin"], "1.0.0")
+ self.assertIsNone(result["data"]["runs_error"])
+ self.assertEqual(mint.call_count, 1)
+ self.assertEqual(
+ mint.last_request.json(),
+ {"repositories": ["posthog"], "permissions": {"contents": "read", "actions": "read"}},
+ )
+ self.assertEqual(budget.call_count, 3)
+ for call in budget.call_args_list:
+ self.assertEqual(call.args, ("12345",))
+ self.assertEqual(call.kwargs["priority"], Priority.NORMAL)
+ self.assertNotIn("example-read-only-token", str(result))
+ self.assertNotIn("example-app-jwt", str(result))
+
@override_settings(TASKS_REDIS_URL="", CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})
class TestInfrastructureInventory(BaseTest):
diff --git a/products/tasks/frontend/infrastructure/InfrastructureAdmin.tsx b/products/tasks/frontend/infrastructure/InfrastructureAdmin.tsx
index bf0e3883ac8e..d3d67f663392 100644
--- a/products/tasks/frontend/infrastructure/InfrastructureAdmin.tsx
+++ b/products/tasks/frontend/infrastructure/InfrastructureAdmin.tsx
@@ -56,6 +56,11 @@ export function InfrastructureAdmin({ region }: { region: string }): JSX.Element
timestamps.
</p>
)}
+ {fresh(data.release, now) && data.release?.data?.runs_error && (
+ <p className="alert">
+ The version pin is available, but build history is incomplete. Inspect Data sources for details.
+ </p>
+ )}
<div className="summary-grid">
<Card className="summary">
<span className="muted">npm latest</span>
diff --git a/products/tasks/frontend/infrastructure/ReleasePipeline.tsx b/products/tasks/frontend/infrastructure/ReleasePipeline.tsx
index 8e2909329b13..1305377a0bca 100644
--- a/products/tasks/frontend/infrastructure/ReleasePipeline.tsx
+++ b/products/tasks/frontend/infrastructure/ReleasePipeline.tsx
@@ -1,6 +1,16 @@
import { Card } from '@posthog/quill'
-import { Sources, customState, fresh, imageNames, imageState, pinState, releaseBadge } from './infrastructureTypes'
+import {
+ Sources,
+ customState,
+ devStackBadge,
+ devStackState,
+ fresh,
+ imageNames,
+ imageState,
+ pinState,
+ releaseBadge,
+} from './infrastructureTypes'
import { PipelineNode } from './PipelineNode'
export function ReleasePipeline({
@@ -131,20 +141,10 @@ export function ReleasePipeline({
id="dev_stack"
title="PostHog dev stack"
subtitle={devStack?.name || 'Reading bake record'}
- state={
- !fresh(sources.dev_stack) || !base || !devStack?.base_image_reference
- ? 'unknown'
- : devStack.base_image_reference === base
- ? 'current'
- : 'waiting'
- }
+ state={devStackState(sources)}
selected={selected}
onSelect={onSelect}
- badge={
- devStack && !fresh(sources.dev_stack)
- ? { label: 'Last seen', variant: 'default' }
- : undefined
- }
+ badge={devStackBadge(sources)}
/>
<span className="parallel-caption">Notebook and Streamlit build alongside the base.</span>
</div>
diff --git a/products/tasks/frontend/infrastructure/SourceFreshness.tsx b/products/tasks/frontend/infrastructure/SourceFreshness.tsx
index c45bb42c892a..6341064cc048 100644
--- a/products/tasks/frontend/infrastructure/SourceFreshness.tsx
+++ b/products/tasks/frontend/infrastructure/SourceFreshness.tsx
@@ -36,14 +36,25 @@ export function SourceFreshness({ sources, now }: { sources: Sources; now: numbe
{sourceNames.map((name) => {
const source = sources[name]
const isFresh = fresh(source, now)
+ const partial = name === 'release' && !!sources.release?.data?.runs_error
return (
<TableRow key={name}>
- <TableCell className="font-medium">{sourceLabels[name]}</TableCell>
+ <TableCell>
+ <span className="font-medium">{sourceLabels[name]}</span>
+ {source?.error && <p className="text-muted-foreground mt-1">{source.error}</p>}
+ {name === 'release' && sources.release?.data?.runs_error && (
+ <p className="text-muted-foreground mt-1">
+ {`Build history incomplete. ${sources.release.data.runs_error}`}
+ </p>
+ )}
+ </TableCell>
<TableCell>
<Badge
variant={
isFresh
- ? 'success'
+ ? partial
+ ? 'warning'
+ : 'success'
: source?.status === 'error'
? 'destructive'
: source?.status === 'ok'
@@ -52,7 +63,9 @@ export function SourceFreshness({ sources, now }: { sources: Sources; now: numbe
}
>
{isFresh
- ? 'Fresh'
+ ? partial
+ ? 'Partial'
+ : 'Fresh'
: source?.status === 'error'
? 'Unavailable'
: source?.status === 'ok'
diff --git a/products/tasks/frontend/infrastructure/StageInspector.tsx b/products/tasks/frontend/infrastructure/StageInspector.tsx
index 248b18f099b0..c37a0cfbc251 100644
--- a/products/tasks/frontend/infrastructure/StageInspector.tsx
+++ b/products/tasks/frontend/infrastructure/StageInspector.tsx
@@ -5,6 +5,8 @@ import {
Source,
Sources,
Workflow,
+ devStackBadge,
+ devStackState,
fresh,
imageNames,
imageState,
@@ -29,13 +31,19 @@ export function StageInspector({
const image = sources.custom?.data?.images.find((item) => item.id === selected)
const registry = imageNames.includes(selected as ImageName) ? sources[selected as ImageName]?.data : null
const run = workflow?.id === selected ? workflow.source : null
+ const devState = devStackState(sources)
+ const devBadge = devStackBadge(sources)
return (
<Card className="inspector">
<div className="inspector-header">
<span className="eyebrow">Stage evidence</span>
- <Badge variant={fresh(source) ? 'success' : 'default'}>
- {fresh(source) ? 'Observed' : image ? 'Custom image' : 'Unverified'}
- </Badge>
+ {selected === 'dev_stack' ? (
+ <Badge variant={devBadge.variant}>{devBadge.label}</Badge>
+ ) : (
+ <Badge variant={fresh(source) ? 'success' : 'default'}>
+ {fresh(source) ? 'Source fresh' : image ? 'Custom image' : 'Unverified'}
+ </Badge>
+ )}
</div>
<h2>{image ? `Image ${image.id.slice(0, 8)}` : selected.replace('_', ' ')}</h2>
{source?.observed_at && (
@@ -44,7 +52,10 @@ export function StageInspector({
</p>
)}
{source?.status === 'error' && (
- <p className="alert">Source unavailable. Any values below are from the last successful read.</p>
+ <>
+ <p className="alert">{source.error || 'Source unavailable. Refresh to retry.'}</p>
+ {source.data !== null && <p className="muted">Values below are from the last successful read.</p>}
+ </>
)}
{selected === 'package' && (
<p>Latest published npm version. A newer package does not mean the sandbox version pin has merged.</p>
@@ -55,13 +66,29 @@ export function StageInspector({
Master's sandbox version pin and the latest five workflow runs. Unrelated changes can skip image
builds. Build and promotion results below do not prove custom-image adoption.
</p>
+ {sources.release?.data?.runs_error && (
+ <p className="alert">{`Build history incomplete. ${sources.release.data.runs_error}`}</p>
+ )}
+ {sources.release?.data?.runs_stale && !!sources.release.data.runs.length && (
+ <p className="muted">
+ Build history is from the last successful read
+ {sources.release.data.runs_observed_at
+ ? ` at ${new Date(sources.release.data.runs_observed_at).toISOString().replace('T', ' ').slice(0, 19)} UTC`
+ : ''}
+ .
+ </p>
+ )}
{sources.release?.data?.runs.map((item) => (
<div className="platform-details" key={item.id}>
<a className="run-link" href={item.html_url} target="_blank" rel="noreferrer">
<code>{item.head_sha.slice(0, 8)}</code>
<span>{`Workflow ${item.conclusion || item.status} ↗`}</span>
</a>
- {!item.build_jobs?.length && <p>Build jobs not observed.</p>}
+ {item.build_jobs_error ? (
+ <p className="alert">{`Build jobs unavailable. ${item.build_jobs_error}`}</p>
+ ) : (
+ !item.build_jobs?.length && <p>Build jobs not observed.</p>
+ )}
{item.build_jobs?.map((job) => (
<div key={job.name}>
<p>{`${job.name}: ${job.conclusion || job.status}`}</p>
@@ -121,12 +148,21 @@ export function StageInspector({
{selected === 'dev_stack' && (
<>
<p>
- The recorded base of the last successful dev-stack bake. Missing records do not prove a failed
- bake.
+ {devState === 'waiting'
+ ? 'The last successful bake uses a different VM base. A fresh source read does not mean the bake has caught up.'
+ : devState === 'current'
+ ? 'The last successful bake matches the current VM base.'
+ : 'Fresh bake and VM base records are needed to verify adoption. Missing records do not prove a failed bake.'}
</p>
+ <h3>Last successful bake base</h3>
<p className="digest">
<code>{sources.dev_stack?.data?.base_image_reference || 'No recorded base'}</code>
</p>
+ <h3>Current VM base</h3>
+ <p className="digest">
+ <code>{sources.vm?.data?.reference || 'No recorded base'}</code>
+ </p>
+ {!fresh(sources.vm) && <p className="muted">The VM base source is unavailable or stale.</p>}
<p>
Base changes are checked every 2 minutes; the scheduled bake runs daily at 06:45 UTC when
enabled.
diff --git a/products/tasks/frontend/infrastructure/infrastructureTypes.test.ts b/products/tasks/frontend/infrastructure/infrastructureTypes.test.ts
index 3d1921d17ec7..9fbd8a2bce1b 100644
--- a/products/tasks/frontend/infrastructure/infrastructureTypes.test.ts
+++ b/products/tasks/frontend/infrastructure/infrastructureTypes.test.ts
@@ -4,6 +4,7 @@ import {
SourceData,
Sources,
customState,
+ devStackState,
imageState,
pinState,
releaseBadge,
@@ -24,6 +25,34 @@ const image: CustomImage = {
}
describe('infrastructure rollout evidence', () => {
+ it.each([
+ ['current', 'ok', 'ok', 0, 'current'],
+ ['previous', 'ok', 'ok', 0, 'waiting'],
+ [null, 'ok', 'ok', 0, 'unknown'],
+ ['current', 'error', 'ok', 0, 'unknown'],
+ ['current', 'ok', 'error', 0, 'unknown'],
+ ['current', 'ok', 'ok', 300_000, 'unknown'],
+ ] as const)(
+ 'compares the baked base %s with fresh VM evidence (%s, %s, %s)',
+ (base, devStatus, vmStatus, age, expected) => {
+ const observed_at = new Date(Date.now() - age).toISOString()
+ expect(
+ devStackState({
+ dev_stack: {
+ status: devStatus,
+ observed_at,
+ data: {
+ name: 'example',
+ base_image_reference: base,
+ workflow_url: 'https://example.com/workflow',
+ },
+ },
+ vm: { status: vmStatus, observed_at, data: { name: 'vm', reference: 'current', platforms: [] } },
+ })
+ ).toEqual(expected)
+ }
+ )
+
it.each([
['matching', ['1.1.0', '1.1.0'], 'ok', 0, 'Latest release', 'success'],
['different', ['1.0.0', '1.0.0'], 'ok', 0, 'Different release', 'warning'],
diff --git a/products/tasks/frontend/infrastructure/infrastructureTypes.ts b/products/tasks/frontend/infrastructure/infrastructureTypes.ts
index f3f28534e75f..d2afcc5c8110 100644
--- a/products/tasks/frontend/infrastructure/infrastructureTypes.ts
+++ b/products/tasks/frontend/infrastructure/infrastructureTypes.ts
@@ -1,7 +1,12 @@
export const imageNames = ['base', 'notebook', 'streamlit', 'pi', 'autoresearch', 'vm'] as const
export type ImageName = (typeof imageNames)[number]
export type Evidence = 'current' | 'waiting' | 'building' | 'failed' | 'unknown' | 'unmanaged'
-export type Source<T> = { status: 'ok' | 'error' | 'refreshing'; observed_at: string | null; data: T | null }
+export type Source<T> = {
+ status: 'ok' | 'error' | 'refreshing'
+ observed_at: string | null
+ data: T | null
+ error?: string | null
+}
export type Platform = {
arch: string
version: string | null
@@ -36,6 +41,9 @@ export type SourceData = {
package: { version: string; revision: string | null }
release: {
pin: string
+ runs_error?: string | null
+ runs_stale?: boolean
+ runs_observed_at?: string | null
runs: {
id: number
head_sha: string
@@ -44,6 +52,7 @@ export type SourceData = {
html_url: string
created_at: string
build_jobs: { name: string; status: string; conclusion: string | null; promotion: string | null }[]
+ build_jobs_error?: string | null
}[]
}
custom: { images: CustomImage[]; truncated: boolean; limit: number }
@@ -157,6 +166,23 @@ export function imageState(sources: Sources, name: ImageName): Evidence {
return 'current'
}
+export function devStackState(sources: Sources): Evidence {
+ const reference = sources.dev_stack?.data?.base_image_reference
+ const base = sources.vm?.data?.reference
+ if (!fresh(sources.dev_stack) || !fresh(sources.vm) || !reference || !base) {
+ return 'unknown'
+ }
+ return reference === base ? 'current' : 'waiting'
+}
+
+export function devStackBadge(sources: Sources): ReleaseBadge {
+ if (sources.dev_stack?.data && !fresh(sources.dev_stack)) {
+ return { label: 'Last seen', variant: 'default' }
+ }
+ const state = devStackState(sources)
+ return { label: labels[state], variant: variants[state] }
+}
+
export function customState(image: CustomImage, currentBase: string | undefined): Evidence {
if (['building', 'scanning'].includes(image.status)) {
return 'building'