: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(data-warehouse): add missing env0 endpoint tables (#107285)
Tom Owers23ef71449238
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 5f924fa030ba..9d98aff87efb 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@@ -2857,14 +2857,15 @@ Note: The docs URL serves the raw OpenAPI 3.1 JSON directly. The v2 API GET surf## Env0 — gaps-Today (7): `deployments`, `environment_costs`, `environments`, `organizations`, `projects`, `teams`, `templates`+Today (12): `deployment_resources`, `deployments`, `drift_causes`, `environment_costs`, `environments`, `organization_costs`, `organization_users`, `organizations`, `projects`, `project_costs`, `teams`, `templates`Diffed against: <https://docs.envzero.com/llms.txt>-- [ ] `cost/get-costs-for-a-project and cost/get-costs-for-an-organization` — project- and org-level cost rollups; only per-environment cost is synced today (high)-- [ ] `environments/list-deployment-resources` — the resources a deployment created or changed — the analytical detail behind each deployment row (high)-- [ ] `environments/get-a-drifted-resources-events (and find-deployment-drift-status)` — drift detection events, one of env0's headline signals and absent from the current tables (high)-- [ ] `organization/list-users` — lookup resolving the user ids stamped on deployments, environments and role assignments (high)+- [x] `cost/get-costs-for-a-project and cost/get-costs-for-an-organization` — project- and org-level cost rollups; only per-environment cost is synced today (high)+- [x] `environments/list-deployment-resources` — the resources a deployment created or changed — the analytical detail behind each deployment row (high)+- [x] `drift/get-drift-causes` — drift causes detected across an organization, with the environments each one affects (high)+- [ ] `environments/get-a-drifted-resources-events (and find-deployment-drift-status)` — drift detection events, one of env0's headline signals and absent from the current tables (high). Not syncable: `get-a-drifted-resources-events` is keyed on a cloud `resourceId`/`resourceType` pair that no listing endpoint enumerates, and `find-deployment-drift-status` is a per-deployment point lookup returning a copy of a deployment log the `deployments` table already carries (including `driftDetected` and `driftCause`). `drift/get-drift-causes` covers the drift signal instead.+- [x] `organization/list-users` — lookup resolving the user ids stamped on deployments, environments and role assignments (high)- [ ] `roles/get-user-role-assignments and roles/get-team-role-assignments (+ roles/get-all-roles)` — membership and permission mapping between users, teams and projects (medium)- [ ] `deployment-logs/find-all-steps-by-deployment-id` — per-step timing and status within a deployment, needed for duration and failure-stage analysis (medium)- [ ] `cost/get-a-projects-budget and cost/get-projects-budget-summary-of-the-current-period` — budget targets to compare actual spend against (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/canonical_descriptions.pyindex 48f8790e2403..1a575e459198 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/canonical_descriptions.py@@ -110,4 +110,68 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"isStale": "Whether the cost record is stale and pending refresh.",},},+ "project_costs": {+ "description": "Daily cloud cost records for a project over the last year, rolling up the costs of the environments it contains. Requires cost monitoring to be configured.",+ "docs_url": "https://docs.envzero.com/api-reference/cost/get-costs-for-a-project",+ "columns": {+ "project_id": "Identifier of the project the cost record belongs to.",+ "date": "Date of the cost record.",+ "total": "Cost for the period, broken down by cloud provider (AWS, GCP, AZURE).",+ "id": "Identifier of the cost record.",+ "isStale": "Whether the cost record is stale and pending refresh.",+ },+ },+ "organization_costs": {+ "description": "Daily cloud cost data points for an organization over the last year, one per date and project. Requires cost monitoring to be configured.",+ "docs_url": "https://docs.envzero.com/api-reference/cost/get-costs-for-an-organization",+ "columns": {+ "organization_id": "Identifier of the organization the cost record belongs to.",+ "date": "Date of the cost record.",+ "providersCost": "Cost for the period, broken down by cloud provider (AWS, GCP, AZURE).",+ "groupKey": "Identifier of the project the cost data point is grouped under.",+ },+ },+ "organization_users": {+ "description": "A user or API key with access to an organization, with the role it holds. Resolves the user ids stamped on deployments, environments, and role assignments.",+ "docs_url": "https://docs.envzero.com/api-reference/organization/list-users",+ "columns": {+ "organization_id": "Identifier of the organization the membership belongs to.",+ "user_id": "Unique identifier of the user, as referenced by deployments and environments.",+ "email": "Email address of the user.",+ "name": "Display name of the user.",+ "given_name": "First name of the user.",+ "family_name": "Last name of the user.",+ "picture": "URL of the user's avatar.",+ "last_login": "Timestamp of the user's most recent login.",+ "app_metadata": "Account metadata, including whether this entry is an API key rather than a person.",+ "role": "The user's role in the organization.",+ "status": "Whether the user is Active or still Invited.",+ },+ },+ "drift_causes": {+ "description": "A drift cause detected across an organization: a change that made deployed infrastructure differ from the code, grouped across every environment it affects.",+ "docs_url": "https://docs.envzero.com/api-reference/drift/get-drift-causes",+ "columns": {+ "organization_id": "Identifier of the organization the drift cause was detected in.",+ "causeId": "Unique identifier of the drift cause.",+ "causeKind": "Kind of drift (unmanagedChange, unappliedCommit, providerVersionChange, moduleVersionChange, variableChange, or stateChange).",+ "causeKeyParts": "The fields that identify this cause, which differ per causeKind.",+ "firstSeenAt": "Timestamp when the drift cause was first detected.",+ "lastSeenAt": "Timestamp when the drift cause was last detected.",+ "environments": "Environments affected by the drift cause, with the drift detection deployment that found it.",+ },+ },+ "deployment_resources": {+ "description": "A resource that a deployment created or changed, giving one row per resource behind each deployment.",+ "docs_url": "https://docs.envzero.com/api-reference/environments/list-deployment-resources",+ "columns": {+ "deployment_id": "Identifier of the deployment that managed the resource.",+ "deployment_started_at": "Timestamp when that deployment started running.",+ "provider": "IaC provider that owns the resource (e.g. aws, google, azurerm).",+ "type": "Resource type (e.g. aws_s3_bucket).",+ "name": "Resource name within its module.",+ "moduleName": "Module containing the resource. Empty for resources in the root module.",+ "mode": "Whether the resource is managed by the deployment or read as a data source.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/env0.py b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/env0.pyindex 8bbe13427a4f..921aba130bce 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/env0.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/env0.py@@ -90,9 +90,10 @@ def _build_date_window_params(def _paginator_for(config: Env0EndpointConfig) -> BasePaginator:- if config.data_key:+ if config.data_key and config.paginated:# Teams returns {"teams": [...], "nextPageKey": ...}; the next request sends the returned- # nextPageKey back as the `offset` query param.+ # nextPageKey back as the `offset` query param. Other wrapped endpoints (organization+ # costs, drift causes) return the whole collection in one object.return JSONResponseCursorPaginator(cursor_path="nextPageKey", cursor_param="offset")if config.paginated:# env0 has no top-level total; termination is a short/empty page (OffsetPaginator default).@@ -102,26 +103,42 @@ def _paginator_for(config: Env0EndpointConfig) -> BasePaginator:def _row_transform(config: Env0EndpointConfig, parent_resource_name: Optional[str]-) -> Optional[Callable[[dict[str, Any]], dict[str, Any]]]:- """Per-item reshape matching the old `_normalize_row`: drop huge free-text blobs and- secret-bearing fields, and rename the injected parent id to its documented column."""+) -> Callable[[dict[str, Any]], dict[str, Any]]:+ """Per-item reshape: drop huge free-text blobs and secret-bearing fields, lift a nested object+ into the row root, rename injected parent fields to their documented columns, and fill blank+ primary key parts."""strip = set(config.strip_fields)- rename_to = config.inject_parent_id_field- injected_key = f"_{parent_resource_name}_id" if (rename_to and parent_resource_name) else None- if not strip and injected_key is None:- return None+ flatten = config.flatten_field+ injected = (+ {+ f"_{parent_resource_name}_{parent_field}": column+ for parent_field, column in config.inject_parent_fields.items()+ }+ if parent_resource_name+ else {}+ )+ # A NULL primary key part never matches on merge, so the row would be inserted again on every+ # sync instead of updated. Injected columns always carry a parent value, so they are excluded.+ nullable_key_fields = [key for key in config.primary_keys if key not in injected.values()]def _transform(row: dict[str, Any]) -> dict[str, Any]:out = {key: value for key, value in row.items() if key not in strip}- if injected_key is not None and rename_to is not None and injected_key in out:- out[rename_to] = out.pop(injected_key)+ nested = out.pop(flatten, None) if flatten else None+ if isinstance(nested, dict):+ out = {**nested, **out}+ for injected_key, column in injected.items():+ if injected_key in out:+ out[column] = out.pop(injected_key)+ for key in nullable_key_fields:+ if out.get(key) is None:+ out[key] = ""return outreturn _transformdef _organizations_parent() -> EndpointResource:- """Organizations list used only to resolve org ids for the organization/environment fan-out."""+ """Organizations list used only to resolve org ids. Every fan-out chain starts here."""return {"name": "organizations","endpoint": {"path": ENV0_ENDPOINTS["organizations"].path, "paginator": SinglePagePaginator()},@@ -146,6 +163,40 @@ def _environments_parent() -> EndpointResource:}+def _projects_parent() -> EndpointResource:+ """Projects list (one request chain per organization) used only to resolve project ids for the+ project-level fan-out."""+ projects_config = ENV0_ENDPOINTS["projects"]+ return {+ "name": "projects",+ "endpoint": {+ "path": f"{projects_config.path}?{projects_config.org_id_param}={{org_id}}",+ "params": {"org_id": {"type": "resolve", "resource": "organizations", "field": "id"}},+ "paginator": SinglePagePaginator(),+ },+ }+++def _deployments_parent(date_window_params: dict[str, str]) -> EndpointResource:+ """Deployments list (one request chain per environment) used only to resolve deployment ids for+ the deployment-level fan-out. The incremental window lands here rather than on the child, so a+ run only visits deployments that started inside it. Otherwise every sync would re-walk every+ deployment the account has ever made."""+ deployments_config = ENV0_ENDPOINTS["deployments"]+ return {+ "name": "deployments",+ "endpoint": {+ "path": deployments_config.path,+ "params": {+ "parent_id": {"type": "resolve", "resource": "environments", "field": "id"},+ **date_window_params,+ },+ "paginator": OffsetPaginator(limit=PAGE_SIZE, total_path=None),+ "response_actions": [{"status_code": 404, "action": "ignore"}],+ },+ }++def _target_resource(config: Env0EndpointConfig, parent_resource_name: Optional[str], extra_params: dict[str, str]) -> EndpointResource:@@ -156,42 +207,47 @@ def _target_resource(# lands in the query string (the resolve mechanism only substitutes into the path).path = f"{config.path}?{config.org_id_param}={{org_id}}"params["org_id"] = {"type": "resolve", "resource": "organizations", "field": "id"}- elif parent_resource_name == "organizations":- # Teams embeds the org id directly in its path (/teams/organizations/{parent_id}).+ elif parent_resource_name is not None:+ # The parent id is embedded directly in the path (/teams/organizations/{parent_id},+ # /costs/projects/{parent_id}, /environments/deployments/{parent_id}/resources).path = config.path- params["parent_id"] = {"type": "resolve", "resource": "organizations", "field": "id"}- elif parent_resource_name == "environments":- path = config.path- params["parent_id"] = {"type": "resolve", "resource": "environments", "field": "id"}+ params["parent_id"] = {"type": "resolve", "resource": parent_resource_name, "field": "id"}else:path = config.pathendpoint: Endpoint = {"path": path, "params": params, "paginator": _paginator_for(config)}if config.data_key:endpoint["data_selector"] = config.data_key- if config.scope == "environment":- # A 404 during the per-environment fan-out means the environment was deleted mid-sync or- # (for costs) cost monitoring isn't configured — skip it rather than failing the sync.+ if config.scope in ("project", "environment", "deployment"):+ # A 404 deep in the fan-out means the parent was deleted mid-sync or (for costs) cost+ # monitoring isn't configured, so skip it rather than failing the sync.endpoint["response_actions"] = [{"status_code": 404, "action": "ignore"}]resource: EndpointResource = {"name": config.name, "endpoint": endpoint}- if config.inject_parent_id_field and parent_resource_name:- resource["include_from_parent"] = ["id"]- transform = _row_transform(config, parent_resource_name)- if transform is not None:- resource["data_map"] = transform+ if config.inject_parent_fields and parent_resource_name:+ resource["include_from_parent"] = list(config.inject_parent_fields)+ resource["data_map"] = _row_transform(config, parent_resource_name)return resourcedef _build_resources(config: Env0EndpointConfig, date_window_params: dict[str, str]) -> list[EndpointResource | str]:if config.scope == "organization":return [_organizations_parent(), _target_resource(config, "organizations", {})]+ if config.scope == "project":+ return [_organizations_parent(), _projects_parent(), _target_resource(config, "projects", {})]if config.scope == "environment":return [_organizations_parent(),_environments_parent(),_target_resource(config, "environments", date_window_params),]+ if config.scope == "deployment":+ return [+ _organizations_parent(),+ _environments_parent(),+ _deployments_parent(date_window_params),+ _target_resource(config, "deployments", {}),+ ]return [_target_resource(config, None, {})]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/posthog_com_doc.md b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/posthog_com_doc.mdindex 272decadbd96..9309843a9b0c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/posthog_com_doc.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/posthog_com_doc.md@@ -14,13 +14,13 @@ import AlphaRelease from "../\_snippets/alpha-release.mdx"<AlphaRelease />-The env0 connector syncs your infrastructure-as-code data — organizations, projects, environments, deployment history, teams, templates, and per-environment cloud cost — into PostHog, so you can attribute cloud spend to teams and projects and analyze deployment activity alongside your product data.+The env0 connector syncs your infrastructure-as-code data into PostHog: organizations, projects, teams, templates, organization members, environments, deployment history, the resources behind each deployment, drift causes, and cloud cost at the environment, project, and organization level. You can attribute cloud spend to teams and projects and analyze deployment and drift activity alongside your product data.## PrerequisitesYou need an env0 API key. Organization administrators can create an organization API key, or you can use a personal API key scoped to your user. The key needs read access to the organizations you want to sync.-Environment cost data additionally requires [cost monitoring](https://docs.envzero.com/docs/cost-monitoring) to be configured in env0 for the environments you want cost records for.+Cost data additionally requires [cost monitoring](https://docs.envzero.com/docs/cost-monitoring) to be configured in env0 for the environments you want cost records for. Project and organization cost roll up the environments below them, so they are empty until cost monitoring is on.## Adding a data source@@ -38,7 +38,9 @@ To connect env0, you need an API key ID and an API key secret:The `deployments` table supports incremental sync on `startedAt`. Deployments can change after they first sync (their status and finish time land when the run completes), so incremental syncs re-pull a one-day window behind the last synced deployment to keep recently-synced rows fresh.-The `environment_costs` table always syncs the last year of daily cost records per environment, so full refresh is the right mode for it.+The `deployment_resources` table supports incremental sync on `deployment_started_at`, the start time of the deployment that managed the resource. An incremental sync only visits deployments inside that window, which keeps the table cheap to refresh. A full refresh visits every deployment in every environment, so use incremental sync once the first load finishes.++The cost tables always sync the last year of daily cost records, so full refresh is the right mode for them. The same goes for `drift_causes` and `organization_users`, which env0 returns in full on every request.## Configuration@@ -50,8 +52,10 @@ The `environment_costs` table always syncs the last year of daily cost records p## Troubleshooting-**Missing cost data:** the `environment_costs` table only has rows for environments where env0 cost monitoring is configured. Environments without it are skipped.+**Missing cost data:** the cost tables only have rows for environments and projects where env0 cost monitoring is configured. Those without it are skipped.++**Rate limits:** env0 limits API usage to 1,000 requests per 60 seconds. Deployments and costs are fetched per environment, and `deployment_resources` is fetched per deployment, so accounts with very many environments or deployments may sync these tables slowly. The connector backs off and retries automatically.-**Rate limits:** env0 limits API usage to 1,000 requests per 60 seconds. Deployments and costs are fetched per environment, so accounts with very many environments may sync these tables slowly — the connector backs off and retries automatically.+**API keys in `organization_users`:** env0 counts organization API keys as users, so they appear in this table alongside people. The `app_metadata` column marks them. They are included because a deployment can be started by an API key, so leaving them out would make the table an incomplete lookup.<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/settings.pyindex a2ddc89e7c4a..e8db095342ea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/settings.py@@ -1,20 +1,23 @@-from dataclasses import dataclass, field+from dataclasses import fieldfrom datetime import timedeltafrom typing import Literal, Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType-Env0EndpointScope = Literal["root", "organization", "environment"]+Env0EndpointScope = Literal["root", "organization", "project", "environment", "deployment"]-@dataclass+@frozenclass Env0EndpointConfig:name: str- # Path template; `{parent_id}` is replaced with the fan-out parent's id (organization or- # environment, per `scope`).+ # Path template; `{parent_id}` is replaced with the fan-out parent's id (organization,+ # project, environment or deployment, per `scope`).path: str- # "root" endpoints are called once; "organization"/"environment" endpoints fan out one- # request chain per parent resource.+ # "root" endpoints are called once; every other scope fans out one request chain per+ # parent resource of that kind, walking organizations -> projects / environments ->+ # deployments to enumerate the parents.scope: Env0EndpointScope = "root"# env0's core list endpoints are mostly unpaginated JSON arrays; only environments,# deployments, and teams document limit/offset pagination.@@ -37,13 +40,18 @@ class Env0EndpointConfig:strip_fields: tuple[str, ...] = ()# Endpoint supports env0's server-side fromDate/toDate window (must be passed together).supports_date_window: bool = False- # When set, each row gets the fan-out parent's id injected under this column so the- # primary key stays unique table-wide.- inject_parent_id_field: Optional[str] = None+ # Fan-out parent fields copied onto each row, mapped to the column they land in. The+ # parent id keeps the primary key unique table-wide; a parent timestamp gives a child with+ # no time field of its own an incremental cursor.+ inject_parent_fields: dict[str, str] = field(default_factory=dict)+ # Nested object lifted into the row root, for endpoints that bury the row's identity one+ # level down (organization users wrap everything but role and status under "user").+ flatten_field: Optional[str] = None# Safety overlap subtracted from the incremental watermark on every run, re-pulling a# window that merge dedupes on the primary key. Deployments mutate after creation# (status/finishedAt land when the run completes), so re-pulling the last day refreshes- # rows first fetched mid-run.+ # rows first fetched mid-run. On a "deployment"-scoped endpoint the window bounds the+ # deployments parent walk rather than the child request.incremental_lookback: Optional[timedelta] = None@@ -114,7 +122,66 @@ ENV0_ENDPOINTS: dict[str, Env0EndpointConfig] = {# range, so the widest window with daily grain is the best full-refresh shape.params={"timespan": "YEAR", "granularity": "DAILY"},primary_keys=["environment_id", "date"],- inject_parent_id_field="environment_id",+ inject_parent_fields={"id": "environment_id"},+ ),+ "project_costs": Env0EndpointConfig(+ name="project_costs",+ path="/costs/projects/{parent_id}",+ scope="project",+ params={"timespan": "YEAR", "granularity": "DAILY"},+ primary_keys=["project_id", "date"],+ inject_parent_fields={"id": "project_id"},+ ),+ "organization_costs": Env0EndpointConfig(+ name="organization_costs",+ path="/costs",+ scope="organization",+ org_id_param="organizationId",+ params={"timespan": "YEAR", "granularity": "DAILY"},+ # Returns {"costDataPoints": [...], "errors": [...], "staleProjectIds": [...]}; only the+ # data points are rows. One point per date and groupKey (the project the cost rolls up to).+ data_key="costDataPoints",+ primary_keys=["organization_id", "date", "groupKey"],+ inject_parent_fields={"id": "organization_id"},+ ),+ "organization_users": Env0EndpointConfig(+ name="organization_users",+ path="/organizations/{parent_id}/users",+ scope="organization",+ # API keys act as deployment initiators too, so including them makes this a complete+ # lookup for the user ids stamped on deployments and environments.+ params={"includeApiKeys": "true"},+ flatten_field="user",+ primary_keys=["organization_id", "user_id"],+ inject_parent_fields={"id": "organization_id"},+ ),+ "drift_causes": Env0EndpointConfig(+ name="drift_causes",+ path="/drift-causes",+ scope="organization",+ org_id_param="organizationId",+ data_key="causes",+ primary_keys=["organization_id", "causeId"],+ inject_parent_fields={"id": "organization_id"},+ ),+ "deployment_resources": Env0EndpointConfig(+ name="deployment_resources",+ path="/environments/deployments/{parent_id}/resources",+ scope="deployment",+ # Resources carry no id or timestamp of their own; the row is addressed by the Terraform+ # address parts within its deployment, and dated by the deployment that produced it.+ primary_keys=["deployment_id", "mode", "moduleName", "type", "name"],+ inject_parent_fields={"id": "deployment_id", "startedAt": "deployment_started_at"},+ supports_date_window=True,+ incremental_lookback=timedelta(hours=24),+ incremental_fields=[+ {+ "label": "deployment_started_at",+ "type": IncrementalFieldType.DateTime,+ "field": "deployment_started_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],),}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0.py b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0.pyindex d0bedafc3a09..fa3acc3c7a8d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0.py@@ -247,23 +247,46 @@ class TestGetRows:# Multi-level fan-out disables resume (one shared hook can't checkpoint two levels).manager.save_state.assert_not_called()+ @pytest.mark.parametrize(+ "endpoint, parents_route, parents, uncovered_path, covered_path, parent_column",+ [+ (+ "environment_costs",+ "organizationId=org-1",+ [{"id": "env-1"}, {"id": "env-2"}],+ "/costs/environments/env-1",+ "/costs/environments/env-2",+ "environment_id",+ ),+ (+ "project_costs",+ "/projects?organizationId=org-1",+ [{"id": "proj-1"}, {"id": "proj-2"}],+ "/costs/projects/proj-1",+ "/costs/projects/proj-2",+ "project_id",+ ),+ ],+ )@mock.patch(SESSION_PATCH)- def test_costs_inject_environment_id_and_skip_404s(self, mock_session):+ def test_costs_inject_the_parent_id_and_skip_404s(+ self, mock_session, endpoint, parents_route, parents, uncovered_path, covered_path, parent_column+ ):session = mock_session.return_value_wire(session,[("env0.com/organizations", _response([{"id": "org-1"}])),- ("organizationId=org-1", _response([{"id": "env-1"}, {"id": "env-2"}])),- # env-1 has no cost monitoring configured.- ("/costs/environments/env-1", _response({"message": "not found"}, status_code=404)),- ("/costs/environments/env-2", _response([{"date": "2026-06-01", "total": 12.5}])),+ (parents_route, _response(parents)),+ # The first parent has no cost monitoring configured.+ (uncovered_path, _response({"message": "not found"}, status_code=404)),+ (covered_path, _response([{"date": "2026-06-01", "total": 12.5}])),],)- rows = _rows(_source("environment_costs", _make_manager()))+ rows = _rows(_source(endpoint, _make_manager()))- assert rows == [{"date": "2026-06-01", "total": 12.5, "environment_id": "env-2"}]+ assert rows == [{"date": "2026-06-01", "total": 12.5, parent_column: parents[1]["id"]}]@mock.patch(SESSION_PATCH)def test_non_404_error_fails_the_sync(self, mock_session):@@ -352,6 +375,129 @@ class TestGetRows:assert _query(urls[1])["organizationId"] == ["org-1"]+class TestFanOutShaping:+ @pytest.mark.parametrize(+ "endpoint, route, payload, expected",+ [+ (+ "organization_costs",+ "/costs?organizationId=org-1",+ {+ "costDataPoints": [{"date": "2026-06-01", "providersCost": {"AWS": 5}, "groupKey": "p-1"}],+ "errors": [],+ "staleProjectIds": [],+ },+ {"date": "2026-06-01", "providersCost": {"AWS": 5}, "groupKey": "p-1", "organization_id": "org-1"},+ ),+ (+ "drift_causes",+ "/drift-causes",+ {"causes": [{"causeId": "cause-1", "causeKind": "unmanagedChange"}]},+ {"causeId": "cause-1", "causeKind": "unmanagedChange", "organization_id": "org-1"},+ ),+ ],+ )+ @mock.patch(SESSION_PATCH)+ def test_wrapped_org_endpoints_select_their_rows(self, mock_session, endpoint, route, payload, expected):+ session = mock_session.return_value+ _wire(+ session,+ [+ ("env0.com/organizations", _response([{"id": "org-1"}])),+ (route, _response(payload)),+ ],+ )++ rows = _rows(_source(endpoint, _make_manager()))++ # The rows sit under one key of the response object; its siblings (errors, staleProjectIds)+ # are not rows, and the organization id appears nowhere in the payload.+ assert rows == [expected]++ @mock.patch(SESSION_PATCH)+ def test_organization_users_lifts_the_nested_user_onto_the_row(self, mock_session):+ session = mock_session.return_value+ urls = _wire(+ session,+ [+ ("env0.com/organizations", _response([{"id": "org-1"}])),+ (+ "/organizations/org-1/users",+ _response(+ [+ {+ "user": {"user_id": "u-1", "email": "[email protected]"},+ "role": "Admin",+ "status": "Active",+ }+ ]+ ),+ ),+ ],+ )++ rows = _rows(_source("organization_users", _make_manager()))++ # user_id is the row's identity and sits one level down, so a nested column would leave the+ # primary key unresolvable.+ assert rows == [+ {+ "user_id": "u-1",+ "email": "[email protected]",+ "role": "Admin",+ "status": "Active",+ "organization_id": "org-1",+ }+ ]+ assert _query(urls[1])["includeApiKeys"] == ["true"]++ @mock.patch(SESSION_PATCH)+ def test_deployment_resources_window_the_parent_walk_not_the_child(self, mock_session):+ session = mock_session.return_value+ urls = _wire(+ session,+ [+ ("env0.com/organizations", _response([{"id": "org-1"}])),+ ("/environments?organizationId=org-1", _response([{"id": "env-1"}])),+ (+ "/environments/env-1/deployments",+ _response([{"id": "dep-1", "startedAt": "2026-06-02T10:00:00.000Z"}]),+ ),+ (+ "/environments/deployments/dep-1/resources",+ _response([{"provider": "aws", "type": "aws_s3_bucket", "name": "logs", "mode": "managed"}]),+ ),+ ],+ )++ rows = _rows(+ _source(+ "deployment_resources",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),+ )+ )++ # moduleName is absent for root-module resources but is part of the key, and a NULL key part+ # never matches on merge.+ assert rows == [+ {+ "provider": "aws",+ "type": "aws_s3_bucket",+ "name": "logs",+ "mode": "managed",+ "moduleName": "",+ "deployment_id": "dep-1",+ "deployment_started_at": "2026-06-02T10:00:00.000Z",+ }+ ]+ deployments_query = _query(next(url for url in urls if url.endswith("/deployments") or "/deployments?" in url))+ assert deployments_query["fromDate"] == ["2026-05-31T00:00:00.000Z"]+ # The resources endpoint takes no time filter; only the parent walk is bounded.+ assert _query(next(url for url in urls if "/resources" in url)) == {}++class TestEnv0SourceResponse:@pytest.mark.parametrize("endpoint", list(ENDPOINTS))@mock.patch(SESSION_PATCH)@@ -372,10 +518,11 @@ class TestEnv0SourceResponse:assert response.partition_mode is Noneassert response.partition_keys is None- def test_fan_out_child_primary_keys_include_parent_id(self):- # Cost rows have no globally-unique id of their own; without the environment id in the- # key, rows from different environments on the same date would merge into one.- assert ENV0_ENDPOINTS["environment_costs"].primary_keys == ["environment_id", "date"]+ @pytest.mark.parametrize("config", [c for c in ENV0_ENDPOINTS.values() if c.inject_parent_fields])+ def test_fan_out_child_primary_keys_include_parent_id(self, config):+ # Fan-out rows carry no globally-unique id of their own; without the parent id in the key,+ # rows from different parents collapse into one and every later merge multi-matches them.+ assert config.inject_parent_fields["id"] in config.primary_keys@pytest.mark.parametrize("config", list(ENV0_ENDPOINTS.values()))def test_partition_keys_are_stable_creation_fields(self, config):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0_source.pyindex 3cc6e89e1197..27a948893eb9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/env0/tests/test_env0_source.py@@ -39,13 +39,15 @@ class TestEnv0Source:assert {schema.name for schema in schemas} == set(ENDPOINTS)incremental = {schema.name for schema in schemas if schema.supports_incremental}- # Only deployments expose env0's server-side fromDate/toDate window.- assert incremental == {"deployments"}+ # Only the deployments walk accepts env0's server-side fromDate/toDate window, either for+ # the deployments table itself or to bound the parent walk behind deployment resources.+ assert incremental == {"deployments", "deployment_resources"}def test_incremental_schemas_advertise_their_fields(self):schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}assert schemas["deployments"].incremental_fields == INCREMENTAL_FIELDS["deployments"]+ assert schemas["deployment_resources"].incremental_fields == INCREMENTAL_FIELDS["deployment_resources"]assert schemas["environments"].incremental_fields == []assert schemas["environments"].supports_append is False