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.

feat(data-warehouse): implement e2b import source (#69999)

Tom Owers22a7b49b9740
diff --git a/frontend/public/services/e2b.png b/frontend/public/services/e2b.png
new file mode 100644
index 000000000000..c7f0bb3edf5c
Binary files /dev/null and b/frontend/public/services/e2b.png differ
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 89ff7c7fb917..ae7f973a6609 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -156,6 +156,7 @@ the row lists both.
| doit | HTTP | requests | ✅ |
| dropbox_sign | HTTP | requests | ✅ |
| drip | HTTP | requests | ✅ |
+| e2b | HTTP | requests | ✅ |
| e_conomic | HTTP | requests | ✅ |
| easypost | HTTP | requests | ✅ |
| easypromos | HTTP | requests | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/canonical_descriptions.py
new file mode 100644
index 000000000000..ea658a6a1ec3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/canonical_descriptions.py
@@ -0,0 +1,62 @@
+"""Canonical, documentation-sourced descriptions for E2B endpoints and columns.
+
+Sourced from the official E2B OpenAPI spec (https://github.com/e2b-dev/infra/blob/main/spec/openapi.yml)
+and the E2B API reference (https://e2b.dev/docs). Keyed by the endpoint names in `settings.py`
+`E2B_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced table. Columns absent here fall
+back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "sandboxes": {
+ "description": "Running and paused sandboxes for the team. Terminated sandboxes are not listed here.",
+ "docs_url": "https://e2b.dev/docs",
+ "columns": {
+ "sandboxID": "Identifier of the sandbox.",
+ "templateID": "Identifier of the template the sandbox was created from.",
+ "alias": "Alias of the template.",
+ "clientID": "Identifier of the client (deprecated).",
+ "startedAt": "Time when the sandbox was started.",
+ "endAt": "Time when the sandbox will expire.",
+ "cpuCount": "Number of virtual CPUs allocated to the sandbox.",
+ "memoryMB": "Memory allocated to the sandbox, in MiB.",
+ "diskSizeMB": "Disk size allocated to the sandbox, in MiB.",
+ # `metadata` is deliberately not synced — it can hold user-stored secrets. See `SENSITIVE_FIELDS`.
+ "state": "State of the sandbox (running or paused).",
+ "envdVersion": "Version of the envd daemon running in the sandbox.",
+ },
+ },
+ "templates": {
+ "description": "Sandbox templates available to the team (public and team-private).",
+ "docs_url": "https://e2b.dev/docs",
+ "columns": {
+ "templateID": "Identifier of the template.",
+ "buildID": "Identifier of the last successful build for the template.",
+ "cpuCount": "Number of virtual CPUs the template provisions.",
+ "memoryMB": "Memory the template provisions, in MiB.",
+ "diskSizeMB": "Disk size the template provisions, in MiB.",
+ "public": "Whether the template is public or only accessible by the team.",
+ "aliases": "Aliases of the template (deprecated).",
+ "names": "Names of the template (namespace/alias format when namespaced).",
+ "createdAt": "Time when the template was created.",
+ "updatedAt": "Time when the template was last updated.",
+ "createdBy": "The team member who created the template.",
+ "lastSpawnedAt": "Time when the template was last used to start a sandbox.",
+ "spawnCount": "Number of times the template has been used.",
+ "buildCount": "Number of times the template has been built.",
+ "envdVersion": "Version of the envd daemon baked into the template.",
+ "buildStatus": "Status of the template's most recent build.",
+ },
+ },
+ "snapshots": {
+ "description": "Snapshots of paused sandboxes for the team.",
+ "docs_url": "https://e2b.dev/docs",
+ "columns": {
+ "snapshotID": "Identifier of the snapshot template including the tag.",
+ "names": "Full names of the snapshot template including team namespace and tag.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/e2b.md b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/e2b.md
new file mode 100644
index 000000000000..bc02332f51f4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/e2b.md
@@ -0,0 +1,57 @@
+<!--
+This is the user-facing posthog.com documentation for the E2B source. It lives here because no
+posthog.com checkout was available when the source was implemented. Before release, move it to
+`posthog.com/contents/docs/cdp/sources/e2b.md` (served at /docs/cdp/sources/e2b) and run
+`python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`.
+-->
+
+---
+
+title: Linking E2B as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: E2B
+beta: true
+
+---
+
+import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"
+import SyncModes from "../\_snippets/sync-modes.mdx"
+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"
+import AlphaRelease from "../\_snippets/alpha-release.mdx"
+
+<AlphaRelease />
+
+[E2B](https://e2b.dev) runs secure cloud sandboxes for executing AI-agent-generated code. Linking E2B as a source syncs your sandbox infrastructure inventory — running and paused sandboxes, templates, and snapshots — into the PostHog data warehouse, so you can join agent sandbox activity with your product analytics.
+
+## Prerequisites
+
+Before connecting, you need a team-scoped E2B API key (prefixed `e2b_`). You can create one self-serve in your [E2B dashboard](https://e2b.dev/dashboard).
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+Provide your E2B API key. The key is team-scoped and is sent in the `X-API-Key` header on every request. E2B uses a single global API host (`api.e2b.app`); there are no regional endpoints to configure.
+
+## Sync modes
+
+<SyncModes />
+
+E2B's list endpoints are point-in-time inventories and do not expose a server-side timestamp filter, so every table syncs as a full refresh. Each run replaces the table with the current state, deduplicated on the table's primary key.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+- **Invalid or revoked API key**: reconnect with a fresh team-scoped key from your E2B dashboard. Sandbox syncs that hit a `401` or `403` stop rather than retrying, since a credential problem cannot be resolved by retrying.
+- **Terminated sandboxes are missing**: the `sandboxes` table only lists running and paused sandboxes. E2B does not expose terminated sandboxes through the list API, so they never appear here.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/e2b.py b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/e2b.py
new file mode 100644
index 000000000000..b587915629e1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/e2b.py
@@ -0,0 +1,184 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.e2b.settings import E2B_ENDPOINTS
+
+# E2B exposes a single global base URL; there are no regional hosts.
+E2B_BASE_URL = "https://api.e2b.app"
+
+# Cursor pagination: `limit` maxes out at 100, and the next cursor is returned in this response header.
+E2B_PAGE_LIMIT = 100
+NEXT_TOKEN_HEADER = "X-Next-Token"
+
+# E2B lets users stash arbitrary key/value data on a sandbox, and its own docs suggest keeping secrets
+# (API keys, tokens) there. Writing it to the warehouse table would let anyone with table read access
+# read credentials they can't see in the protected source config, so we drop it before ingesting.
+SENSITIVE_FIELDS = ("metadata",)
+
+
+def _scrub(item: Any) -> Any:
+ if not isinstance(item, dict):
+ return item
+ return {key: value for key, value in item.items() if key not in SENSITIVE_FIELDS}
+
+
+class E2BRetryableError(Exception):
+ pass
+
+
+class E2BResumeConfig:
+ # Opaque cursor to fetch the next page from (E2B's `nextToken`). `None` starts at the first page.
+ # A job only ever syncs one endpoint, so a single token slot is unambiguous.
+ next_token: str | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "X-API-Key": api_key,
+ "Accept": "application/json",
+ }
+
+
+def validate_credentials(api_key: str) -> bool:
+ # Cheapest authenticated probe: list a single sandbox. 200 means the team-scoped key is genuine,
+ # 401/403 means it isn't. Anything else — a timeout, connection error, rate limit, or 5xx — is a
+ # transient upstream problem that says nothing about the key, so raise rather than mislabel a valid
+ # key "invalid" and send the user down the wrong recovery path.
+ # `redact_values` masks the key from tracked HTTP samples (the `X-API-Key` header isn't on the
+ # generic scrubber's denylist); `allow_redirects=False` keeps the key from replaying to another host;
+ # `capture=False` keeps the raw response body out of sample storage, since a sandbox's user-set
+ # metadata can carry secrets the name-based scrubbers can't recognise (see `SENSITIVE_FIELDS`).
+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False)
+ response = session.get(
+ f"{E2B_BASE_URL}/v2/sandboxes",
+ headers=_get_headers(api_key),
+ params={"limit": 1},
+ timeout=10,
+ )
+ if response.status_code == 200:
+ return True
+ if response.status_code in (401, 403):
+ return False
+ raise E2BRetryableError(f"E2B credential probe failed (retryable): status={response.status_code}")
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ E2BRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> requests.Response:
+ response = session.get(url, headers=headers, params=params, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise E2BRetryableError(f"E2B API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"E2B API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[E2BResumeConfig],
+) -> Iterator[Any]:
+ config = E2B_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ # One session reused across every page so urllib3 keeps the connection alive. `redact_values` masks
+ # the key from tracked HTTP samples; `allow_redirects=False` keeps it from replaying to another host;
+ # `capture=False` keeps raw response bodies (which can hold secret-bearing sandbox metadata that the
+ # name-based scrubbers miss) out of sample storage, since `_scrub` only runs after capture.
+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False)
+ url = f"{E2B_BASE_URL}{config.path}"
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ next_token = resume.next_token if resume else None
+ if next_token:
+ logger.debug(f"E2B: resuming {endpoint} from cursor")
+
+ while True:
+ params: dict[str, Any] = {"limit": E2B_PAGE_LIMIT}
+ if next_token:
+ params["nextToken"] = next_token
+
+ response = _fetch_page(session, url, headers, params, logger)
+ items = response.json()
+ # E2B list endpoints return a bare JSON array, not a wrapped `{data: [...]}` envelope.
+ if not isinstance(items, list):
+ logger.warning(f"E2B: unexpected non-list response for {endpoint}, stopping")
+ break
+
+ page_token = response.headers.get(NEXT_TOKEN_HEADER) or None
+
+ for item in items:
+ batcher.batch(_scrub(item))
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it;
+ # merge dedupes on the primary key. Only persist while there's another page to fetch.
+ if page_token:
+ resumable_source_manager.save_state(E2BResumeConfig(next_token=page_token))
+
+ # Terminate when the API stops handing back a cursor, or hands back the same one (defensive
+ # guard against an endpoint that echoes the token instead of dropping it).
+ if not page_token or page_token == next_token:
+ break
+ next_token = page_token
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def e2b_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[E2BResumeConfig],
+) -> SourceResponse:
+ config = E2B_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/settings.py
new file mode 100644
index 000000000000..bc72f85fb1e7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/settings.py
@@ -0,0 +1,49 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@dataclass
+class E2BEndpointConfig:
+ name: str
+ path: str
+ # Field to partition by. Must be a STABLE creation-style timestamp so partitions don't
+ # rewrite on every sync; `None` for endpoints whose rows carry no timestamp.
+ partition_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ should_sync_default: bool = True
+
+
+# E2B's list endpoints are point-in-time inventories reachable with a team-scoped API key. None of
+# them expose a server-side timestamp filter, so every endpoint is full refresh (see the source's
+# `get_schemas`). Cursor pagination (`nextToken` request param + `X-Next-Token` response header) lets
+# a single run resume mid-list after a heartbeat timeout without restarting.
+E2B_ENDPOINTS: dict[str, E2BEndpointConfig] = {
+ # GET /v2/sandboxes — running and paused sandboxes. Terminated sandboxes are not listed here.
+ "sandboxes": E2BEndpointConfig(
+ name="sandboxes",
+ path="/v2/sandboxes",
+ partition_key="startedAt",
+ primary_keys=["sandboxID"],
+ ),
+ # GET /v2/templates — the team's sandbox templates.
+ "templates": E2BEndpointConfig(
+ name="templates",
+ path="/v2/templates",
+ partition_key="createdAt",
+ primary_keys=["templateID"],
+ ),
+ # GET /snapshots — paused-sandbox snapshots for the team. `SnapshotInfo` carries no timestamp,
+ # so there is no stable partition key.
+ "snapshots": E2BEndpointConfig(
+ name="snapshots",
+ path="/snapshots",
+ primary_keys=["snapshotID"],
+ ),
+}
+
+ENDPOINTS = tuple(E2B_ENDPOINTS.keys())
+
+# No endpoint exposes a server-side timestamp filter, so none is incremental.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/source.py
index 9f72ad644abb..4d4664769a08 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/source.py
@@ -1,19 +1,39 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.e2b.e2b import (
+ E2BResumeConfig,
+ e2b_source,
+ validate_credentials as validate_e2b_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.e2b.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import E2BSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class E2BSource(SimpleSource[E2BSourceConfig]):
+class E2BSource(ResumableSource[E2BSourceConfig, E2BResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.E2B
@@ -24,8 +44,94 @@ class E2BSource(SimpleSource[E2BSourceConfig]):
name=SchemaExternalDataSourceType.E2_B,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="E2B",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your E2B API key to sync your sandbox infrastructure data into the PostHog Data warehouse.
+
+You can create a team-scoped API key (prefixed `e2b_`) in your [E2B dashboard](https://e2b.dev/dashboard).""",
iconPath="/static/services/e2b.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/e2b",
keywords=["sandbox", "ai agents", "code execution", "infrastructure"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="e2b_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.e2b.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked API key surfaces as an HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.
+ "401 Client Error: Unauthorized for url: https://api.e2b.app": "Your E2B API key is invalid or has been revoked. Create a new team-scoped API key in your E2B dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.e2b.app": "Your E2B API key does not have access to this data. Check the key's team scope in your E2B dashboard, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: E2BSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every E2B list endpoint is a point-in-time inventory with no server-side timestamp filter,
+ # so all are full refresh (no incremental / append).
+ def _build_schema(endpoint: str) -> SourceSchema:
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: E2BSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ if validate_e2b_credentials(config.api_key):
+ return True, None
+ return False, "Invalid E2B API key"
+ except Exception:
+ # The probe couldn't reach E2B (timeout, rate limit, or a 5xx). That says nothing about the
+ # key, so point the user at retrying rather than at their credentials.
+ return (
+ False,
+ "Couldn't reach E2B to validate your API key. This is usually temporary, so try again in a moment.",
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[E2BResumeConfig]:
+ return ResumableSourceManager[E2BResumeConfig](inputs, E2BResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: E2BSourceConfig,
+ resumable_source_manager: ResumableSourceManager[E2BResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return e2b_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/tests/test_e2b.py b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/tests/test_e2b.py
new file mode 100644
index 000000000000..9406c0f635f3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/tests/test_e2b.py
@@ -0,0 +1,228 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.e2b import e2b
+from products.warehouse_sources.backend.temporal.data_imports.sources.e2b.e2b import (
+ E2BResumeConfig,
+ e2b_source,
+ get_rows,
+ validate_credentials,
+)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: E2BResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[E2BResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> E2BResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: E2BResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _response(items: Any, next_token: str | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.json.return_value = items
+ response.headers = {"X-Next-Token": next_token} if next_token else {}
+ return response
+
+
+def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: list[MagicMock], endpoint: str = "sandboxes"):
+ """Drive get_rows with a scripted sequence of pages, recording the nextToken each fetch sent."""
+ sent_tokens: list[str | None] = []
+ pages_iter = iter(pages)
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], params: dict[str, Any], logger: Any) -> MagicMock:
+ sent_tokens.append(params.get("nextToken"))
+ return next(pages_iter)
+
+ monkeypatch.setattr(e2b, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for table in get_rows(api_key="e2b_test", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=manager): # type: ignore[arg-type]
+ rows.extend(table.to_pylist())
+ return rows, sent_tokens
+
+
+class TestPagination:
+ def test_follows_next_token_header_across_pages(self, monkeypatch: Any) -> None:
+ # The paginator must chase the X-Next-Token header; stopping after page one silently drops data.
+ pages = [_response([{"sandboxID": "a"}, {"sandboxID": "b"}], next_token="t1"), _response([{"sandboxID": "c"}])]
+ rows, sent_tokens = _collect(_FakeResumableManager(), monkeypatch, pages)
+ assert rows == [{"sandboxID": "a"}, {"sandboxID": "b"}, {"sandboxID": "c"}]
+ # First page requested with no cursor, second page with the header token.
+ assert sent_tokens == [None, "t1"]
+
+ def test_terminates_when_token_repeats(self, monkeypatch: Any) -> None:
+ # An endpoint that echoes the same cursor instead of dropping it must not loop forever.
+ pages = [_response([{"sandboxID": "a"}], next_token="same"), _response([{"sandboxID": "b"}], next_token="same")]
+ rows, sent_tokens = _collect(_FakeResumableManager(), monkeypatch, pages)
+ assert rows == [{"sandboxID": "a"}, {"sandboxID": "b"}]
+ assert sent_tokens == [None, "same"]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ # A resumed run must start from the persisted cursor, not re-page from the beginning.
+ manager = _FakeResumableManager(E2BResumeConfig(next_token="resume_tok"))
+ pages = [_response([{"sandboxID": "x"}])]
+ rows, sent_tokens = _collect(manager, monkeypatch, pages)
+ assert rows == [{"sandboxID": "x"}]
+ assert sent_tokens == ["resume_tok"]
+
+ def test_non_list_response_stops_without_crashing(self, monkeypatch: Any) -> None:
+ # A wrapped/error body must be tolerated rather than raising while iterating a dict.
+ pages = [_response({"code": 500, "message": "boom"})]
+ rows, _ = _collect(_FakeResumableManager(), monkeypatch, pages)
+ assert rows == []
+
+ def test_builds_a_redacted_redirect_pinned_uncaptured_session(self, monkeypatch: Any) -> None:
+ # The sync session carries the same X-API-Key header the scrubber can't see, so it must redact the
+ # key and refuse redirects; `capture=False` keeps secret-bearing sandbox metadata out of sample
+ # storage, which the row-level `_scrub` can't do (it only runs after capture).
+ session = MagicMock()
+ monkeypatch.setattr(e2b, "_fetch_page", lambda *a, **k: _response([]))
+ with patch.object(e2b, "make_tracked_session", return_value=session) as make_session:
+ list(
+ get_rows(
+ api_key="e2b_secret",
+ endpoint="sandboxes",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ )
+ assert make_session.call_args.kwargs == {
+ "redact_values": ("e2b_secret",),
+ "allow_redirects": False,
+ "capture": False,
+ }
+
+ def test_drops_sensitive_metadata_before_ingesting(self, monkeypatch: Any) -> None:
+ # E2B lets users stash secrets in sandbox metadata; writing it to the table would leak them to
+ # anyone with table read access, so it must be stripped before batching. Other fields survive.
+ pages = [_response([{"sandboxID": "a", "metadata": {"API_KEY": "sk-secret"}, "state": "running"}])]
+ rows, _ = _collect(_FakeResumableManager(), monkeypatch, pages)
+ assert rows == [{"sandboxID": "a", "state": "running"}]
+
+ def test_saves_next_page_cursor_after_yielding_a_batch(self, monkeypatch: Any) -> None:
+ # Save-after-yield with the NEXT page's token is what makes resume re-yield (not skip) the last
+ # batch on a crash. A full 2000-row page forces the batcher to flush mid-loop.
+ manager = _FakeResumableManager()
+ pages = [
+ _response([{"sandboxID": str(i)} for i in range(2000)], next_token="t1"),
+ _response([{"sandboxID": "last"}]),
+ ]
+ rows, _ = _collect(manager, monkeypatch, pages)
+ assert len(rows) == 2001
+ assert manager.saved == [E2BResumeConfig(next_token="t1")]
+
+
+class TestFetchPageRetries:
+ @parameterized.expand(
+ [
+ ("read_timeout", requests.ReadTimeout("Read timed out.")),
+ ("connection_error", requests.ConnectionError("Connection reset by peer")),
+ ("chunked_encoding", requests.exceptions.ChunkedEncodingError("Connection broken")),
+ ]
+ )
+ def test_transient_errors_are_retried(self, _name: str, transient_error: Exception) -> None:
+ good = _response([])
+ session = MagicMock()
+ session.get.side_effect = [transient_error, good]
+
+ with patch.object(e2b._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = e2b._fetch_page(session, "https://api.e2b.app/v2/sandboxes", {}, {}, MagicMock())
+
+ assert result is good
+ assert session.get.call_count == 2
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_retryable_status_codes_retry_then_succeed(self, _name: str, status: int) -> None:
+ bad = MagicMock(status_code=status, ok=False, text="err")
+ good = _response([])
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
+
+ with patch.object(e2b._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = e2b._fetch_page(session, "https://api.e2b.app/v2/sandboxes", {}, {}, MagicMock())
+
+ assert result is good
+ assert session.get.call_count == 2
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_status_code_maps_to_validity(self, _name: str, status: int, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status)
+ with patch.object(e2b, "make_tracked_session", return_value=session) as make_session:
+ assert validate_credentials("e2b_test") is expected
+ # The key rides in the X-API-Key header, which the generic scrubber's denylist doesn't cover, so
+ # the probe must redact it from tracked samples, pin redirects off to stop it replaying elsewhere,
+ # and disable capture so the sandbox response body never reaches sample storage.
+ assert make_session.call_args.kwargs == {
+ "redact_values": ("e2b_test",),
+ "allow_redirects": False,
+ "capture": False,
+ }
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_transient_status_raises_rather_than_reporting_invalid(self, _name: str, status: int) -> None:
+ # A rate limit or 5xx says nothing about the key; mapping it to "invalid" sends the user the wrong way.
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status)
+ with patch.object(e2b, "make_tracked_session", return_value=session):
+ with pytest.raises(e2b.E2BRetryableError):
+ validate_credentials("e2b_test")
+
+ def test_network_error_propagates(self) -> None:
+ # A connection failure is transient — it must bubble up, not be swallowed into a False "invalid key".
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError()
+ with patch.object(e2b, "make_tracked_session", return_value=session):
+ with pytest.raises(requests.ConnectionError):
+ validate_credentials("e2b_test")
+
+
+class TestSourceResponsePartitioning:
+ @parameterized.expand(
+ [
+ ("sandboxes", ["sandboxID"], "startedAt"),
+ ("templates", ["templateID"], "createdAt"),
+ # Snapshots carry no timestamp — a partition key would have to be an unstable field.
+ ("snapshots", ["snapshotID"], None),
+ ]
+ )
+ def test_primary_keys_and_partitioning_per_endpoint(
+ self, endpoint: str, expected_pks: list[str], expected_partition: str | None
+ ) -> None:
+ response = e2b_source(
+ api_key="e2b_test", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+ assert response.primary_keys == expected_pks
+ assert response.sort_mode == "asc"
+ if expected_partition is None:
+ assert response.partition_keys is None
+ assert response.partition_mode is None
+ else:
+ assert response.partition_keys == [expected_partition]
+ assert response.partition_mode == "datetime"
+
+
[email protected]("endpoint", ["sandboxes", "templates", "snapshots"])
+def test_every_endpoint_builds_a_source_response(endpoint: str) -> None:
+ response = e2b_source(
+ api_key="e2b_test", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+ assert response.name == endpoint
+ assert callable(response.items)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/tests/test_e2b_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/tests/test_e2b_source.py
new file mode 100644
index 000000000000..e04d6f846f2b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/tests/test_e2b_source.py
@@ -0,0 +1,115 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.e2b.e2b import E2BResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.e2b.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.e2b.source import E2BSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import E2BSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestE2BSource:
+ def setup_method(self) -> None:
+ self.source = E2BSource()
+ self.team_id = 123
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.E2B
+
+ def test_api_key_field_is_required_password_secret(self) -> None:
+ fields = self.source.get_source_config.fields
+ assert len(fields) == 1
+ field = fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "api_key"
+ assert field.required is True
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+
+ def test_get_schemas_are_all_full_refresh(self) -> None:
+ # No E2B list endpoint has a server-side timestamp filter, so none may advertise incremental
+ # or append — doing so would let the pipeline skip rows it never actually filtered server-side.
+ schemas = self.source.get_schemas(MagicMock(spec=E2BSourceConfig), team_id=self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ for schema in schemas:
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(spec=E2BSourceConfig), team_id=self.team_id, names=["templates"])
+ assert [s.name for s in schemas] == ["templates"]
+
+ @parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid E2B API key"))])
+ def test_validate_credentials_delegates_to_transport(self, _name: str, transport_ok: bool, expected) -> None:
+ config = E2BSourceConfig(api_key="e2b_test")
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.e2b.source.validate_e2b_credentials",
+ return_value=transport_ok,
+ ):
+ assert self.source.validate_credentials(config, self.team_id) == expected
+
+ def test_validate_credentials_transient_error_is_not_reported_as_invalid(self) -> None:
+ # A probe that can't reach E2B must not brand a possibly-valid key "invalid" and send the user
+ # down the credential-reset path — the message has to point at retrying instead.
+ config = E2BSourceConfig(api_key="e2b_test")
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.e2b.source.validate_e2b_credentials",
+ side_effect=Exception("upstream 503"),
+ ):
+ ok, message = self.source.validate_credentials(config, self.team_id)
+ assert ok is False
+ assert message is not None and "invalid" not in message.lower()
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.e2b.app/v2/sandboxes?limit=100"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.e2b.app/snapshots"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='api.e2b.app', port=443): Read timed out."),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.e2b.app/v2/sandboxes"),
+ ]
+ )
+ def test_transient_errors_stay_retryable(self, _name: str, other_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable)
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is E2BResumeConfig
+
+ def test_source_for_pipeline_plumbs_api_key_and_schema(self) -> None:
+ config = E2BSourceConfig(api_key="e2b_secret")
+ inputs = MagicMock()
+ inputs.schema_name = "sandboxes"
+ manager = MagicMock()
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.e2b.source.e2b_source"
+ ) as mock_source:
+ self.source.source_for_pipeline(config, manager, inputs)
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "e2b_secret"
+ assert kwargs["endpoint"] == "sandboxes"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_documented_tables_render_from_static_catalog(self) -> None:
+ # lists_tables_without_credentials=True lets posthog.com render the Supported tables section
+ # with no credentials; the canonical descriptions must feed through.
+ assert self.source.lists_tables_without_credentials is True
+ tables = {t["name"]: t for t in self.source.get_documented_tables()}
+ assert set(tables) == set(ENDPOINTS)
+ assert tables["sandboxes"]["description"]
+ assert tables["sandboxes"]["sync_methods"] == ["Full refresh"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index dfa35f7a54b0..0ca7acbe1223 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1303,7 +1303,7 @@ class DynatraceSourceConfig(config.Config):
@config.config
class E2BSourceConfig(config.Config):
- pass
+ api_key: str
@config.config