:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): add e2b metrics and template build tables (#106643)
Tom Owers0265a1e60ba2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 4f4b78c1db29..6fe1c7aae332 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -2716,19 +2716,28 @@ Note: Diffed against the Environment API section of docs.dynatrace.com/docs/site## E2B — gaps-Today (3): `sandboxes`, `snapshots`, `templates`+Today (7): `sandbox_metrics`, `sandbox_metrics_latest`, `sandboxes`, `snapshots`, `team_metrics`, `template_builds`, `templates`Diffed against: <https://raw.githubusercontent.com/e2b-dev/infra/main/spec/openapi.yml>-- [ ] `GET /sandboxes/metrics and GET /sandboxes/{sandboxID}/metrics` — CPU/memory/disk timeseries per sandbox - the usage metric everyone charts, and the only quantitative data E2B exposes (high)-- [ ] `GET /teams/{teamID}/metrics and /teams/{teamID}/metrics/max` — team-level concurrent-sandbox and start-rate metrics, the headline capacity/quota numbers (high)+- [x] `GET /sandboxes/metrics and GET /sandboxes/{sandboxID}/metrics` — CPU/memory/disk timeseries per sandbox - the usage metric everyone charts, and the only quantitative data E2B exposes (high)+- [x] `GET /teams/{teamID}/metrics` — team-level concurrent-sandbox and start-rate metrics, the headline capacity/quota numbers (high)+- [ ] `GET /teams/{teamID}/metrics/max` — one scalar per metric enum value, not a table; see the reasons below (high)- [ ] `GET /teams` — team lookup resolving the teamID stamped on sandboxes, templates and snapshots (medium)-- [ ] `GET /templates/{templateID} (returns the template's build list) and /templates/{templateID}/builds/{buildID}/status` — template build history - durations, statuses and failure rates for the build pipeline (medium)+- [x] `GET /templates/{templateID}` (returns the template's build list) — template build history - durations, statuses and failure rates for the build pipeline (medium)+- [ ] `GET /templates/{templateID}/builds/{buildID}/status` — per-build status and logs; see the reasons below (medium)- [ ] `GET /templates/{templateID}/tags` — template version/tag lookup, needed to attribute sandboxes to a template version (low)- [ ] `GET /volumes` — persistent volume inventory and their sandbox attachments (low)- [ ] `GET /v2/sandboxes/{sandboxID}/logs` — per-sandbox logs for failure analysis; high volume and per-ID fetch, so nice to have (low)-Note: E2B's public API is genuinely small (~20 GET-able paths, most of them template build plumbing or admin/api-key management). The source is static: E2B_ENDPOINTS in settings.py hardcodes /v2/sandboxes, /v2/templates and /snapshots with no dynamic discovery, and correctly uses the v2 sandbox listing (all states) rather than the running-only v1.+Note: E2B's public API is genuinely small (~20 GET-able paths, most of them template build plumbing or admin/api-key management). The source is static: E2B_ENDPOINTS in settings.py hardcodes each path with no dynamic discovery, and correctly uses the v2 sandbox listing (all states) rather than the running-only v1.++Not covered, with reasons:++- `/teams` is the one endpoint in the spec that does not accept `ApiKeyAuth` — it is `AuthProviderBearerAuth` only, so the team-scoped API key this source stores cannot call it. Its `Team` schema also returns the team's live `apiKey`, which must not land in a warehouse table. The gap's rationale does not hold either: `ListedSandbox`, `Template` and `SnapshotInfo` carry no `teamID` to resolve.+- `/teams/{teamID}/metrics/max` returns a single `{timestamp, value}` object per `metric` enum value, so it is one scalar per call rather than a table, and it is the max of the `team_metrics` series over the same window.+- `/templates/{templateID}/builds/{buildID}/status` is a second fan-out hop costing one request per build. Its only non-log fields (`templateID`, `buildID`, `status`) already arrive in `template_builds`; the rest is build log entries.+- `/teams/{teamID}/metrics` and the sandbox metrics endpoints do take `start`/`end` filters, but the spec documents no ordering guarantee, and a fan-out child's global ascending watermark would advance past sandboxes a partial run has not reached. Both ship full refresh, like the rest of the source.## Easybill — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex a6990b62b73e..062007c15e49 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -255,7 +255,7 @@ the row lists both.| dynamics_365_business_central | HTTP | requests + `rest_source.RESTClient` | ✅ || dynamodb | HTTP | requests | ✅ || dynatrace | HTTP | requests | ✅ |-| e2b | HTTP | requests | ✅ |+| e2b | HTTP | requests + `rest_source.RESTClient` | ✅ || e_conomic | HTTP | requests | ✅ || easybill | HTTP | requests + `rest_source.RESTClient` | ✅ || easypost | 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.pyindex ea658a6a1ec3..66ffd5e59d16 100644--- 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@@ -59,4 +59,62 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"names": "Full names of the snapshot template including team namespace and tag.",},},+ "sandbox_metrics": {+ "description": "CPU, memory and disk samples over time for each running or paused sandbox.",+ "docs_url": "https://e2b.dev/docs",+ "columns": {+ "sandboxID": "Identifier of the sandbox the sample belongs to.",+ "timestamp": "Timestamp of the metric entry (deprecated by E2B in favor of timestampUnix).",+ "timestampUnix": "Timestamp of the metric entry in Unix time (seconds since epoch).",+ "cpuCount": "Number of CPU cores.",+ "cpuUsedPct": "CPU usage percentage.",+ "memUsed": "Memory used in bytes.",+ "memTotal": "Total memory in bytes.",+ "memCache": "Cached memory (page cache) in bytes.",+ "diskUsed": "Disk used in bytes.",+ "diskTotal": "Total disk space in bytes.",+ },+ },+ "sandbox_metrics_latest": {+ "description": "The most recent CPU, memory and disk sample for each sandbox, one row per sandbox.",+ "docs_url": "https://e2b.dev/docs",+ "columns": {+ "sandboxID": "Identifier of the sandbox the sample belongs to.",+ "timestamp": "Timestamp of the metric entry (deprecated by E2B in favor of timestampUnix).",+ "timestampUnix": "Timestamp of the metric entry in Unix time (seconds since epoch).",+ "cpuCount": "Number of CPU cores.",+ "cpuUsedPct": "CPU usage percentage.",+ "memUsed": "Memory used in bytes.",+ "memTotal": "Total memory in bytes.",+ "memCache": "Cached memory (page cache) in bytes.",+ "diskUsed": "Disk used in bytes.",+ "diskTotal": "Total disk space in bytes.",+ },+ },+ "template_builds": {+ "description": "Build history for each sandbox template, one row per build.",+ "docs_url": "https://e2b.dev/docs",+ "columns": {+ "templateID": "Identifier of the template the build belongs to.",+ "buildID": "Identifier of the build.",+ "status": "Status of the build (building, waiting, ready or error).",+ "createdAt": "Time when the build was created.",+ "updatedAt": "Time when the build was last updated.",+ "finishedAt": "Time when the build finished.",+ "cpuCount": "Number of virtual CPUs the build provisions.",+ "memoryMB": "Memory the build provisions, in MiB.",+ "diskSizeMB": "Disk size the build provisions, in MiB.",+ "envdVersion": "Version of the envd daemon baked into the build.",+ },+ },+ "team_metrics": {+ "description": "Concurrent sandboxes and sandbox start rate for the team over time.",+ "docs_url": "https://e2b.dev/docs",+ "columns": {+ "timestamp": "Timestamp of the metric entry (deprecated by E2B in favor of timestampUnix).",+ "timestampUnix": "Timestamp of the metric entry in Unix time (seconds since epoch).",+ "concurrentSandboxes": "The number of concurrent sandboxes for the team.",+ "sandboxStartRate": "Number of sandboxes started per second.",+ },+ },}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.mdindex bc02332f51f4..a171f15eb96c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/e2b.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/e2b.md@@ -23,7 +23,7 @@ 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.+[E2B](https://e2b.dev) runs secure cloud sandboxes for executing AI-agent-generated code. Linking E2B as a source syncs your sandbox infrastructure into the PostHog data warehouse: running and paused sandboxes, templates and their build history, snapshots, and CPU, memory and disk usage per sandbox. You can then join agent sandbox activity with your product analytics.## Prerequisites@@ -35,11 +35,15 @@ Before connecting, you need a team-scoped E2B API key (prefixed `e2b_`). You canProvide 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.+The team ID is optional and only used by the `team_metrics` table, because E2B takes the team in the request path even when the API key already identifies it. You can copy the team ID from the URL of your E2B dashboard. Leave it blank if you do not want team metrics.+## 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.+E2B's list endpoints are point-in-time inventories and do not expose a server-side timestamp filter we can safely page against, so every table syncs as a full refresh. Each run replaces the table with the current state, deduplicated on the table's primary key.++`sandbox_metrics` asks E2B for the usage series of every sandbox, one request per sandbox, so it starts unselected. If you only need current usage, sync `sandbox_metrics_latest` instead. It reads up to 100 sandboxes per request.## Configuration@@ -52,6 +56,7 @@ E2B's list endpoints are point-in-time inventories and do not expose a server-si## 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.+- **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. The same applies to the metrics tables, which are built from that list.+- **Team metrics will not sync**: add your team ID to the source settings. E2B needs it in the request path, and no endpoint an API key can call returns it.<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.pyindex 61ce6ebce3f1..2d9925b382a1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/e2b.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/e2b.py@@ -1,27 +1,52 @@-import dataclasses+import re+import functools+from collections.abc import Callable, Iterable, Iteratorfrom typing import Any, Optionalfrom requests import Request, Response+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,+ RESTClient,+ create_auth,+ create_paginator,rest_api_resource,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.e2b.settings import E2B_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.e2b.settings import (+ E2B_ENDPOINTS,+ E2B_PAGE_LIMIT,+ E2BEndpointConfig,+)# 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+# The next cursor is returned in this response header and echoed back as a query param.NEXT_TOKEN_HEADER = "X-Next-Token"NEXT_TOKEN_PARAM = "nextToken"+# Endpoint name of the batched latest-metrics table, which needs an iterator of its own: it turns a+# page of sandboxes into a single `sandbox_ids=` request rather than one request per sandbox.+SANDBOX_METRICS_LATEST = "sandbox_metrics_latest"+# 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.@@ -37,21 +62,52 @@ NO_ACCESS_ERROR = ("Your E2B API key does not have access to this data. Check the key's team scope in your E2B ""dashboard, then reconnect.")+# E2B takes the team in the path even when the API key already identifies the team, and exposes no+# endpoint an API key can call to look it up, so the user has to supply it.+TEAM_ID_REQUIRED_ERROR = (+ "Add your E2B team ID to this source to sync team metrics. You can copy it from the URL of your E2B dashboard."+)+TEAM_ID_INVALID_ERROR = (+ "Your E2B team ID contains unsupported characters. It should be the team UUID or the project ID "+ "shown in your E2B dashboard."+)+_TEAM_ID_RE = re.compile(r"^[A-Za-z0-9_-]+$")-def _scrub(item: dict[str, Any]) -> dict[str, Any]:- return {key: value for key, value in item.items() if key not in SENSITIVE_FIELDS}+# Called with the paginator state after each page is yielded, or `None` on the last page.+ResumeHook = Callable[[Optional[dict[str, Any]]], None]class E2BRetryableError(Exception):pass+class E2BConfigurationError(Exception):+ pass+++def _scrub(item: dict[str, Any]) -> dict[str, Any]:+ return {key: value for key, value in item.items() if key not in SENSITIVE_FIELDS}+++def _require_team_id(e2b_team_id: str | None) -> str:+ """Return an E2B team ID that is safe to interpolate into a request path."""+ cleaned = (e2b_team_id or "").strip()+ if not cleaned:+ raise E2BConfigurationError(TEAM_ID_REQUIRED_ERROR)+ if not _TEAM_ID_RE.match(cleaned):+ raise E2BConfigurationError(TEAM_ID_INVALID_ERROR)+ return cleaned+++@frozenclass 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+ # A fan-out endpoint checkpoints a different shape — which parents finished, and where the+ # in-progress parent stopped — so it gets its own slot rather than overloading `next_token`.+ fanout: dict[str, Any] | None = Noneclass HeaderCursorPaginator(BasePaginator):@@ -98,16 +154,7 @@ class HeaderCursorPaginator(BasePaginator):self._has_next_page = True-def e2b_source(- api_key: str,- endpoint: str,- team_id: int,- job_id: str,- resumable_source_manager: ResumableSourceManager[E2BResumeConfig],- db_incremental_field_last_value: Optional[Any] = None,-) -> SourceResponse:- config = E2B_ENDPOINTS[endpoint]-+def _client_config(api_key: str) -> ClientConfig:# One tracked session reused across every page so urllib3 keeps the connection alive.# `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 it from replaying to another host;@@ -115,40 +162,134 @@ def e2b_source(# 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)+ return {+ "base_url": E2B_BASE_URL,+ "headers": {"Accept": "application/json"},+ # Auth via the framework so the key is injected per-request and redacted from logs.+ "auth": {"type": "api_key", "api_key": api_key, "name": "X-API-Key", "location": "header"},+ "paginator": HeaderCursorPaginator(),+ "session": session,+ # Same-host-only (base_url host is implicitly allowed) + no redirects: an off-host+ # pagination/resume URL or a 3xx can't replay the API key to another origin.+ "allowed_hosts": [],+ "allow_redirects": False,+ "capture": False,+ }+++def _make_client(client_config: ClientConfig) -> RESTClient:+ return RESTClient(+ base_url=client_config["base_url"],+ headers=client_config.get("headers"),+ auth=create_auth(client_config.get("auth")),+ paginator=create_paginator(client_config.get("paginator")),+ session=client_config.get("session"),+ allowed_hosts=client_config.get("allowed_hosts"),+ allow_redirects=client_config.get("allow_redirects", True),+ capture=client_config.get("capture", True),+ )+++def _fetch_latest_metrics(client: RESTClient, sandbox_ids: list[str]) -> list[dict[str, Any]]:+ """Fetch the latest metric sample for a batch of sandboxes and key each one by its sandbox id.++ The endpoint answers with `{"sandboxes": {"<sandboxID>": {...}}}`, so the id only exists as a+ map key — the rows have to carry it or nothing joins them back to a sandbox.+ """+ rows: list[dict[str, Any]] = []+ for page in client.paginate(+ path=E2B_ENDPOINTS[SANDBOX_METRICS_LATEST].path,+ params={"sandbox_ids": ",".join(sandbox_ids)},+ paginator=SinglePagePaginator(),+ data_selector="sandboxes",+ data_selector_required=True,+ ):+ for by_sandbox in page:+ rows.extend({**metric, "sandboxID": sandbox_id} for sandbox_id, metric in by_sandbox.items())+ return rows+++def _iter_latest_metrics(+ client: RESTClient,+ save_checkpoint: ResumeHook,+ initial_paginator_state: Optional[dict[str, Any]],+) -> Iterator[list[dict[str, Any]]]:+ """Walk the sandbox list and turn each page into one batched metrics request.++ `/sandboxes/metrics` accepts up to 100 sandbox ids per call, the same cap as the sandbox list's+ page size, so a page costs one extra request instead of the one-per-sandbox the declarative+ fan-out would issue. The shared helper can't express that batching, hence the custom iterator.+ """+ for sandboxes in client.paginate(+ path=E2B_ENDPOINTS["sandboxes"].path,+ params={"limit": E2B_PAGE_LIMIT},+ data_selector_required=True,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ ):+ sandbox_ids = [sandbox["sandboxID"] for sandbox in sandboxes if sandbox.get("sandboxID")]+ if sandbox_ids:+ yield _fetch_latest_metrics(client, sandbox_ids)+++def _top_level_resource(+ config: E2BEndpointConfig,+ client_config: ClientConfig,+ path: str,+ team_id: int,+ job_id: str,+ save_checkpoint: ResumeHook,+ initial_paginator_state: Optional[dict[str, Any]],+) -> Resource:+ endpoint: Endpoint = {+ "path": path,+ # Require the documented shape so a wrapped/error body (a response-shape change) fails loud+ # instead of syncing the object as a row.+ "data_selector_required": True,+ }+ if config.data_selector:+ endpoint["data_selector"] = config.data_selector+ if config.page_size_param is None:+ # No page-size param documented means the endpoint answers in one response; the client's+ # cursor paginator would send a `nextToken` it never issued.+ endpoint["paginator"] = SinglePagePaginator()+ else:+ endpoint["params"] = {config.page_size_param: config.page_size}+rest_config: RESTAPIConfig = {- "client": {- "base_url": E2B_BASE_URL,- "headers": {"Accept": "application/json"},- # Auth via the framework so the key is injected per-request and redacted from logs.- "auth": {"type": "api_key", "api_key": api_key, "name": "X-API-Key", "location": "header"},- "paginator": HeaderCursorPaginator(),- "session": session,- # Same-host-only (base_url host is implicitly allowed) + no redirects: an off-host- # pagination/resume URL or a 3xx can't replay the API key to another origin.- "allowed_hosts": [],- "allow_redirects": False,- },+ "client": client_config,"resources": [{- "name": endpoint,- "endpoint": {- "path": config.path,- "params": {"limit": E2B_PAGE_LIMIT},- # E2B list endpoints return a bare JSON array. Require a list so a wrapped/error- # body (a response-shape change) fails loud instead of syncing the object as a row.- "data_selector_required": True,- },+ "name": config.name,+ "endpoint": endpoint,# Drop secret-bearing sandbox metadata before ingesting."data_map": _scrub,}],}+ return rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+- initial_paginator_state: Optional[dict[str, Any]] = None- if resumable_source_manager.can_resume():- resume = resumable_source_manager.load_state()- if resume is not None and resume.next_token is not None:- initial_paginator_state = {"next_token": resume.next_token}+def e2b_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[E2BResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+ e2b_team_id: Optional[str] = None,+) -> SourceResponse:+ config = E2B_ENDPOINTS[endpoint]+ client_config = _client_config(api_key)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Nonedef save_checkpoint(state: Optional[dict[str, Any]]) -> None:# Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields@@ -156,18 +297,54 @@ def e2b_source(if state and state.get("next_token") is not None:resumable_source_manager.save_state(E2BResumeConfig(next_token=state["next_token"]))- resource = rest_api_resource(- rest_config,- team_id,- job_id,- db_incremental_field_last_value,- resume_hook=save_checkpoint,- initial_paginator_state=initial_paginator_state,+ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state:+ resumable_source_manager.save_state(E2BResumeConfig(fanout=state))++ cursor_state: Optional[dict[str, Any]] = (+ {"next_token": resume.next_token} if resume is not None and resume.next_token is not None else None)+ items: Callable[[], Iterable[Any]]+ column_hints: Optional[dict[str, Any]] = None++ if endpoint == SANDBOX_METRICS_LATEST:+ client = _make_client(client_config)+ # Bound, not called: the iterator is a generator, so a stored one would be exhausted on a+ # second pass.+ items = functools.partial(_iter_latest_metrics, client, save_checkpoint, cursor_state)+ elif config.fanout is not None:+ child_endpoint_extra: Endpoint = {"data_selector_required": True}+ if config.data_selector:+ child_endpoint_extra["data_selector"] = config.data_selector+ if config.page_size_param is None:+ child_endpoint_extra["paginator"] = SinglePagePaginator()+ dependent = build_dependent_resource(+ endpoint_configs=E2B_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ child_endpoint_extra=child_endpoint_extra,+ page_size_param=config.page_size_param,+ resume_hook=save_fanout_checkpoint,+ initial_paginator_state=resume.fanout if resume is not None else None,+ )+ items = functools.partial(iter, dependent)+ else:+ path = config.path+ if config.requires_team_id:+ path = path.replace("{team_id}", _require_team_id(e2b_team_id))+ resource = _top_level_resource(config, client_config, path, team_id, job_id, save_checkpoint, cursor_state)+ items = functools.partial(iter, resource)+ column_hints = resource.column_hints+return SourceResponse(name=endpoint,- items=lambda: resource,+ items=items,primary_keys=config.primary_keys,sort_mode="asc",partition_count=1,@@ -175,7 +352,7 @@ def e2b_source(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,- column_hints=resource.column_hints,+ column_hints=column_hints,)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.pyindex bc72f85fb1e7..2604072f4014 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e2b/settings.py@@ -1,10 +1,20 @@-from dataclasses import dataclass, field+from dataclasses import fieldfrom typing import Optional+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.types import IncrementalField+# Cursor pagination: `limit` maxes out at 100 on every paginated E2B list endpoint. It is also the+# cap on how many sandbox ids `/sandboxes/metrics` accepts per call, so one page of sandboxes+# costs exactly one batched metrics request.+E2B_PAGE_LIMIT = 100+-@dataclass+@frozenclass E2BEndpointConfig:name: strpath: str@@ -13,12 +23,47 @@ class E2BEndpointConfig:partition_key: Optional[str] = Noneprimary_keys: list[str] = field(default_factory=lambda: ["id"])should_sync_default: bool = True+ # Key the rows sit under in the response body; `None` for a bare JSON array.+ data_selector: Optional[str] = None+ # `None` for endpoints that document no page-size param — sending one risks a strict validator+ # rejecting the request.+ page_size_param: Optional[str] = "limit"+ page_size: int = E2B_PAGE_LIMIT+ fanout: Optional[DependentEndpointConfig] = None+ # The path carries `{team_id}`, which only the user can supply (see the source's `team_id` field).+ requires_team_id: bool = False+ # Read by the shared fan-out helper's `FanoutEndpointLike` protocol. No E2B endpoint filters+ # server-side by timestamp in a way we can drive a cursor from, so both stay empty.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None+++# Every sandbox-level endpoint hangs off `/sandboxes/{sandboxID}/...`, so the sandbox list is the+# parent they resolve from. `/sandboxes/{sandboxID}/metrics` documents no page-size param, so the+# parent carries its own `limit` instead of the shared one.+SANDBOX_FANOUT = DependentEndpointConfig(+ parent_name="sandboxes",+ resolve_param="sandboxID",+ resolve_field="sandboxID",+ include_from_parent=["sandboxID"],+ parent_field_renames={"sandboxID": "sandboxID"},+ parent_params={"limit": E2B_PAGE_LIMIT},+)++TEMPLATE_FANOUT = DependentEndpointConfig(+ parent_name="templates",+ resolve_param="templateID",+ resolve_field="templateID",+ include_from_parent=["templateID"],+ parent_field_renames={"templateID": "templateID"},+)# 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.+# them expose a server-side timestamp filter we can safely drive a cursor from, 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(@@ -41,6 +86,45 @@ E2B_ENDPOINTS: dict[str, E2BEndpointConfig] = {path="/snapshots",primary_keys=["snapshotID"],),+ # GET /sandboxes/{sandboxID}/metrics — the CPU/memory/disk series for one sandbox. Off by+ # default: it costs one request per sandbox per sync, which `sandbox_metrics_latest` avoids+ # for teams that only want current usage.+ "sandbox_metrics": E2BEndpointConfig(+ name="sandbox_metrics",+ path="/sandboxes/{sandboxID}/metrics",+ partition_key="timestamp",+ primary_keys=["sandboxID", "timestampUnix"],+ page_size_param=None,+ fanout=SANDBOX_FANOUT,+ should_sync_default=False,+ ),+ # GET /sandboxes/metrics — the latest sample for up to 100 sandboxes per call. One row per+ # sandbox, so the only key is the sandbox id; the sample timestamp moves every sync, which+ # rules it out as a partition key.+ "sandbox_metrics_latest": E2BEndpointConfig(+ name="sandbox_metrics_latest",+ path="/sandboxes/metrics",+ primary_keys=["sandboxID"],+ page_size_param=None,+ ),+ # GET /templates/{templateID} — the build history of one template, under a `builds` key.+ "template_builds": E2BEndpointConfig(+ name="template_builds",+ path="/templates/{templateID}",+ partition_key="createdAt",+ primary_keys=["templateID", "buildID"],+ data_selector="builds",+ fanout=TEMPLATE_FANOUT,+ ),+ # GET /teams/{teamID}/metrics — concurrent sandboxes and sandbox start rate over time.+ "team_metrics": E2BEndpointConfig(+ name="team_metrics",+ path="/teams/{team_id}/metrics",+ partition_key="timestamp",+ primary_keys=["timestampUnix"],+ page_size_param=None,+ requires_team_id=True,+ ),}ENDPOINTS = tuple(E2B_ENDPOINTS.keys())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.pyindex 586a52787ff5..f8e75a8e5271 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@@ -18,11 +18,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.e2b.e2b import (INVALID_CREDENTIALS_ERROR,NO_ACCESS_ERROR,+ TEAM_ID_INVALID_ERROR,+ TEAM_ID_REQUIRED_ERROR,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.e2b.settings import (+ E2B_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.e2b import E2BSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -47,7 +53,9 @@ class E2BSource(ResumableSource[E2BSourceConfig, E2BResumeConfig]):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).""",+You can create a team-scoped API key (prefixed `e2b_`) in your [E2B dashboard](https://e2b.dev/dashboard).++The team ID is only needed for the team metrics table. Every other table syncs with the API key alone.""",iconPath="/static/services/e2b.png",docsUrl="https://posthog.com/docs/cdp/sources/e2b",keywords=["sandbox", "ai agents", "code execution", "infrastructure"],@@ -62,6 +70,14 @@ You can create a team-scoped API key (prefixed `e2b_`) in your [E2B dashboard](hplaceholder="e2b_...",secret=True,),+ SourceFieldInputConfig(+ name="team_id",+ label="Team ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="prj_...",+ secret=False,+ ),],),)@@ -79,6 +95,10 @@ You can create a team-scoped API key (prefixed `e2b_`) in your [E2B dashboard](h# `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync."401 Client Error: Unauthorized for url: https://api.e2b.app": INVALID_CREDENTIALS_ERROR,"403 Client Error: Forbidden for url: https://api.e2b.app": NO_ACCESS_ERROR,+ # A missing or malformed team ID can only be fixed in the source settings, so retrying+ # the sync just burns attempts until the job gives up.+ TEAM_ID_REQUIRED_ERROR: TEAM_ID_REQUIRED_ERROR,+ TEAM_ID_INVALID_ERROR: TEAM_ID_INVALID_ERROR,}def get_schemas(@@ -92,12 +112,18 @@ You can create a team-scoped API key (prefixed `e2b_`) in your [E2B dashboard](h) -> 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).+ has_team_id = bool((config.team_id or "").strip())+def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = E2B_ENDPOINTS[endpoint]return SourceSchema(name=endpoint,supports_incremental=False,supports_append=False,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ # A table whose team ID is missing starts unselected rather than failing its first sync.+ should_sync_default=endpoint_config.should_sync_default+ and (has_team_id or not endpoint_config.requires_team_id),)schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]@@ -109,6 +135,9 @@ You can create a team-scoped API key (prefixed `e2b_`) in your [E2B dashboard](hdef validate_credentials(self, config: E2BSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None) -> tuple[bool, str | None]:+ endpoint = E2B_ENDPOINTS.get(schema_name) if schema_name else None+ if endpoint is not None and endpoint.requires_team_id and not (config.team_id or "").strip():+ return False, TEAM_ID_REQUIRED_ERRORtry:return validate_e2b_credentials(config.api_key)except Exception:@@ -134,4 +163,5 @@ You can create a team-scoped API key (prefixed `e2b_`) in your [E2B dashboard](hteam_id=inputs.team_id,job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,+ e2b_team_id=config.team_id,)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.pyindex bfcd52aa01b5..3c9dd7ec0ae7 100644--- 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@@ -9,11 +9,13 @@ from requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClientfrom products.warehouse_sources.backend.temporal.data_imports.sources.e2b.e2b import (+ E2BConfigurationError,E2BResumeConfig,E2BRetryableError,e2b_source,validate_credentials,)+from products.warehouse_sources.backend.temporal.data_imports.sources.e2b.settings import ENDPOINTS# e2b builds its own tracked session and hands it to the RESTClient, so patch it in the e2b module.E2B_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.e2b.e2b.make_tracked_session"@@ -36,28 +38,41 @@ def _make_manager(resume_state: E2BResumeConfig | None = None) -> mock.MagicMockdef _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:- """Wire a mock session and return a list capturing each request's params AT SEND TIME.+ """Wire a mock session and return a list capturing each request's url and params AT SEND TIME.``request.params`` is a single dict mutated in place across pages, so inspecting it after the runshows only the final state — snapshot a copy when each request is prepared instead."""session.headers = {}- param_snapshots: list[dict[str, Any]] = []+ calls: list[dict[str, Any]] = []def _prepare(request: Any) -> mock.MagicMock:- param_snapshots.append(dict(request.params or {}))+ calls.append({"url": request.url, "params": dict(request.params or {})})prepared = mock.MagicMock()- # allowed_hosts pins requests to the base host, so the prepared URL must resolve there.- prepared.url = "https://api.e2b.app/v2/sandboxes"+ # allowed_hosts pins requests to the base host, and RESTClient already joined the path+ # against it, so echoing the request URL keeps the check honest.+ prepared.url = request.urlreturn preparedsession.prepare_request.side_effect = _preparesession.send.side_effect = responses- return param_snapshots---def _source(manager: mock.MagicMock, endpoint: str = "sandboxes", api_key: str = "e2b_test"):- return e2b_source(api_key=api_key, endpoint=endpoint, team_id=1, job_id="j", resumable_source_manager=manager)+ return calls+++def _source(+ manager: mock.MagicMock,+ endpoint: str = "sandboxes",+ api_key: str = "e2b_test",+ e2b_team_id: str | None = None,+):+ return e2b_source(+ api_key=api_key,+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ e2b_team_id=e2b_team_id,+ )def _rows(source_response) -> list[dict[str, Any]]:@@ -69,7 +84,7 @@ class TestPagination:def test_follows_next_token_header_across_pages(self, MockSession) -> None:# The paginator must chase the X-Next-Token header; stopping after page one silently drops data.session = MockSession.return_value- params = _wire(+ calls = _wire(session,[_response([{"sandboxID": "a"}, {"sandboxID": "b"}], next_token="t1"), _response([{"sandboxID": "c"}])],)@@ -78,15 +93,15 @@ class TestPagination:assert rows == [{"sandboxID": "a"}, {"sandboxID": "b"}, {"sandboxID": "c"}]# First page requested with no cursor, second page with the header token; limit ridden every page.- assert params[0].get("nextToken") is None- assert params[0]["limit"] == 100- assert params[1]["nextToken"] == "t1"+ assert calls[0]["params"].get("nextToken") is None+ assert calls[0]["params"]["limit"] == 100+ assert calls[1]["params"]["nextToken"] == "t1"@mock.patch(E2B_SESSION_PATCH)def test_terminates_when_token_repeats(self, MockSession) -> None:# An endpoint that echoes the same cursor instead of dropping it must not loop forever.session = MockSession.return_value- params = _wire(+ calls = _wire(session,[_response([{"sandboxID": "a"}], next_token="same"), _response([{"sandboxID": "b"}], next_token="same")],)@@ -94,20 +109,20 @@ class TestPagination:rows = _rows(_source(_make_manager()))assert rows == [{"sandboxID": "a"}, {"sandboxID": "b"}]- assert params[0].get("nextToken") is None- assert params[1]["nextToken"] == "same"+ assert calls[0]["params"].get("nextToken") is None+ assert calls[1]["params"]["nextToken"] == "same"assert session.send.call_count == 2@mock.patch(E2B_SESSION_PATCH)def test_resumes_from_saved_cursor(self, MockSession) -> None:# A resumed run must start from the persisted cursor, not re-page from the beginning.session = MockSession.return_value- params = _wire(session, [_response([{"sandboxID": "x"}])])+ calls = _wire(session, [_response([{"sandboxID": "x"}])])rows = _rows(_source(_make_manager(E2BResumeConfig(next_token="resume_tok"))))assert rows == [{"sandboxID": "x"}]- assert params[0]["nextToken"] == "resume_tok"+ assert calls[0]["params"]["nextToken"] == "resume_tok"@mock.patch(E2B_SESSION_PATCH)def test_short_first_page_makes_one_request_and_no_checkpoint(self, MockSession) -> None:@@ -246,12 +261,18 @@ class TestSourceResponsePartitioning:("templates", ["templateID"], "createdAt"),# Snapshots carry no timestamp — a partition key would have to be an unstable field.("snapshots", ["snapshotID"], None),+ # A fan-out child aggregates rows from every parent, so the parent id has to be in the key.+ ("sandbox_metrics", ["sandboxID", "timestampUnix"], "timestamp"),+ ("template_builds", ["templateID", "buildID"], "createdAt"),+ # One row per sandbox, and its sample timestamp moves every sync, so it can't partition.+ ("sandbox_metrics_latest", ["sandboxID"], None),+ ("team_metrics", ["timestampUnix"], "timestamp"),])def test_primary_keys_and_partitioning_per_endpoint(self, endpoint: str, expected_pks: list[str], expected_partition: str | None) -> None:- response = _source(_make_manager(), endpoint=endpoint)+ response = _source(_make_manager(), endpoint=endpoint, e2b_team_id="prj_1")assert response.primary_keys == expected_pksassert response.sort_mode == "asc"if expected_partition is None:@@ -263,8 +284,187 @@ class TestSourceResponsePartitioning:assert response.partition_format == "week"[email protected]("endpoint", ["sandboxes", "templates", "snapshots"])[email protected]("endpoint", list(ENDPOINTS))def test_every_endpoint_builds_a_source_response(endpoint: str) -> None:- response = _source(_make_manager(), endpoint=endpoint)+ response = _source(_make_manager(), endpoint=endpoint, e2b_team_id="prj_1")assert response.name == endpointassert callable(response.items)+++class TestFanout:+ @mock.patch(E2B_SESSION_PATCH)+ def test_sandbox_metrics_fans_out_per_sandbox_and_stamps_the_sandbox_id(self, MockSession) -> None:+ # A SandboxMetric row carries no sandbox id, so without the parent injection every row in the+ # table would be unattributable — and the primary key would collide across sandboxes.+ session = MockSession.return_value+ calls = _wire(+ session,+ [+ _response([{"sandboxID": "s1"}, {"sandboxID": "s2"}]),+ _response([{"timestampUnix": 10, "cpuUsedPct": 1.5}]),+ _response([{"timestampUnix": 11, "cpuUsedPct": 2.5}]),+ ],+ )++ rows = _rows(_source(_make_manager(), endpoint="sandbox_metrics"))++ assert rows == [+ {"timestampUnix": 10, "cpuUsedPct": 1.5, "sandboxID": "s1"},+ {"timestampUnix": 11, "cpuUsedPct": 2.5, "sandboxID": "s2"},+ ]+ assert [call["url"] for call in calls] == [+ "https://api.e2b.app/v2/sandboxes",+ "https://api.e2b.app/sandboxes/s1/metrics",+ "https://api.e2b.app/sandboxes/s2/metrics",+ ]+ # The parent keeps its documented page size; the child documents no limit param, so sending+ # one risks a strict validator rejecting the request.+ assert calls[0]["params"]["limit"] == 100+ assert "limit" not in calls[1]["params"]++ @mock.patch(E2B_SESSION_PATCH)+ def test_template_builds_reads_the_builds_key_and_stamps_the_template_id(self, MockSession) -> None:+ # /templates/{templateID} answers with the template object, not a build array, so a missing+ # data_selector would sync one row holding the whole object.+ session = MockSession.return_value+ calls = _wire(+ session,+ [+ _response([{"templateID": "t1"}]),+ _response({"templateID": "t1", "builds": [{"buildID": "b1", "status": "ready"}]}),+ ],+ )++ rows = _rows(_source(_make_manager(), endpoint="template_builds"))++ assert rows == [{"buildID": "b1", "status": "ready", "templateID": "t1"}]+ assert calls[1]["url"] == "https://api.e2b.app/templates/t1"++ @mock.patch(E2B_SESSION_PATCH)+ def test_fanout_checkpoints_under_its_own_slot_and_resumes_from_it(self, MockSession) -> None:+ # Fan-out resume state is a completed-parents map, not a page cursor, so it must not be+ # written into next_token — replaying that against the API would be meaningless.+ session = MockSession.return_value+ _wire(+ session,+ [+ _response([{"templateID": "t1"}, {"templateID": "t2"}]),+ _response({"builds": [{"buildID": "b1"}]}),+ _response({"builds": [{"buildID": "b2"}]}),+ ],+ )++ manager = _make_manager()+ _rows(_source(manager, endpoint="template_builds"))++ saved = manager.save_state.call_args.args[0]+ assert saved.next_token is None+ assert saved.fanout is not None and sorted(saved.fanout["completed"]) == [+ "/templates/t1",+ "/templates/t2",+ ]++ @mock.patch(E2B_SESSION_PATCH)+ def test_fanout_resume_skips_parents_already_completed(self, MockSession) -> None:+ session = MockSession.return_value+ calls = _wire(+ session,+ [+ _response([{"templateID": "t1"}, {"templateID": "t2"}]),+ _response({"builds": [{"buildID": "b2"}]}),+ ],+ )++ resume = E2BResumeConfig(fanout={"completed": ["/templates/t1"], "current": None, "child_state": None})+ rows = _rows(_source(_make_manager(resume), endpoint="template_builds"))++ assert rows == [{"buildID": "b2", "templateID": "t2"}]+ assert [call["url"] for call in calls] == [+ "https://api.e2b.app/v2/templates",+ "https://api.e2b.app/templates/t2",+ ]+++class TestLatestSandboxMetrics:+ @mock.patch(E2B_SESSION_PATCH)+ def test_batches_a_page_of_sandboxes_into_one_request_and_keys_rows_by_sandbox(self, MockSession) -> None:+ # The endpoint takes up to 100 ids per call and answers with a sandboxID -> metric map, so the+ # id only exists as a map key. One request per page is the whole point of this table.+ session = MockSession.return_value+ calls = _wire(+ session,+ [+ _response([{"sandboxID": "s1"}, {"sandboxID": "s2"}]),+ _response({"sandboxes": {"s1": {"cpuUsedPct": 1.0}, "s2": {"cpuUsedPct": 2.0}}}),+ ],+ )++ rows = _rows(_source(_make_manager(), endpoint="sandbox_metrics_latest"))++ assert rows == [+ {"cpuUsedPct": 1.0, "sandboxID": "s1"},+ {"cpuUsedPct": 2.0, "sandboxID": "s2"},+ ]+ assert calls[1]["url"] == "https://api.e2b.app/sandboxes/metrics"+ assert calls[1]["params"]["sandbox_ids"] == "s1,s2"++ @mock.patch(E2B_SESSION_PATCH)+ def test_walks_the_whole_sandbox_list_starting_from_a_resumed_cursor(self, MockSession) -> None:+ # The iterator drives the sandbox list itself, so it has to seed a resumed run from the saved+ # cursor and keep chasing the header token; stopping after one page leaves most sandboxes+ # with no metrics at all.+ session = MockSession.return_value+ calls = _wire(+ session,+ [+ _response([{"sandboxID": "s9"}], next_token="t2"),+ _response({"sandboxes": {"s9": {"cpuUsedPct": 9.0}}}),+ _response([{"sandboxID": "s10"}]),+ _response({"sandboxes": {"s10": {"cpuUsedPct": 10.0}}}),+ ],+ )++ rows = _rows(_source(_make_manager(E2BResumeConfig(next_token="tok")), endpoint="sandbox_metrics_latest"))++ assert rows == [{"cpuUsedPct": 9.0, "sandboxID": "s9"}, {"cpuUsedPct": 10.0, "sandboxID": "s10"}]+ assert calls[0]["params"]["nextToken"] == "tok"+ assert calls[2]["params"]["nextToken"] == "t2"++ @mock.patch(E2B_SESSION_PATCH)+ def test_a_page_with_no_sandboxes_makes_no_metrics_request(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([])])++ assert _rows(_source(_make_manager(), endpoint="sandbox_metrics_latest")) == []+ assert session.send.call_count == 1++ @mock.patch(E2B_SESSION_PATCH)+ def test_missing_sandboxes_key_fails_loudly(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([{"sandboxID": "s1"}]), _response({"error": "nope"})])++ with pytest.raises(ValueError, match="data_selector"):+ _rows(_source(_make_manager(), endpoint="sandbox_metrics_latest"))+++class TestTeamMetrics:+ @mock.patch(E2B_SESSION_PATCH)+ def test_puts_the_team_id_in_the_path_and_sends_no_page_size(self, MockSession) -> None:+ # E2B takes the team in the path even though the API key already identifies it, and the+ # endpoint documents no pagination — a stray limit/nextToken would be an undocumented param.+ session = MockSession.return_value+ calls = _wire(session, [_response([{"timestampUnix": 5, "concurrentSandboxes": 3}])])++ rows = _rows(_source(_make_manager(), endpoint="team_metrics", e2b_team_id=" prj_abc "))++ assert rows == [{"timestampUnix": 5, "concurrentSandboxes": 3}]+ assert calls[0]["url"] == "https://api.e2b.app/teams/prj_abc/metrics"+ assert calls[0]["params"] == {}+ assert session.send.call_count == 1++ @parameterized.expand([("missing", None), ("blank", " "), ("path_traversal", "../admin/teams")])+ def test_an_unusable_team_id_fails_before_any_request(self, _name: str, team_id: str | None) -> None:+ # The value lands in a request path, so anything but an opaque identifier must be refused+ # rather than interpolated.+ with pytest.raises(E2BConfigurationError):+ _source(_make_manager(), endpoint="team_metrics", e2b_team_id=team_id)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.pyindex cfd226ca28a6..178b63a1cdd6 100644--- 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@@ -1,3 +1,4 @@+import pytestfrom unittest.mock import MagicMock, patchfrom parameterized import parameterized@@ -5,6 +6,8 @@ from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.sources.e2b.e2b import (INVALID_CREDENTIALS_ERROR,NO_ACCESS_ERROR,+ E2BConfigurationError,+ _require_team_id,)from products.warehouse_sources.backend.temporal.data_imports.sources.e2b.settings import ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.e2b.source import E2BSource@@ -26,10 +29,39 @@ class TestE2BSource:assert schema.supports_append is Falseassert schema.incremental_fields == []+ @parameterized.expand(+ [+ # A table whose team ID is missing would fail its first sync, so it starts unselected.+ ("team_metrics_without_team_id", None, "team_metrics", False),+ ("team_metrics_with_team_id", "prj_1", "team_metrics", True),+ # One request per sandbox per sync is a cost to opt into, not a default.+ ("sandbox_metrics", "prj_1", "sandbox_metrics", False),+ ("sandboxes", None, "sandboxes", True),+ ]+ )+ def test_should_sync_default_per_endpoint(+ self, _name: str, team_id: str | None, endpoint: str, expected: bool+ ) -> None:+ config = E2BSourceConfig(api_key="e2b_test", team_id=team_id)+ schemas = {s.name: s for s in self.source.get_schemas(config, team_id=self.team_id)}+ assert schemas[endpoint].should_sync_default is expected+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"]+ def test_a_table_needing_the_team_id_says_so_instead_of_probing(self) -> None:+ # The per-schema check is the only place a user learns the team ID is missing before the+ # sync fails, and a credential probe cannot tell them anything about it.+ config = E2BSourceConfig(api_key="e2b_test")+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.e2b.source.validate_e2b_credentials"+ ) as probe:+ ok, message = self.source.validate_credentials(config, self.team_id, "team_metrics")+ assert ok is False+ assert message is not None and "team ID" in message+ probe.assert_not_called()+@parameterized.expand([("valid", (True, None)),@@ -80,6 +112,14 @@ class TestE2BSource:non_retryable = self.source.get_non_retryable_errors()assert any(key in observed_error for key in non_retryable)+ @parameterized.expand([("missing", None), ("malformed", "../admin")])+ def test_a_bad_team_id_stops_the_sync_instead_of_retrying(self, _name: str, team_id: str | None) -> None:+ # Only a settings change can fix it, so the message the transport raises has to be one the+ # source classifies as non-retryable — otherwise the job burns every attempt.+ with pytest.raises(E2BConfigurationError) as exc:+ _require_team_id(team_id)+ assert str(exc.value) in self.source.get_non_retryable_errors()+@parameterized.expand([("read_timeout", "HTTPSConnectionPool(host='api.e2b.app', port=443): Read timed out."),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/e2b.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/e2b.pyindex 2d104d64cfe0..f0d3ab500c4a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/e2b.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/e2b.py@@ -7,3 +7,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass E2BSourceConfig(config.Config):api_key: str+ team_id: str | None = None