: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
chore(tasks): automate the sandbox agent pin bump (#104428)
Alessandro Pogliaghi79e603549d78
diff --git a/.github/workflows/cd-sandbox-base-image.yml b/.github/workflows/cd-sandbox-base-image.ymlindex 781b850d4ffd..48f9ce9a649a 100644--- a/.github/workflows/cd-sandbox-base-image.yml+++ b/.github/workflows/cd-sandbox-base-image.yml@@ -22,6 +22,10 @@ on:- 'products/notebooks/backend/kernel_package.py'workflow_dispatch:+concurrency:+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}+jobs:changes:runs-on: ubuntu-24.04@@ -310,7 +314,7 @@ jobs:contains(github.event.pull_request.labels.*.name, 'build-tasks-sandbox-image'))runs-on: depot-ubuntu-24.04- timeout-minutes: 15+ timeout-minutes: 20permissions:id-token: write # allow issuing OIDC tokens for this workflow runcontents: read # allow at least reading the repo contents, add other permissions if necessary@@ -355,7 +359,7 @@ jobs:file: ./products/tasks/backend/sandbox/images/Dockerfile.sandbox-basebuildx-fallback: false # the fallback is so slow it's better to just failpush: ${{ 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) }}+ tags: ghcr.io/posthog/posthog-sandbox-base:${{ github.sha }}platforms: linux/arm64,linux/amd64# AGENT_VERSION is not passed here: the Dockerfile's ARG default is the# pinned, reviewed version. Bump it there, not by resolving npm "latest".@@ -387,6 +391,40 @@ jobs:tags: ${{ github.ref == 'refs/heads/master' && format('ghcr.io/posthog/posthog-sandbox-streamlit:master,ghcr.io/posthog/posthog-sandbox-streamlit:{0}', github.sha) || format('ghcr.io/posthog/posthog-sandbox-streamlit:{0}', github.sha) }}platforms: linux/arm64,linux/amd64+ - name: Smoke the installed agent on both architectures+ if: github.event_name == 'pull_request' || vars.CD_DEPLOY_ENABLED == 'true'+ env:+ IMAGE: ghcr.io/posthog/posthog-sandbox-base:${{ github.sha }}+ run: |+ pinned=$(sed -n 's/^ARG AGENT_VERSION=//p' products/tasks/backend/sandbox/images/Dockerfile.sandbox-base)+ for platform in linux/amd64 linux/arm64; do+ echo "::group::$platform"+ installed=$(docker run --rm --platform "$platform" "$IMAGE" \+ node -p "require('/scripts/node_modules/@posthog/agent/package.json').version")+ if [ "$installed" != "$pinned" ]; then+ echo "::error::$platform image has @posthog/agent $installed, Dockerfile pins $pinned"+ exit 1+ fi+ docker run --rm --platform "$platform" "$IMAGE" \+ /scripts/node_modules/.bin/agent-server --help >/dev/null+ echo "@posthog/agent $installed starts on $platform"+ echo "::endgroup::"+ done++ - name: Promote the smoked base image to :master+ if: github.ref == 'refs/heads/master' && vars.CD_DEPLOY_ENABLED == 'true'+ env:+ IMAGE: ghcr.io/posthog/posthog-sandbox-base+ run: |+ docker buildx imagetools create --tag "$IMAGE:master" "$IMAGE:${{ github.sha }}"+ sha_digest=$(docker buildx imagetools inspect "$IMAGE:${{ github.sha }}" --format '{{json .Manifest.Digest}}')+ master_digest=$(docker buildx imagetools inspect "$IMAGE:master" --format '{{json .Manifest.Digest}}')+ if [ "$sha_digest" != "$master_digest" ]; then+ echo "::error::$IMAGE:master is $master_digest, expected $sha_digest"+ exit 1+ fi+ echo "$IMAGE:master -> $master_digest"+- parallel:- name: Build and push container image (pi)id: build-pidiff --git a/.github/workflows/desktop-agent-release.yml b/.github/workflows/desktop-agent-release.ymlindex 8f84e37aaac6..c93d039e97c7 100644--- a/.github/workflows/desktop-agent-release.yml+++ b/.github/workflows/desktop-agent-release.yml@@ -24,6 +24,8 @@ jobs:permissions:contents: readid-token: write+ outputs:+ version: ${{ steps.version.outputs.version }}defaults:run:working-directory: products/desktop@@ -70,23 +72,22 @@ jobs:env:NPM_CONFIG_PROVENANCE: true- rebuild-sandbox-images:- name: Rebuild tasks sandbox base images+ bump-sandbox-agent-pin:+ name: Open a PR bumping the sandbox agent pinneeds: release- runs-on: depot-ubuntu-24.04+ runs-on: ubuntu-24.04timeout-minutes: 5permissions:contents: readactions: writesteps:- # Same-repo dispatch: the agent now lives in this repository, so the- # cross-repo GH_APP_POSTHOG_WORKFLOW_TRIGGER app is retired and the- # ambient token dispatches the rebuild directly.- - name: Dispatch sandbox image rebuild+ - name: Dispatch the agent version bumpenv:GH_TOKEN: ${{ github.token }}+ AGENT_VERSION: ${{ needs.release.outputs.version }}run: |- echo "Dispatching sandbox base image rebuild for $GITHUB_REF_NAME"- gh workflow run cd-sandbox-base-image.yml \+ echo "Dispatching sandbox agent pin bump to $AGENT_VERSION"+ gh workflow run update-sandbox-agent-version.yml \--repo PostHog/posthog \- --ref master+ --ref master \+ -f version="$AGENT_VERSION"diff --git a/.github/workflows/update-sandbox-agent-version.yml b/.github/workflows/update-sandbox-agent-version.ymlnew file mode 100644index 000000000000..0965562bda6d--- /dev/null+++ b/.github/workflows/update-sandbox-agent-version.yml@@ -0,0 +1,262 @@+name: Update Sandbox Agent Version++on:+ schedule:+ - cron: '0 3 * * *'+ workflow_dispatch:+ inputs:+ version:+ description: 'Agent version to pin. Defaults to the npm "latest" dist-tag.'+ required: false+ type: string++permissions:+ contents: read++concurrency:+ group: update-sandbox-agent-version+ cancel-in-progress: false++jobs:+ update-sandbox-agent-version:+ runs-on: ubuntu-24.04+ timeout-minutes: 10++ env:+ DOCKERFILE: products/tasks/backend/sandbox/images/Dockerfile.sandbox-base+ BRANCH_PREFIX: chore/bump-sandbox-agent-version-+ AGENT_PATHS: products/desktop/packages/agent products/desktop/packages/enricher products/desktop/packages/git products/desktop/packages/harness products/desktop/packages/shared++ steps:+ - name: Guard - only run on master+ env:+ REF: ${{ github.ref }}+ run: |+ if [ "$REF" != "refs/heads/master" ]; then+ echo "::error::This workflow can only run on master (got $REF). Re-dispatch it from master."+ exit 1+ fi++ - name: Get app token+ id: app-token+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1+ with:+ client-id: ${{ vars.GH_APP_POSTHOG_SCHEDULED_ACTIONS_APP_ID }}+ private-key: ${{ secrets.GH_APP_POSTHOG_SCHEDULED_ACTIONS_PRIVATE_KEY }}+ permission-contents: write+ permission-pull-requests: write++ - name: Checkout repository+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ token: ${{ steps.app-token.outputs.token }}+ sparse-checkout: products/tasks/backend/sandbox/images/Dockerfile.sandbox-base+ sparse-checkout-cone-mode: false++ - name: Resolve the published agent version+ id: resolve+ env:+ REQUESTED_VERSION: ${{ inputs.version }}+ run: |+ latest="$REQUESTED_VERSION"+ for attempt in 1 2 3; do+ if [ -n "$latest" ]; then break; fi+ latest=$(npm view @posthog/agent version 2>/dev/null || true)+ if [ -n "$latest" ]; then break; fi+ echo "npm view returned nothing (attempt $attempt)"+ sleep $((attempt * 5))+ done+ if ! printf '%s' "$latest" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then+ echo "could not resolve a version for @posthog/agent (got '$latest')" >&2+ exit 1+ fi+ echo "latest=$latest" >> "$GITHUB_OUTPUT"+ echo "BRANCH=${BRANCH_PREFIX}${latest}" >> "$GITHUB_ENV"++ pinned=$(sed -n 's/^ARG AGENT_VERSION=//p' "$DOCKERFILE")+ if [ -z "$pinned" ]; then+ echo "no ARG AGENT_VERSION line in $DOCKERFILE" >&2+ exit 1+ fi+ echo "pinned=$pinned" >> "$GITHUB_OUTPUT"+ echo "Pinned $pinned, published $latest"++ - name: Decide what this run does+ id: state+ env:+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ REPO: ${{ github.repository }}+ LATEST: ${{ steps.resolve.outputs.latest }}+ PINNED: ${{ steps.resolve.outputs.pinned }}+ run: |+ current_pr=""+ stale_prs=""+ while read -r number head; do+ if [ -z "$number" ]; then continue; fi+ if [ "$head" = "$BRANCH" ]; then current_pr="$number"; else stale_prs="$stale_prs $number"; fi+ done <<< "$(gh pr list --state open --search '"bump sandbox @posthog/agent to" in:title' \+ --json number,headRefName,isCrossRepository \+ --jq ".[] | select(.isCrossRepository == false and (.headRefName | startswith(\"${BRANCH_PREFIX}\"))) | \"\(.number) \(.headRefName)\"")"++ if [ "$LATEST" = "$PINNED" ]; then+ action=noop+ echo "Pin already at $LATEST"+ else+ declined_by=$(gh api graphql -f query='query($q: String!) {+ search(query: $q, type: ISSUE, first: 10) { nodes { ... on PullRequest {+ headRepository { nameWithOwner }+ timelineItems(last: 1, itemTypes: [CLOSED_EVENT]) { nodes { ... on ClosedEvent { actor { __typename login } } } }+ } } } }' \+ -f q="repo:${REPO} is:pr is:closed is:unmerged head:${BRANCH} in:title \"bump sandbox @posthog/agent to ${LATEST}\"" \+ --jq ".data.search.nodes[] | select(.headRepository.nameWithOwner == \"${REPO}\") | .timelineItems.nodes[0].actor | select(.__typename == \"User\") | .login" | head -1)+ if [ -n "$declined_by" ]; then+ action=declined+ echo "::notice::$declined_by closed the bump PR for $LATEST without merging, so this run leaves the pin alone"+ elif [ -n "$current_pr" ]; then+ action=current+ echo "PR #$current_pr already proposes $LATEST"+ else+ action=bump+ fi+ fi++ if [ "$action" = noop ] || [ "$action" = declined ]; then+ stale_prs="$stale_prs${current_pr:+ $current_pr}"+ fi+ {+ echo "action=$action"+ echo "stale_prs=${stale_prs# }"+ } >> "$GITHUB_OUTPUT"++ - name: Bump the pin+ if: steps.state.outputs.action == 'bump'+ env:+ LATEST: ${{ steps.resolve.outputs.latest }}+ run: |+ sed -i "s/^ARG AGENT_VERSION=.*/ARG AGENT_VERSION=${LATEST}/" "$DOCKERFILE"+ if git diff --quiet "$DOCKERFILE"; then+ echo "could not rewrite ARG AGENT_VERSION in $DOCKERFILE" >&2+ exit 1+ fi+ git diff "$DOCKERFILE"++ - name: Summarize what the bump ships+ if: steps.state.outputs.action == 'bump'+ env:+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ REPO: ${{ github.repository }}+ LATEST: ${{ steps.resolve.outputs.latest }}+ PINNED: ${{ steps.resolve.outputs.pinned }}+ run: |+ from_tag="agent-v${PINNED}"+ to_tag="agent-v${LATEST}"+ compare="https://github.com/${REPO}/compare/${from_tag}...${to_tag}"+ {+ echo "## What this ships"+ echo+ if ! since=$(gh api "repos/${REPO}/commits/${from_tag}" --jq '.commit.committer.date' 2>/dev/null); then+ echo "_No \`${from_tag}\` tag, so the commit list is unavailable. Compare on GitHub: [\`${from_tag}...${to_tag}\`](${compare})._"+ else+ from_sha=$(gh api "repos/${REPO}/commits/${from_tag}" --jq '.sha')+ commits=$(for path in $AGENT_PATHS; do+ gh api --paginate "repos/${REPO}/commits?sha=${to_tag}&path=${path}&since=${since}&per_page=100" \+ --jq '.[] | "\(.sha) \(.commit.message | split("\n")[0])"'+ done | grep -v "^${from_sha} " | sort -u -k1,1 | sort -k2)+ count=$(printf '%s' "$commits" | grep -c . || true)+ echo "Agent commits between \`${from_tag}\` and \`${to_tag}\` ([compare](${compare})): ${count}"+ echo+ printf '%s\n' "$commits" | sed -E 's/^([0-9a-f]{40}) (.*)$/- \2 \1/'+ fi+ echo+ echo "### Dependency changes in the published package"+ echo+ deps_ok=true+ for v in "$PINNED" "$LATEST"; do+ if ! npm view "@posthog/agent@${v}" dependencies --json > "deps-${v}.json" 2>/dev/null; then+ deps_ok=false+ fi+ jq -r 'to_entries[] | "\(.key) \(.value)"' "deps-${v}.json" 2>/dev/null | sort > "deps-${v}.txt" || deps_ok=false+ done+ if [ "$deps_ok" != true ]; then+ echo "_Unavailable: npm did not return the dependencies for both versions._"+ elif changed=$(diff "deps-${PINNED}.txt" "deps-${LATEST}.txt" | grep -E '^[<>]'); then+ echo '```diff'+ printf '%s\n' "$changed" | sed -E 's/^< /- /; s/^> /+ /'+ echo '```'+ else+ echo "None."+ fi+ } > delta.md+ cat delta.md++ - name: Close bump PRs this run supersedes+ if: steps.state.outputs.stale_prs != ''+ env:+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ STALE_PRS: ${{ steps.state.outputs.stale_prs }}+ run: |+ for number in $STALE_PRS; do+ gh pr close "$number" --delete-branch+ echo "Closed PR #$number and deleted its branch"+ done++ - name: Reset branch to checked-out SHA+ if: steps.state.outputs.action == 'bump'+ env:+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ TARGET_SHA: ${{ github.sha }}+ run: |+ if gh api "repos/${{ github.repository }}/git/ref/heads/$BRANCH" >/dev/null 2>&1; then+ gh api -X PATCH "repos/${{ github.repository }}/git/refs/heads/$BRANCH" \+ -f sha="$TARGET_SHA" -F force=true+ echo "Force-reset branch to $TARGET_SHA"+ else+ gh api "repos/${{ github.repository }}/git/refs" -f ref="refs/heads/$BRANCH" -f sha="$TARGET_SHA"+ echo "Created branch at $TARGET_SHA"+ fi++ - name: Commit via GitHub API (signed)+ if: steps.state.outputs.action == 'bump'+ uses: planetscale/ghcommit-action@25309d8005ac7c3bcd61d3fe19b69e0fe47dbdde # v0.2.20+ with:+ commit_message: 'chore(tasks): bump sandbox @posthog/agent to ${{ steps.resolve.outputs.latest }}'+ repo: ${{ github.repository }}+ branch: ${{ env.BRANCH }}+ file_pattern: products/tasks/backend/sandbox/images/Dockerfile.sandbox-base+ env:+ GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}++ - name: Create the pull request+ if: steps.state.outputs.action == 'bump'+ env:+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ LATEST: ${{ steps.resolve.outputs.latest }}+ PINNED: ${{ steps.resolve.outputs.pinned }}+ run: |+ {+ cat <<BODY+ ## Problem++ The sandbox base image pins \`@posthog/agent\` so a published release cannot reach production sandboxes without a reviewed commit. That pin is at \`${PINNED}\`; npm now serves \`${LATEST}\`.++ ## Changes++ - \`Dockerfile.sandbox-base\`: \`AGENT_VERSION\` \`${PINNED}\` to \`${LATEST}\`.++ Merging this builds and ships the image on \`${LATEST}\`. Closing it without merging keeps \`${PINNED}\` until the next release. A newer release opens its own PR and closes this one.++ BODY+ cat delta.md+ cat <<BODY++ ## How did you test this code?++ The sandbox image CD workflow builds this PR's image on both architectures, checks that the installed \`@posthog/agent\` matches the pin, and runs the \`agent-server\` entrypoint. That covers packaging and dependency resolution. The agent's own test suite ran before the release was published.+ BODY+ } > body.md+ gh pr create \+ --title "chore(tasks): bump sandbox @posthog/agent to ${LATEST}" \+ --body-file body.md \+ --base master \+ --head "$BRANCH" \+ --label "automated" --label "dependencies" --label "skip-agent-review"diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.mdindex e747a4b76531..6c05d1f8b34e 100644--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md@@ -627,10 +627,10 @@ for readiness before signaling completion, then checks persisted status, error,sandbox shutdown. It does not test Django API authentication or LLM task execution.These tests consume the published sandbox image, not the agent source in the checkout.-An agent release triggers a separate sandbox image build that installs the published-package and updates the shared image. Running backend tests against that image alone-does not validate an unpublished agent change. A release check must exercise the-candidate image before promoting it to the shared tag.+The image pins the agent version in `Dockerfile.sandbox-base`.+An agent release opens a pull request that bumps that pin, and merging it rebuilds the shared image.+That build checks the installed agent against the pin and starts the `agent-server` entrypoint on both architectures before the image is promoted.+Running backend tests against that image alone does not validate an unpublished agent change.## Questions?diff --git a/products/desktop/packages/agent/README.md b/products/desktop/packages/agent/README.mdindex 2579e385d8d3..8c97d374f237 100644--- a/products/desktop/packages/agent/README.md+++ b/products/desktop/packages/agent/README.md@@ -278,7 +278,7 @@ Releases are automatic. There is no manual version bump: `package.json` stays at1. A merge to `master` that changes a file in this package or `products/desktop/packages/harness` runs `.github/workflows/desktop-agent-tag.yml`.2. It pushes the tag `agent-vX.Y.Z`. `Z` counts commits that change either package since the base tag `agent-vX.Y.0`. A commit that changes both packages counts once.-3. The tag push runs `.github/workflows/desktop-agent-release.yml`, which builds, tests and publishes to npm with provenance, then rebuilds the sandbox base images.+3. The tag push runs `.github/workflows/desktop-agent-release.yml`, which builds, tests and publishes to npm with provenance, then opens a pull request that bumps the agent pin in `Dockerfile.sandbox-base`. Merging that pull request builds and ships the sandbox images.A merge that changes neither package adds no new version.A change to either agent workflow file still runs the tag job, so it releases any package commits that have no tag yet.diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.mdindex 7eeba45de8d8..4034a6279b2c 100644--- a/products/posthog_ai/eval_harness/README.md+++ b/products/posthog_ai/eval_harness/README.md@@ -114,11 +114,10 @@ Use Docker for small smoke tests or when remote access is unavailable.Each container defaults to 16 GB, so host RAM is what bounds concurrency: the default cap is 4, and raising `--max-sandboxes` needs a big host.A case running notebook python or duckdb cells holds a second container on top of that (see [Notebook kernel sandboxes](#notebook-kernel-sandboxes)), which the sandbox cap does not count.-Every docker run verifies the `posthog-sandbox-base` image is fresh before any case starts: it rebuilds when `@posthog/agent` has published a newer version than the one baked into the image, or when the Dockerfile changed since the image was built.+Every docker run verifies the `posthog-sandbox-base` image is fresh before any case starts: it rebuilds when the `ARG AGENT_VERSION` pin in the Dockerfile differs from the version baked into the image, or when the Dockerfile changed since the image was built.An unchanged image passes the check in under a second, and even a rebuild is mostly layer-cached — only the npm install layer onward re-runs when the agent version moved.-When npm is unreachable the check warns and reuses the existing image instead of failing the run.`--rebuild-sandbox-image` forces the rebuild regardless.-(The modal DEBUG image is rebuilt by Modal whenever the Dockerfile or build context changes, but a new `@posthog/agent` publish alone does not invalidate it — a known limitation.)+(Modal rebuilds the DEBUG image whenever the Dockerfile or build context changes, so a pin bump reaches it the same way.)**modal** runs sandboxes remotely.Modal's network cannot reach `localhost`, so the harness exposes the host services via Tailscale Funnel itself and points the sandbox at the public URLs.diff --git a/products/posthog_ai/eval_harness/harness/README.md b/products/posthog_ai/eval_harness/harness/README.mdindex 07b80913f194..c807f2348979 100644--- a/products/posthog_ai/eval_harness/harness/README.md+++ b/products/posthog_ai/eval_harness/harness/README.md@@ -54,7 +54,7 @@ The bootstrap is deliberately synchronous and runs before any event loop exists,3. `personhog-replica` (`:15051`) and `personhog-router` (`:15052`) start against the test persons database — before anything can query, so a dead router never poisons the negative group-types cache.4. `EvalLiveServer` serves PostHog's ASGI application on `0.0.0.0:18000`, including the sandbox event-ingest route.5. The LLM gateway (`:13308`) starts and local skills are built. In bundled mode, the MCP server (`:18787`) starts with exec skill distribution forced off. In exec mode, the skills are packaged, the local archive server (`:18788`) starts, and MCP receives its content-addressed URL with distribution forced on.-6. Docker only: the `posthog-sandbox-base` image freshness check runs (rebuilding on a new `@posthog/agent` version or Dockerfile change). Modal only: Tailscale Funnel comes up, exposing the callback services publicly.+6. Docker only: the `posthog-sandbox-base` image freshness check runs (rebuilding when the Dockerfile or its agent pin changed). Modal only: Tailscale Funnel comes up, exposing the callback services publicly.7. Bundled mode bind-mounts the built skills on Docker and bakes them into the Modal image. Exec mode suppresses those skills and clears native skill directories before every case; `disable_bundled_skills=True` remains available as a per-case override in other modes.8. The master Hedgebox team is seeded.diff --git a/products/posthog_ai/eval_harness/harness/providers.py b/products/posthog_ai/eval_harness/harness/providers.pyindex 413b868b4e03..8dae5236b06c 100644--- a/products/posthog_ai/eval_harness/harness/providers.py+++ b/products/posthog_ai/eval_harness/harness/providers.py@@ -201,9 +201,9 @@ class DockerProviderStrategy(SandboxProviderStrategy):raise PreflightError("The Docker daemon is not reachable. Start Docker and retry.")def start(self, stack: ExitStack) -> None:- # Verify posthog-sandbox-base is fresh (rebuilding when @posthog/agent published a- # newer version or the Dockerfile changed) before any case grabs a sandbox, so a- # stale image can't break the whole run. Imported here because it pulls in Django.+ # Verify posthog-sandbox-base is fresh (rebuilding when the Dockerfile or its+ # agent pin changed) before any case grabs a sandbox, so a stale image can't+ # break the whole run. Imported here because it pulls in Django.from products.tasks.backend.logic.services.docker_sandbox import ( # noqa: PLC0415 — Django import, kept off the harness import pathensure_fresh_base_image,ensure_template_image,diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.pyindex 8fd1839684b4..3dadbcf9470a 100644--- a/products/tasks/backend/logic/services/docker_sandbox.py+++ b/products/tasks/backend/logic/services/docker_sandbox.py@@ -1,6 +1,7 @@from __future__ import annotationsimport os+import reimport jsonimport timeimport uuid@@ -1301,37 +1302,27 @@ def _none_if_blank(value: str) -> str | None:return value-def _resolve_latest_agent_version() -> str | None:- """Latest published @posthog/agent version, or ``None`` if npm is unavailable.-- Any failure (npm missing, nonzero exit, timeout) resolves to ``None`` so the caller- can fall back to reusing the existing image rather than failing the whole run.- """+def _pinned_agent_version(dockerfile_path: str) -> str | None:try:- result = subprocess.run(- ["npm", "view", "@posthog/agent", "version"],- capture_output=True,- text=True,- timeout=15,- )- except Exception:- return None- if result.returncode != 0:+ source = Path(dockerfile_path).read_text(encoding="utf-8")+ except OSError:return None- return result.stdout.strip() or None+ match = re.search(r"^ARG AGENT_VERSION=(\S+)", source, re.MULTILINE)+ return match.group(1) if match else Nonedef ensure_fresh_base_image(*, force: bool = False) -> None:"""Rebuild ``posthog-sandbox-base`` when it is stale, otherwise reuse it.Stale means any of: ``force``; the image is missing; the Dockerfile changed since the- image was built; or @posthog/agent published a newer version than the one baked in.- This is the only place that reaches out to npm.+ image was built; or the baked agent version differs from the Dockerfile's pin."""dockerfile_path = _base_dockerfile_path()current_dockerfile_sha = _base_image_source_sha(dockerfile_path)- latest = _resolve_latest_agent_version()+ pinned = _pinned_agent_version(dockerfile_path)+ if pinned is None:+ raise RuntimeError(f"no ARG AGENT_VERSION in {dockerfile_path}")# A nonzero exit means the image is missing; otherwise the two labels come back# tab-separated (or "<no value>" for a label the image predates).@@ -1355,9 +1346,7 @@ def ensure_fresh_base_image(*, force: bool = False) -> None:image_agent_version = _none_if_blank(parts[1]) if len(parts) > 1 else Nonedockerfile_changed = image_dockerfile_sha is None or image_dockerfile_sha != current_dockerfile_sha- agent_stale = latest is not None and (- image_agent_version is None or image_agent_version == "unknown" or image_agent_version != latest- )+ agent_stale = image_agent_version is None or image_agent_version == "unknown" or image_agent_version != pinnedif force:reason = "forced"@@ -1366,32 +1355,24 @@ def ensure_fresh_base_image(*, force: bool = False) -> None:elif dockerfile_changed:reason = "dockerfile changed"elif agent_stale:- reason = f"stale agent version (have {image_agent_version!r}, latest {latest!r})"+ reason = f"stale agent version (have {image_agent_version!r}, pinned {pinned!r})"else:reason = Noneif reason is None:- if latest is None:- # npm unreachable but the on-disk image still matches the Dockerfile — the best- # we can do offline is trust it rather than fail or force a needless rebuild.- logger.warning(- "could not check @posthog/agent freshness (npm unreachable); reusing existing posthog-sandbox-base"- )- else:- logger.info("posthog-sandbox-base is up to date (agent %s); reusing existing image", latest)+ logger.info("posthog-sandbox-base is up to date (agent %s); reusing existing image", pinned)return# Passing the agent version as COMMIT_HASH lets docker's layer cache no-op the npm# install layer when the version is unchanged, and re-run exactly that layer onward- # when it changed. When we can't resolve a version, fall back to a unique cache-bust.- cache_bust = latest or f"force-{int(time.time())}"+ # when it changed.logger.info("Rebuilding posthog-sandbox-base: %s", reason)DockerSandbox._build_image_if_needed(DEFAULT_IMAGE_NAME,dockerfile_path,- build_args={"COMMIT_HASH": cache_bust},+ build_args={"COMMIT_HASH": pinned},labels={- _AGENT_VERSION_LABEL: latest or "unknown",+ _AGENT_VERSION_LABEL: pinned,_DOCKERFILE_SHA_LABEL: current_dockerfile_sha,},force=True,diff --git a/products/tasks/backend/logic/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.pyindex 587914a4c672..b1907a22733b 100644--- a/products/tasks/backend/logic/services/test_docker_sandbox.py+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py@@ -1,6 +1,7 @@from __future__ import annotationsimport os+import reimport shleximport subprocessfrom typing import TYPE_CHECKING, Any@@ -15,7 +16,11 @@ from products.tasks.backend.logic.services.agent_server_launcher import (AGENT_SERVER_LAUNCH_CAPABILITIES,AGENT_SERVER_PREFLIGHT_CAPABILITY_PREFIX,)-from products.tasks.backend.logic.services.docker_sandbox import DockerSandbox+from products.tasks.backend.logic.services.docker_sandbox import (+ DockerSandbox,+ _base_dockerfile_path,+ _pinned_agent_version,+)from products.tasks.backend.logic.services.local_skills import ENV_DISABLE_BUNDLED_SKILLS, ENV_LOCAL_SKILLS_HOST_PATHfrom products.tasks.backend.logic.services.sandbox import (ExecutionResult,@@ -28,6 +33,8 @@ from products.tasks.backend.logic.services.sandbox import ()if TYPE_CHECKING:+ from pathlib import Path+from pytest_django.fixtures import Settings@@ -1013,3 +1020,17 @@ class TestDockerSandboxIntegration:assert result.stdout.strip() != ""finally:DockerSandbox.delete_snapshot(snapshot_id)+++class TestPinnedAgentVersion:+ def test_reads_a_semver_from_the_base_dockerfile(self) -> None:+ version = _pinned_agent_version(_base_dockerfile_path())++ assert version is not None+ assert re.fullmatch(r"\d+\.\d+\.\d+", version), version++ def test_ignores_lines_that_are_not_the_arg(self, tmp_path: Path) -> None:+ dockerfile = tmp_path / "Dockerfile"+ dockerfile.write_text("FROM scratch\nENV AGENT_VERSION=1.2.3\n# ARG AGENT_VERSION=4.5.6\n")++ assert _pinned_agent_version(str(dockerfile)) is None