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): rebuild custom images after agent releases (#71603)

Alessandro Pogliaghi775aec400189
diff --git a/.github/workflows/cd-sandbox-base-image.yml b/.github/workflows/cd-sandbox-base-image.yml
index a6f9c26054ec..c6ceccb874af 100644
--- a/.github/workflows/cd-sandbox-base-image.yml
+++ b/.github/workflows/cd-sandbox-base-image.yml
@@ -204,6 +204,16 @@ jobs:
password: ${{ secrets.GITHUB_TOKEN }}
logout: false
+ - name: Resolve published agent version
+ id: agent-version
+ run: |
+ version=$(curl -fsSL --retry 3 https://registry.npmjs.org/@posthog%2fagent/latest | jq -r '.version')
+ if [[ -z "$version" || "$version" == "null" ]]; then
+ echo "Could not resolve the latest @posthog/agent version" >&2
+ exit 1
+ fi
+ echo "version=$version" >> "$GITHUB_OUTPUT"
+
- name: Build and push container image (base)
id: build
uses: depot/build-push-action@5f3b3c2e5a00f0093de47f657aeaefcedff27d18 # v1.17.0
@@ -214,7 +224,9 @@ jobs:
push: ${{ github.event_name == 'pull_request' || vars.CD_DEPLOY_ENABLED == 'true' }}
tags: ${{ github.ref == 'refs/heads/master' && format('ghcr.io/posthog/posthog-sandbox-base:master,ghcr.io/posthog/posthog-sandbox-base:{0}', github.sha) || format('ghcr.io/posthog/posthog-sandbox-base:{0}', github.sha) }}
platforms: linux/arm64,linux/amd64
- build-args: COMMIT_HASH=${{ github.sha }}
+ build-args: |
+ AGENT_VERSION=${{ steps.agent-version.outputs.version }}
+ COMMIT_HASH=${{ github.sha }}
- name: Build and push container image (notebook)
id: build-notebook
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 1ea4cc6d60ff..0860b643af38 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -102,6 +102,7 @@ from products.streamlit_apps.backend.facade.api import (
prune_old_streamlit_app_versions,
stop_idle_streamlit_sandboxes,
)
+from products.tasks.backend.facade.tasks import refresh_stale_sandbox_custom_images_task
from products.web_analytics.backend.achievements.tasks import sweep_web_analytics_achievement_team_tracks
from products.web_analytics.backend.tasks.heatmap_screenshot import report_stuck_heatmap_screenshots
@@ -261,6 +262,15 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="redispatch orphaned queued task runs",
)
+ # Refresh custom sandbox images after the VM base image digest changes.
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="*/10"),
+ refresh_stale_sandbox_custom_images_task.s(),
+ name="refresh stale sandbox custom images",
+ expires_seconds=10 * 60,
+ )
+
# Re-enqueue signals PR refunds whose billing credit sync hasn't landed - hourly at minute 25
sender.add_periodic_task(
crontab(hour="*", minute="25"),
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 7d5c5bceb122..156e169741be 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -1383,10 +1383,19 @@ def build_sandbox_custom_image(
raise ValueError("The image spec is empty; add packages, commands, or env vars before building")
validate_spec_buildable(spec, image.repository)
- image.spec = spec.model_dump()
- image.status = SandboxCustomImage.Status.SCANNING
- image.error = ""
- image.save(update_fields=["spec", "status", "error", "updated_at"])
+ updated = (
+ _accessible_custom_images(team_id, user_id)
+ .filter(id=image.id)
+ .exclude(status__in=(SandboxCustomImage.Status.SCANNING, SandboxCustomImage.Status.BUILDING))
+ .update(
+ spec=spec.model_dump(),
+ status=SandboxCustomImage.Status.SCANNING,
+ error="",
+ updated_at=django_timezone.now(),
+ )
+ )
+ if not updated:
+ raise ValueError("A build is already in progress for this image")
observe_custom_image_build("started")
execute_build_sandbox_image_workflow(str(image.id), team_id)
diff --git a/products/tasks/backend/facade/tasks.py b/products/tasks/backend/facade/tasks.py
new file mode 100644
index 000000000000..c42cbbb49581
--- /dev/null
+++ b/products/tasks/backend/facade/tasks.py
@@ -0,0 +1,10 @@
+from celery import shared_task
+
+
+@shared_task(ignore_result=True)
+def refresh_stale_sandbox_custom_images_task() -> None:
+ from products.tasks.backend.logic.services.custom_image_refresh import ( # noqa: PLC0415
+ refresh_stale_sandbox_custom_images,
+ )
+
+ refresh_stale_sandbox_custom_images()
diff --git a/products/tasks/backend/logic/services/custom_image_refresh.py b/products/tasks/backend/logic/services/custom_image_refresh.py
new file mode 100644
index 000000000000..e583a94a6a8a
--- /dev/null
+++ b/products/tasks/backend/logic/services/custom_image_refresh.py
@@ -0,0 +1,76 @@
+import logging
+
+from django.db.models import Q
+
+from products.tasks.backend.logic.services.modal_sandbox import resolve_template_base_image_reference
+from products.tasks.backend.logic.services.sandbox import SandboxTemplate
+from products.tasks.backend.models import SandboxCustomImage
+from products.tasks.backend.temporal.client import execute_build_sandbox_image_workflow
+
+logger = logging.getLogger(__name__)
+
+CUSTOM_IMAGE_REFRESH_BATCH_SIZE = 10
+
+
+def refresh_stale_sandbox_custom_images(batch_size: int = CUSTOM_IMAGE_REFRESH_BATCH_SIZE) -> int:
+ base_image_reference = resolve_template_base_image_reference(SandboxTemplate.VM_BASE)
+ if base_image_reference is None:
+ return 0
+
+ candidates = list(
+ SandboxCustomImage.objects.unscoped()
+ .filter(
+ status=SandboxCustomImage.Status.READY,
+ )
+ .exclude(modal_image_name="")
+ .exclude(spec={})
+ .exclude(Q(base_image_reference=base_image_reference) | Q(base_image_refresh_reference=base_image_reference))
+ .order_by("updated_at")
+ .values_list("id", "team_id")[:batch_size]
+ )
+
+ dispatched = 0
+ for image_id, team_id in candidates:
+ claimed = (
+ SandboxCustomImage.objects.unscoped()
+ .filter(
+ id=image_id,
+ status=SandboxCustomImage.Status.READY,
+ )
+ .exclude(
+ Q(base_image_reference=base_image_reference) | Q(base_image_refresh_reference=base_image_reference)
+ )
+ .update(
+ status=SandboxCustomImage.Status.BUILDING,
+ error="",
+ build_log="",
+ base_image_refresh_reference=base_image_reference,
+ )
+ )
+ if not claimed:
+ continue
+
+ try:
+ execute_build_sandbox_image_workflow(str(image_id), team_id, refresh=True)
+ except Exception:
+ (
+ SandboxCustomImage.objects.unscoped()
+ .filter(
+ id=image_id,
+ status=SandboxCustomImage.Status.BUILDING,
+ )
+ .update(status=SandboxCustomImage.Status.READY, base_image_refresh_reference=None)
+ )
+ logger.exception(
+ "sandbox_custom_image_refresh_dispatch_failed",
+ extra={"image_id": str(image_id), "team_id": team_id},
+ )
+ continue
+
+ dispatched += 1
+
+ logger.info(
+ "sandbox_custom_image_refresh_fanout_completed",
+ extra={"base_image_reference": base_image_reference, "dispatched": dispatched},
+ )
+ return dispatched
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index c292a770bcc3..a91a0f8b43e9 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -398,7 +398,10 @@ def get_template_base_image(template: SandboxTemplate) -> modal.Image:
if settings.DEBUG:
dockerfile_path, context_dir = _prepare_local_modal_build_context(template)
return modal.Image.from_dockerfile(dockerfile_path, context_dir=context_dir, ignore=[])
- return modal.Image.from_registry(_get_sandbox_image_reference(registry_image))
+ image_reference = resolve_template_base_image_reference(template)
+ if image_reference is None:
+ raise ValueError(f"Template does not use a registry image: {template}")
+ return modal.Image.from_registry(image_reference)
def _get_template_image(template: SandboxTemplate) -> modal.Image:
@@ -411,6 +414,21 @@ def resolve_template_base_image(template: SandboxTemplate) -> modal.Image:
return get_template_base_image(template)
+def resolve_template_base_image_reference(template: SandboxTemplate) -> str | None:
+ if settings.DEBUG:
+ return None
+
+ registry_image = {
+ SandboxTemplate.DEFAULT_BASE: SANDBOX_BASE_IMAGE,
+ SandboxTemplate.NOTEBOOK_BASE: SANDBOX_NOTEBOOK_IMAGE,
+ SandboxTemplate.VM_BASE: SANDBOX_VM_IMAGE,
+ SandboxTemplate.STREAMLIT_BASE: SANDBOX_STREAMLIT_IMAGE,
+ }.get(template)
+ if registry_image is None:
+ raise ValueError(f"Template does not use a registry image: {template}")
+ return _get_sandbox_image_reference(registry_image)
+
+
@lru_cache(maxsize=3)
def _prepare_local_modal_build_context(template: SandboxTemplate) -> tuple[str, str]:
dockerfile_relative_path = LOCAL_MODAL_DOCKERFILES.get(template)
diff --git a/products/tasks/backend/migrations/0062_sandbox_custom_image_base_reference.py b/products/tasks/backend/migrations/0062_sandbox_custom_image_base_reference.py
new file mode 100644
index 000000000000..b68076923d65
--- /dev/null
+++ b/products/tasks/backend/migrations/0062_sandbox_custom_image_base_reference.py
@@ -0,0 +1,32 @@
+# Generated by Django 5.2.14 on 2026-07-16 16:01
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("tasks", "0061_task_runtime"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sandboxcustomimage",
+ name="base_image_reference",
+ field=models.CharField(
+ blank=True,
+ help_text="Immutable VM base image reference used for the latest successful build.",
+ max_length=255,
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="sandboxcustomimage",
+ name="base_image_refresh_reference",
+ field=models.CharField(
+ blank=True,
+ help_text="VM base image reference most recently queued for an automatic refresh.",
+ max_length=255,
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 8711230f37fe..94f5d5edc055 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0061_task_runtime
+0062_sandbox_custom_image_base_reference
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 88b5409e0567..ccc9f97f7fdd 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -2006,6 +2006,18 @@ class SandboxCustomImage(TeamScopedRootMixin):
default="",
help_text="Published Modal named-image reference (name:tag) for the latest successful build.",
)
+ base_image_reference = models.CharField(
+ max_length=255,
+ null=True,
+ blank=True,
+ help_text="Immutable VM base image reference used for the latest successful build.",
+ )
+ base_image_refresh_reference = models.CharField(
+ max_length=255,
+ null=True,
+ blank=True,
+ help_text="VM base image reference most recently queued for an automatic refresh.",
+ )
scan_result = models.JSONField(default=dict, blank=True, help_text="Latest security scan verdict and findings.")
error = models.TextField(blank=True, default="", help_text="Failure detail for scan_failed/build_failed states.")
build_log = models.TextField(blank=True, default="", help_text="Sanitized tail of the latest Modal build output.")
diff --git a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base
index c96de4331a01..6fc629e0dabe 100644
--- a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base
+++ b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base
@@ -131,13 +131,15 @@ RUN set -eux; \
# Agent SDK
###
-# Set up /scripts as a Node.js project and install @posthog/agent
-# COMMIT_HASH changes every build, busting the cache so each build pulls @latest
+# Set up /scripts as a Node.js project and install @posthog/agent.
+# AGENT_VERSION changes on agent releases; COMMIT_HASH invalidates the layer for
+# PostHog-side image changes that keep the agent version unchanged.
+ARG AGENT_VERSION=latest
ARG COMMIT_HASH
RUN mkdir -p /scripts && \
cd /scripts && \
npm init -y && \
- CACHE_BUST=${COMMIT_HASH} npm install @posthog/agent@latest
+ CACHE_BUST=${COMMIT_HASH} npm install "@posthog/agent@${AGENT_VERSION}"
# Install pre-built skills (PostHog + context-mill) into the plugin directory.
# The dist/skills/ directory is populated by the CD workflow's build_skills job.
diff --git a/products/tasks/backend/temporal/build_image/activities.py b/products/tasks/backend/temporal/build_image/activities.py
index 1196d4dad718..98bc80a363b9 100644
--- a/products/tasks/backend/temporal/build_image/activities.py
+++ b/products/tasks/backend/temporal/build_image/activities.py
@@ -58,6 +58,7 @@ Hard severity rule: "unknown organization", "unfamiliar vendor", "unrelated to t
class ImageBuildActivityInput:
image_id: str
team_id: int
+ refresh: bool = False
def to_log_context(self) -> dict[str, Any]:
return {"image_id": self.image_id, "team_id": self.team_id}
@@ -204,10 +205,13 @@ def _attach_repo_warm_layer(image: "modal.Image", spec: SandboxImageSpec):
)
-def _compose_modal_image(spec: SandboxImageSpec, *, repository: str, team_id: int) -> "tuple[modal.Image, modal.App]":
+def _compose_modal_image(
+ spec: SandboxImageSpec, *, repository: str, team_id: int
+) -> "tuple[modal.Image, modal.App, str | None]":
from products.tasks.backend.logic.services.modal_sandbox import ( # noqa: PLC0415
ModalSandbox,
resolve_template_base_image,
+ resolve_template_base_image_reference,
)
from products.tasks.backend.logic.services.sandbox import SandboxTemplate, get_sandbox_class # noqa: PLC0415
@@ -217,6 +221,7 @@ def _compose_modal_image(spec: SandboxImageSpec, *, repository: str, team_id: in
app = sandbox_cls._get_app_for_template(SandboxTemplate.VM_BASE)
image = resolve_template_base_image(SandboxTemplate.VM_BASE)
+ base_image_reference = resolve_template_base_image_reference(SandboxTemplate.VM_BASE)
# Clone the linked repo with the token FIRST, on the trusted base, before any spec-authored
# layer can tamper with git to capture it. The warm step runs later, token-free.
@@ -234,7 +239,7 @@ def _compose_modal_image(spec: SandboxImageSpec, *, repository: str, team_id: in
if spec.repo_setup_commands:
image = _attach_repo_warm_layer(image, spec)
- return image, app
+ return image, app, base_image_reference
BUILD_LOG_FLUSH_INTERVAL_SECONDS = 2.0
@@ -299,7 +304,9 @@ def build_and_publish_image(input: ImageBuildActivityInput) -> str:
image.save(update_fields=["status", "build_log", "updated_at"])
spec = parse_image_spec_json(image.spec)
- modal_image, app = _compose_modal_image(spec, repository=image.repository, team_id=image.team_id)
+ modal_image, app, base_image_reference = _compose_modal_image(
+ spec, repository=image.repository, team_id=image.team_id
+ )
log_stream = _BuildLogBuffer()
stop_flusher = threading.Event()
@@ -321,9 +328,21 @@ def build_and_publish_image(input: ImageBuildActivityInput) -> str:
image.version = image.version + 1
image.modal_image_name = publish_name
+ image.base_image_reference = base_image_reference
+ image.base_image_refresh_reference = None
image.status = SandboxCustomImage.Status.READY
image.error = ""
- image.save(update_fields=["version", "modal_image_name", "status", "error", "updated_at"])
+ image.save(
+ update_fields=[
+ "version",
+ "modal_image_name",
+ "base_image_reference",
+ "base_image_refresh_reference",
+ "status",
+ "error",
+ "updated_at",
+ ]
+ )
observe_custom_image_build("succeeded")
logger.info(
@@ -338,6 +357,7 @@ class MarkImageBuildFailedInput:
image_id: str
team_id: int
error: str
+ refresh: bool = False
def to_log_context(self) -> dict[str, Any]:
return {"image_id": self.image_id, "team_id": self.team_id}
@@ -352,7 +372,13 @@ def mark_image_build_failed(input: MarkImageBuildFailedInput) -> None:
logger.warning("mark_image_build_failed_image_gone", extra=input.to_log_context())
return
if image.status in (SandboxCustomImage.Status.SCANNING, SandboxCustomImage.Status.BUILDING):
- image.status = SandboxCustomImage.Status.BUILD_FAILED
+ image.status = (
+ SandboxCustomImage.Status.READY
+ if input.refresh and image.modal_image_name
+ else SandboxCustomImage.Status.BUILD_FAILED
+ )
image.error = input.error[:2000]
- image.save(update_fields=["status", "error", "updated_at"])
+ if input.refresh:
+ image.base_image_refresh_reference = None
+ image.save(update_fields=["status", "error", "base_image_refresh_reference", "updated_at"])
observe_custom_image_build("failed")
diff --git a/products/tasks/backend/temporal/build_image/workflow.py b/products/tasks/backend/temporal/build_image/workflow.py
index dddcb931094f..99d9f6706aee 100644
--- a/products/tasks/backend/temporal/build_image/workflow.py
+++ b/products/tasks/backend/temporal/build_image/workflow.py
@@ -21,6 +21,7 @@ from .activities import (
class BuildSandboxImageInput:
image_id: str
team_id: int
+ refresh: bool = False
@dataclass
@@ -35,21 +36,24 @@ class BuildSandboxImageWorkflow(PostHogWorkflow):
@staticmethod
def parse_inputs(inputs: list[str]) -> BuildSandboxImageInput:
loaded = json.loads(inputs[0])
- return BuildSandboxImageInput(image_id=loaded["image_id"], team_id=loaded["team_id"])
+ return BuildSandboxImageInput(
+ image_id=loaded["image_id"], team_id=loaded["team_id"], refresh=loaded.get("refresh", False)
+ )
@workflow.run
async def run(self, input: BuildSandboxImageInput) -> BuildSandboxImageOutput:
- activity_input = ImageBuildActivityInput(image_id=input.image_id, team_id=input.team_id)
+ activity_input = ImageBuildActivityInput(image_id=input.image_id, team_id=input.team_id, refresh=input.refresh)
try:
- scan = await workflow.execute_activity(
- scan_image_spec,
- activity_input,
- start_to_close_timeout=timedelta(minutes=5),
- retry_policy=RetryPolicy(maximum_attempts=3),
- )
- if not scan.passed:
- return BuildSandboxImageOutput(success=False, error="Security scan failed")
+ if not input.refresh:
+ scan = await workflow.execute_activity(
+ scan_image_spec,
+ activity_input,
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ if not scan.passed:
+ return BuildSandboxImageOutput(success=False, error="Security scan failed")
modal_image_name = await workflow.execute_activity(
build_and_publish_image,
@@ -62,7 +66,9 @@ class BuildSandboxImageWorkflow(PostHogWorkflow):
except Exception as e:
await workflow.execute_activity(
mark_image_build_failed,
- MarkImageBuildFailedInput(image_id=input.image_id, team_id=input.team_id, error=str(e)),
+ MarkImageBuildFailedInput(
+ image_id=input.image_id, team_id=input.team_id, error=str(e), refresh=input.refresh
+ ),
start_to_close_timeout=timedelta(minutes=1),
retry_policy=RetryPolicy(maximum_attempts=3),
)
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index 7f4246371615..6c55b6c77ab2 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -450,13 +450,13 @@ def resume_task_in_cloud_workflow(run_id: str, workflow_id: str) -> None:
)
-def execute_build_sandbox_image_workflow(image_id: str, team_id: int) -> None:
+def execute_build_sandbox_image_workflow(image_id: str, team_id: int, *, refresh: bool = False) -> None:
"""Start (or restart) the scan → build → publish workflow for a custom sandbox image."""
client = sync_connect()
asyncio.run(
client.start_workflow(
"build-sandbox-image",
- BuildSandboxImageInput(image_id=image_id, team_id=team_id),
+ BuildSandboxImageInput(image_id=image_id, team_id=team_id, refresh=refresh),
id=f"build-sandbox-image-{image_id}",
id_reuse_policy=WorkflowIDReusePolicy.TERMINATE_IF_RUNNING,
task_queue=settings.TASKS_TASK_QUEUE,
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 6f11cd5a575a..74f91d274337 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -9470,6 +9470,33 @@ class TestSandboxCustomImageAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
mock_workflow.assert_not_called()
+ @patch("products.tasks.backend.temporal.client.execute_build_sandbox_image_workflow")
+ @patch("products.tasks.backend.logic.services.image_spec.validate_spec_buildable")
+ def test_build_rejected_when_refresh_claims_image_after_initial_read(self, mock_validate, mock_workflow):
+ image = _make_custom_image(
+ team=self.team,
+ user=self.user,
+ name="img",
+ status=SandboxCustomImage.Status.READY,
+ spec={"version": 1, "apt_packages": ["git"]},
+ )
+
+ mock_validate.side_effect = lambda *_args: (
+ SandboxCustomImage.objects.for_team(self.team.id)
+ .filter(id=image.id, status=SandboxCustomImage.Status.READY)
+ .update(status=SandboxCustomImage.Status.BUILDING)
+ )
+
+ response = self.client.post(
+ self.detail_url(image.id) + "build/", {"spec_yaml": "version: 1\napt_packages: [jq]\n"}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ mock_workflow.assert_not_called()
+ image.refresh_from_db()
+ self.assertEqual(image.status, SandboxCustomImage.Status.BUILDING)
+ self.assertEqual(image.spec["apt_packages"], ["git"])
+
def test_other_team_image_not_reachable(self):
other_org = Organization.objects.create(name="Other Org")
other_team = Team.objects.create(organization=other_org, name="Other Team")
diff --git a/products/tasks/backend/tests/test_custom_image_refresh.py b/products/tasks/backend/tests/test_custom_image_refresh.py
new file mode 100644
index 000000000000..fc15d2301086
--- /dev/null
+++ b/products/tasks/backend/tests/test_custom_image_refresh.py
@@ -0,0 +1,97 @@
+from collections.abc import Callable
+from datetime import timedelta
+from typing import cast
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from products.tasks.backend.logic.services.custom_image_refresh import refresh_stale_sandbox_custom_images
+from products.tasks.backend.models import SandboxCustomImage
+from products.tasks.backend.temporal.build_image.activities import MarkImageBuildFailedInput, mark_image_build_failed
+
+
+class TestCustomImageRefresh(APIBaseTest):
+ def _create_image(self, *, base_image_reference: str | None) -> SandboxCustomImage:
+ image_count = SandboxCustomImage.objects.for_team(self.team.id).count()
+ return SandboxCustomImage.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ created_by=self.user,
+ name=f"image-{image_count}",
+ spec={"apt_packages": ["git"]},
+ status=SandboxCustomImage.Status.READY,
+ modal_image_name=f"posthog-sandbox-custom-{image_count}:latest",
+ base_image_reference=base_image_reference,
+ )
+
+ @patch("products.tasks.backend.logic.services.custom_image_refresh.execute_build_sandbox_image_workflow")
+ @patch(
+ "products.tasks.backend.logic.services.custom_image_refresh.resolve_template_base_image_reference",
+ return_value="ghcr.io/posthog/posthog-sandbox-vm@sha256:current",
+ )
+ def test_refresh_dispatches_oldest_stale_image_with_batch_limit(self, _mock_reference, mock_execute) -> None:
+ oldest_stale = self._create_image(base_image_reference=None)
+ newer_stale = self._create_image(base_image_reference="ghcr.io/posthog/posthog-sandbox-vm@sha256:old")
+ current = self._create_image(base_image_reference="ghcr.io/posthog/posthog-sandbox-vm@sha256:current")
+ SandboxCustomImage.objects.for_team(self.team.id).filter(id=oldest_stale.id).update(
+ updated_at=timezone.now() - timedelta(days=1)
+ )
+
+ dispatched = refresh_stale_sandbox_custom_images(batch_size=1)
+
+ assert dispatched == 1
+ mock_execute.assert_called_once_with(str(oldest_stale.id), self.team.id, refresh=True)
+ oldest_stale.refresh_from_db()
+ newer_stale.refresh_from_db()
+ current.refresh_from_db()
+ assert oldest_stale.status == SandboxCustomImage.Status.BUILDING
+ assert newer_stale.status == SandboxCustomImage.Status.READY
+ assert current.status == SandboxCustomImage.Status.READY
+
+ already_attempted = self._create_image(base_image_reference="ghcr.io/posthog/posthog-sandbox-vm@sha256:old")
+ already_attempted.base_image_refresh_reference = "ghcr.io/posthog/posthog-sandbox-vm@sha256:current"
+ already_attempted.save(update_fields=["base_image_refresh_reference"])
+
+ assert refresh_stale_sandbox_custom_images() == 1
+ already_attempted.refresh_from_db()
+ assert already_attempted.status == SandboxCustomImage.Status.READY
+
+ @patch(
+ "products.tasks.backend.logic.services.custom_image_refresh.execute_build_sandbox_image_workflow",
+ side_effect=RuntimeError("temporal unavailable"),
+ )
+ @patch(
+ "products.tasks.backend.logic.services.custom_image_refresh.resolve_template_base_image_reference",
+ return_value="ghcr.io/posthog/posthog-sandbox-vm@sha256:current",
+ )
+ def test_refresh_restores_ready_status_when_dispatch_fails(self, _mock_reference, _mock_execute) -> None:
+ stale = self._create_image(base_image_reference="ghcr.io/posthog/posthog-sandbox-vm@sha256:old")
+
+ dispatched = refresh_stale_sandbox_custom_images()
+
+ assert dispatched == 0
+ stale.refresh_from_db()
+ assert stale.status == SandboxCustomImage.Status.READY
+ assert stale.base_image_refresh_reference is None
+
+ def test_refresh_build_failure_remains_ready_and_can_retry(self) -> None:
+ stale = self._create_image(base_image_reference="ghcr.io/posthog/posthog-sandbox-vm@sha256:old")
+ stale.status = SandboxCustomImage.Status.BUILDING
+ stale.base_image_refresh_reference = "ghcr.io/posthog/posthog-sandbox-vm@sha256:current"
+ stale.save(update_fields=["status", "base_image_refresh_reference"])
+
+ activity_body = cast(Callable[[MarkImageBuildFailedInput], None], vars(mark_image_build_failed)["__wrapped__"])
+ activity_body(
+ MarkImageBuildFailedInput(
+ image_id=str(stale.id),
+ team_id=self.team.id,
+ error="transient build failure",
+ refresh=True,
+ )
+ )
+
+ stale.refresh_from_db()
+ assert stale.status == SandboxCustomImage.Status.READY
+ assert stale.error == "transient build failure"
+ assert stale.base_image_refresh_reference is None