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): add 7 missing tables to the Env0 source (#118478)

Tom Owers7c9f76172ca7
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.md
index 6b74e40240e7..81d23e8984e0 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
@@ -4258,10 +4258,10 @@ Diffed against: <https://docs.envzero.com/llms.txt>
- [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)
-- [ ] `audit-events/fetch-audit-logs` — state and transition history across the organization (medium)
+- [x] `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)
+- [x] `deployment-logs/find-all-steps-by-deployment-id` — per-step timing and status within a deployment, needed for duration and failure-stage analysis (medium)
+- [x] `cost/get-a-projects-budget and cost/get-projects-budget-summary-of-the-current-period` — budget targets to compare actual spend against (medium)
+- [x] `audit-events/fetch-audit-logs` — state and transition history across the organization (medium)
- [ ] `modules/list-modules and modules/list-module-versions` — module registry inventory that templates and environments reference (medium)
- [ ] `cloud-compass/find-cloud-resources and cloud-compass/get-resource-events` — cloud resource inventory and change events across linked cloud accounts (medium)
- [ ] `cost/get-weekly-costs-for-projects-or-environments` — pre-bucketed weekly cost series for trend reporting (low)
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.py
index 1a575e459198..0175717d8a9f 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
@@ -174,4 +174,102 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"mode": "Whether the resource is managed by the deployment or read as a data source.",
},
},
+ "deployment_steps": {
+ "description": "A step within a deployment (such as init, plan, or apply), with its status and timing.",
+ "docs_url": "https://docs.envzero.com/api-reference/deployment-logs/find-all-steps-by-deployment-id",
+ "columns": {
+ "deployment_id": "Identifier of the deployment the step belongs to.",
+ "deployment_started_at": "Timestamp when that deployment started running.",
+ "id": "Identifier of the step.",
+ "deploymentLogId": "Identifier of the deployment the step belongs to, as returned by env0.",
+ "name": "Name of the step.",
+ "displayName": "Display name of the step.",
+ "order": "Position of the step within the deployment.",
+ "environmentId": "Identifier of the environment that was deployed.",
+ "projectId": "Identifier of the project the environment belongs to.",
+ "organizationId": "Identifier of the organization the environment belongs to.",
+ "status": "Step status (NOT_STARTED, IN_PROGRESS, WAITING_FOR_USER, TIMEOUT, FAIL, SUCCESS, CANCELLED, SKIPPED, or WARNING).",
+ "startedAt": "Timestamp when the step started.",
+ "completedAt": "Timestamp when the step completed.",
+ "retryCount": "Number of times the step was retried.",
+ },
+ },
+ "roles": {
+ "description": "A role that grants a set of permissions in an organization, either built in or custom.",
+ "docs_url": "https://docs.envzero.com/api-reference/roles/get-all-roles",
+ "columns": {
+ "organization_id": "Identifier of the organization the role belongs to.",
+ "id": "Identifier of the role.",
+ "name": "Name of the role.",
+ "permissions": "Permissions the role grants.",
+ "isDefaultRole": "Whether the role is the organization's default role.",
+ },
+ },
+ "team_role_assignments": {
+ "description": "The role a team holds on a project.",
+ "docs_url": "https://docs.envzero.com/api-reference/roles/get-team-role-assignments",
+ "columns": {
+ "project_id": "Identifier of the project the assignment applies to.",
+ "id": "Identifier of the assignment.",
+ "teamId": "Identifier of the team.",
+ "role": "Role assigned to the team: a built-in role name or a custom role id.",
+ "inherited": "Whether the team inherits the assignment from a parent scope.",
+ "organizationId": "Identifier of the organization.",
+ "projectId": "Identifier of the project the assignment is defined on.",
+ "environmentId": "Identifier of the environment the assignment is defined on, if any.",
+ },
+ },
+ "user_role_assignments": {
+ "description": "The role a user holds on an environment.",
+ "docs_url": "https://docs.envzero.com/api-reference/roles/get-user-role-assignments",
+ "columns": {
+ "environment_id": "Identifier of the environment the assignment applies to.",
+ "id": "Identifier of the assignment.",
+ "userId": "Identifier of the user. Joins to organization_users.user_id.",
+ "role": "Role assigned to the user: a built-in role name or a custom role id.",
+ "organizationId": "Identifier of the organization.",
+ "projectId": "Identifier of the project the environment belongs to.",
+ "environmentId": "Identifier of the environment, as returned by env0.",
+ },
+ },
+ "project_budgets": {
+ "description": "The cost budget set on a project, with the thresholds that trigger alerts.",
+ "docs_url": "https://docs.envzero.com/api-reference/cost/get-a-projects-budget",
+ "columns": {
+ "id": "Identifier of the budget.",
+ "projectId": "Identifier of the project the budget applies to.",
+ "amount": "Budget amount for each timeframe.",
+ "timeframe": "Budget period (WEEKLY, MONTHLY, QUARTERLY, or YEARLY).",
+ "thresholds": "Percentages of the budget that trigger alerts.",
+ },
+ },
+ "project_budget_summaries": {
+ "description": "A project's spend against its budget in the current budget period.",
+ "docs_url": "https://docs.envzero.com/api-reference/cost/get-projects-budget-summary-of-the-current-period",
+ "columns": {
+ "projectId": "Identifier of the project.",
+ "usage": "Cost spent so far in the current budget period.",
+ "amount": "Budget amount for the period.",
+ "renewedAt": "Timestamp when the current budget period started.",
+ },
+ },
+ "audit_logs": {
+ "description": "An audit log event that records an action on an environment, deployment, project, or template.",
+ "docs_url": "https://docs.envzero.com/api-reference/audit-events/fetch-audit-logs",
+ "columns": {
+ "id": "Identifier of the audit event.",
+ "organizationId": "Identifier of the organization.",
+ "actorId": "Identifier of the user or API key that did the action.",
+ "actionName": "Name of the action.",
+ "projectId": "Identifier of the project the action applies to.",
+ "timestamp": "Timestamp when the action occurred.",
+ "ipAddress": "IP address the action came from.",
+ "payload": "Details of the action.",
+ "source": "Where the action came from (ui, cli, api, system, or not-recorded).",
+ "onBehalfOf": "Identifier of the user the action was done for, if any.",
+ "attributedTo": "Identifier of the user or API key the action is attributed to.",
+ "entityType": "Type of entity the action applies to (environment, deployment, project, or template).",
+ "entityId": "Identifier of the entity the action applies to.",
+ },
+ },
}
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.py
index 921aba130bce..ea7570e323ab 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
@@ -48,7 +48,7 @@ class Env0ResumeConfig:
def _format_date_window_value(value: Any) -> Optional[str]:
"""Format an incremental cursor as YYYY-MM-DDTHH:mm:ss.sssZ, the format env0's
- fromDate/toDate params require."""
+ date window params require."""
if isinstance(value, datetime):
dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
elif isinstance(value, date):
@@ -63,7 +63,7 @@ def _build_date_window_params(
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
) -> dict[str, str]:
- """Build the fromDate/toDate server-side window for incremental syncs.
+ """Build the server-side date window for incremental syncs.
env0 requires both params together, so the window runs from the watermark (minus the
endpoint's lookback, letting rows that mutated after first fetch be re-pulled and merged)
@@ -86,7 +86,8 @@ def _build_date_window_params(
if from_date is None:
return {}
- return {"fromDate": from_date, "toDate": _format_date_window_value(datetime.now(UTC)) or ""}
+ from_param, to_param = config.date_window_params
+ return {from_param: from_date, to_param: _format_date_window_value(datetime.now(UTC)) or ""}
def _paginator_for(config: Env0EndpointConfig) -> BasePaginator:
@@ -103,10 +104,10 @@ def _paginator_for(config: Env0EndpointConfig) -> BasePaginator:
def _row_transform(
config: Env0EndpointConfig, parent_resource_name: Optional[str]
-) -> 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."""
+) -> Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]:
+ """Per-item reshape: drop empty placeholder objects, 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)
flatten = config.flatten_field
injected = (
@@ -121,7 +122,9 @@ def _row_transform(
# 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]:
+ def _transform(row: dict[str, Any]) -> dict[str, Any] | list[dict[str, Any]]:
+ if config.required_field and row.get(config.required_field) is None:
+ return []
out = {key: value for key, value in row.items() if key not in strip}
nested = out.pop(flatten, None) if flatten else None
if isinstance(nested, dict):
@@ -232,7 +235,7 @@ def _target_resource(
def _build_resources(config: Env0EndpointConfig, date_window_params: dict[str, str]) -> list[EndpointResource | str]:
if config.scope == "organization":
- return [_organizations_parent(), _target_resource(config, "organizations", {})]
+ return [_organizations_parent(), _target_resource(config, "organizations", date_window_params)]
if config.scope == "project":
return [_organizations_parent(), _projects_parent(), _target_resource(config, "projects", {})]
if config.scope == "environment":
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.md
index 9309843a9b0c..a25fba0fa708 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,7 +14,7 @@ import AlphaRelease from "../\_snippets/alpha-release.mdx"
<AlphaRelease />
-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.
+The env0 connector syncs your infrastructure-as-code data into PostHog: organizations, projects, teams, templates, organization members, roles and role assignments, environments, deployment history, the steps and resources behind each deployment, drift causes, audit logs, project budgets, and cloud cost at the environment, project, and organization level. You can attribute cloud spend to teams and projects, compare it against budgets, and analyze deployment and drift activity alongside your product data.
## Prerequisites
@@ -40,6 +40,10 @@ The `deployments` table supports incremental sync on `startedAt`. Deployments ca
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 `deployment_steps` table works the same way, with incremental sync on `deployment_started_at`.
+
+The `audit_logs` table supports incremental sync on `timestamp`.
+
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
@@ -52,9 +56,11 @@ The cost tables always sync the last year of daily cost records, so full refresh
## Troubleshooting
-**Missing cost data:** the cost tables only have rows for environments and projects where env0 cost monitoring is configured. Those 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. The budget tables only have rows for projects with a budget.
+
+**Rate limits:** env0 limits API usage to 1,000 requests per 60 seconds. Deployments and costs are fetched per environment, and `deployment_resources` and `deployment_steps` are 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, 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.
+**Audit logs:** reading audit logs needs the `VIEW_AUDIT_LOGS` permission in env0.
**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.
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.py
index e8db095342ea..34275520735f 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
@@ -38,8 +38,10 @@ class Env0EndpointConfig:
# Terraform output) and secret-bearing fields (deployment variable values, injected
# OIDC/VCS tokens) that must not be persisted to the warehouse.
strip_fields: tuple[str, ...] = ()
- # Endpoint supports env0's server-side fromDate/toDate window (must be passed together).
+ # Endpoint supports env0's server-side date window (both bounds must be passed together).
supports_date_window: bool = False
+ # Query params that carry the window's lower and upper bound.
+ date_window_params: tuple[str, str] = ("fromDate", "toDate")
# 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.
@@ -47,6 +49,9 @@ class Env0EndpointConfig:
# 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
+ # Rows without this field are dropped, for single-object endpoints that answer with an empty
+ # object when the resource is not configured (a project with no budget).
+ required_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
@@ -183,6 +188,92 @@ ENV0_ENDPOINTS: dict[str, Env0EndpointConfig] = {
},
],
),
+ "deployment_steps": Env0EndpointConfig(
+ name="deployment_steps",
+ path="/deployments/{parent_id}/steps",
+ scope="deployment",
+ # A step's id is optional in the API schema; its position and name within the deployment
+ # are always present.
+ primary_keys=["deployment_id", "order", "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,
+ },
+ ],
+ ),
+ "roles": Env0EndpointConfig(
+ name="roles",
+ path="/roles",
+ scope="organization",
+ org_id_param="organizationId",
+ # Built-in roles can come back without an id; role names are unique within an organization.
+ primary_keys=["organization_id", "name"],
+ inject_parent_fields={"id": "organization_id"},
+ ),
+ "team_role_assignments": Env0EndpointConfig(
+ name="team_role_assignments",
+ path="/roles/assignments/teams?projectId={parent_id}",
+ scope="project",
+ # A team can hold a direct and an inherited assignment on the same project.
+ primary_keys=["project_id", "teamId", "id"],
+ inject_parent_fields={"id": "project_id"},
+ ),
+ "user_role_assignments": Env0EndpointConfig(
+ name="user_role_assignments",
+ # env0 only exposes user role assignments at environment scope.
+ path="/roles/assignments/users?environmentId={parent_id}",
+ scope="environment",
+ primary_keys=["environment_id", "userId"],
+ inject_parent_fields={"id": "environment_id"},
+ # The nested user carries identity provider access and refresh tokens. userId joins to
+ # organization_users instead.
+ strip_fields=("user",),
+ ),
+ "project_budgets": Env0EndpointConfig(
+ name="project_budgets",
+ path="/costs/project/{parent_id}/budget",
+ scope="project",
+ primary_keys=["projectId"],
+ required_field="projectId",
+ ),
+ "project_budget_summaries": Env0EndpointConfig(
+ name="project_budget_summaries",
+ # The endpoint takes a comma-separated list, but the fan-out resolves one project at a time.
+ path="/costs/budget/summary?projectIds={parent_id}",
+ scope="project",
+ primary_keys=["projectId"],
+ ),
+ "audit_logs": Env0EndpointConfig(
+ name="audit_logs",
+ path="/audit/events",
+ scope="organization",
+ org_id_param="organizationId",
+ # Returns {"events": [...], "nextPageKey": ...}; the next request sends nextPageKey back as
+ # `offset`. 1000 is the documented page size maximum.
+ paginated=True,
+ data_key="events",
+ params={"limit": "1000"},
+ partition_key="timestamp",
+ # actor and attributedToUser embed the full user, identity provider tokens included.
+ # actorId and attributedTo keep the ids.
+ strip_fields=("actor", "attributedToUser"),
+ supports_date_window=True,
+ date_window_params=("from", "to"),
+ incremental_fields=[
+ {
+ "label": "timestamp",
+ "type": IncrementalFieldType.DateTime,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
}
ENDPOINTS = tuple(ENV0_ENDPOINTS.keys())
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.py
index 20598f98c412..71c4d21bce54 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
@@ -202,40 +202,179 @@ class TestFanOutShaping:
]
assert result.requests[1].param("includeApiKeys") == "true"
- def test_deployment_resources_window_the_parent_walk_not_the_child(self) -> None:
+ @pytest.mark.parametrize(
+ "endpoint, child_row, expected_row, child_path",
+ [
+ (
+ "deployment_resources",
+ {"provider": "aws", "type": "aws_s3_bucket", "name": "logs", "mode": "managed"},
+ # moduleName is absent for root-module resources but is part of the key, and a NULL
+ # key part never matches on merge.
+ {"provider": "aws", "type": "aws_s3_bucket", "name": "logs", "mode": "managed", "moduleName": ""},
+ "/environments/deployments/dep-1/resources",
+ ),
+ (
+ "deployment_steps",
+ {"name": "terraform-plan", "order": 3, "status": "SUCCESS", "deploymentLogId": "dep-1"},
+ {"name": "terraform-plan", "order": 3, "status": "SUCCESS", "deploymentLogId": "dep-1"},
+ "/deployments/dep-1/steps",
+ ),
+ ],
+ )
+ def test_deployment_children_window_the_parent_walk_not_the_child(
+ self, endpoint: str, child_row: dict, expected_row: dict, child_path: str
+ ) -> None:
result = _driver().run(
- "deployment_resources",
+ endpoint,
[
ScriptedResponse(json=[{"id": "org-1"}]),
ScriptedResponse(json=[{"id": "env-1"}]),
ScriptedResponse(json=[{"id": "dep-1", "startedAt": "2026-06-02T10:00:00.000Z"}]),
- ScriptedResponse(
- json=[{"provider": "aws", "type": "aws_s3_bucket", "name": "logs", "mode": "managed"}]
- ),
+ ScriptedResponse(json=[child_row]),
],
should_use_incremental_field=True,
db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),
)
assert result.raised is None
- # moduleName is absent for root-module resources but is part of the key, and a NULL key part
- # never matches on merge.
assert result.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",
- }
+ {**expected_row, "deployment_id": "dep-1", "deployment_started_at": "2026-06-02T10:00:00.000Z"}
]
deployment_request = next(request for request in result.requests if request.path.endswith("/deployments"))
assert deployment_request.param("fromDate") == "2026-05-31T00:00:00.000Z"
- # The resources endpoint takes no time filter; only the parent walk is bounded.
- resource_request = next(request for request in result.requests if request.path.endswith("/resources"))
- assert resource_request.query == {}
+ # The child endpoint takes no time filter; only the parent walk is bounded.
+ child_request = result.requests[-1]
+ assert child_request.path == child_path
+ assert child_request.query == {}
+
+ @pytest.mark.parametrize(
+ "endpoint, parent_rows, child_responses, expected_child_paths, expected_rows",
+ [
+ (
+ "user_role_assignments",
+ [{"id": "env-1"}],
+ [
+ ScriptedResponse(
+ json=[
+ {
+ "userId": "u-1",
+ "role": "Viewer",
+ "user": {"user_id": "u-1", "identities": [{"access_token": "fake-token"}]},
+ }
+ ]
+ )
+ ],
+ ["/roles/assignments/users"],
+ [{"userId": "u-1", "role": "Viewer", "environment_id": "env-1"}],
+ ),
+ (
+ "team_role_assignments",
+ [{"id": "proj-1"}],
+ [ScriptedResponse(json=[{"teamId": "team-1", "role": "Admin", "inherited": True}])],
+ ["/roles/assignments/teams"],
+ # A missing optional id is part of the key, and a NULL key part never matches on merge.
+ [{"teamId": "team-1", "role": "Admin", "inherited": True, "id": "", "project_id": "proj-1"}],
+ ),
+ (
+ "project_budgets",
+ [{"id": "proj-1"}, {"id": "proj-2"}],
+ [
+ # A project with no budget answers with an empty object, which is not a row.
+ ScriptedResponse(json={}),
+ ScriptedResponse(
+ json={"projectId": "proj-2", "amount": 500, "timeframe": "MONTHLY", "thresholds": [80]}
+ ),
+ ],
+ ["/costs/project/proj-1/budget", "/costs/project/proj-2/budget"],
+ [{"projectId": "proj-2", "amount": 500, "timeframe": "MONTHLY", "thresholds": [80]}],
+ ),
+ ],
+ )
+ def test_role_and_budget_fan_out_shaping(
+ self,
+ endpoint: str,
+ parent_rows: list[dict],
+ child_responses: list[ScriptedResponse],
+ expected_child_paths: list[str],
+ expected_rows: list[dict],
+ ) -> None:
+ result = _driver().run(
+ endpoint,
+ [ScriptedResponse(json=[{"id": "org-1"}]), ScriptedResponse(json=parent_rows), *child_responses],
+ )
+
+ assert result.raised is None
+ assert result.paths[-len(expected_child_paths) :] == expected_child_paths
+ assert result.rows == expected_rows
+
+ def test_project_budget_summaries_request_one_project_at_a_time(self) -> None:
+ result = _driver().run(
+ "project_budget_summaries",
+ [
+ ScriptedResponse(json=[{"id": "org-1"}]),
+ ScriptedResponse(json=[{"id": "proj-1"}, {"id": "proj-2"}]),
+ ScriptedResponse(json=[{"projectId": "proj-1", "usage": 12.5, "amount": 100}]),
+ ScriptedResponse(json=[{"projectId": "proj-2", "usage": 0, "amount": 50}]),
+ ],
+ )
+
+ assert result.raised is None
+ assert [request.param("projectIds") for request in result.requests[-2:]] == ["proj-1", "proj-2"]
+ assert [row["projectId"] for row in result.rows] == ["proj-1", "proj-2"]
+
+ def test_audit_logs_window_strip_users_and_follow_the_cursor(self) -> None:
+ result = _driver().run(
+ "audit_logs",
+ [
+ ScriptedResponse(json=[{"id": "org-1"}]),
+ ScriptedResponse(
+ json={
+ "events": [
+ {
+ "id": "evt-1",
+ "actionName": "deploy",
+ "actorId": "u-1",
+ "timestamp": "2026-06-02T10:00:00.000Z",
+ "actor": {"user_id": "u-1", "identities": [{"refresh_token": "fake-token"}]},
+ "attributedToUser": {"user_id": "u-1"},
+ }
+ ],
+ "nextPageKey": "evt-1",
+ }
+ ),
+ ScriptedResponse(
+ json={
+ "events": [
+ {
+ "id": "evt-2",
+ "actionName": "destroy",
+ "actorId": "u-2",
+ "timestamp": "2026-06-03T10:00:00.000Z",
+ }
+ ],
+ "nextPageKey": "",
+ }
+ ),
+ ],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),
+ )
+
+ assert result.raised is None
+ assert result.rows == [
+ {"id": "evt-1", "actionName": "deploy", "actorId": "u-1", "timestamp": "2026-06-02T10:00:00.000Z"},
+ {"id": "evt-2", "actionName": "destroy", "actorId": "u-2", "timestamp": "2026-06-03T10:00:00.000Z"},
+ ]
+ first_page, second_page = result.requests[1:]
+ assert first_page.path == "/audit/events"
+ assert first_page.param("organizationId") == "org-1"
+ # Audit events take from/to, not the fromDate/toDate names the deployments endpoint uses.
+ assert first_page.param("from") == "2026-06-01T00:00:00.000Z"
+ assert first_page.param("to") is not None
+ assert first_page.param("fromDate") is None
+ assert first_page.param("offset") is None
+ assert second_page.param("offset") == "evt-1"
+ assert second_page.param("from") == "2026-06-01T00:00:00.000Z"
class TestEnv0SourceResponse: