: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 4 missing tables to the PulumiCloud source (#125480)
Tom Owers544481ad65e8
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 34ae7da36879..9050de6a6d57 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@@ -9838,10 +9838,10 @@ Today (5): `audit_logs`, `deployments`, `resources`, `stack_updates`, `stacks`Diffed against: <https://www.pulumi.com/docs/reference/cloud-rest-api/>-- [ ] `GET /api/orgs/{orgName}/policyresults/violationsv2 (also /policyresults/issues)` — policy violations per resource/stack - the compliance dataset users report on (high)-- [ ] `GET /api/orgs/{orgName}/resources/summary` — resources under management, the org's headline usage/billing metric (high)-- [ ] `GET /api/orgs/{orgName}/members` — org membership lookup that resolves the user logins appearing on stack updates and audit logs (high)-- [ ] `GET /api/stacks/{orgName}/{projectName}/{stackName}/tags` — stack tags (environment, owner, cost centre) - the lookup that makes stack and update data groupable (high)+- [x] `GET /api/orgs/{orgName}/policyresults/violationsv2 (also /policyresults/issues)` — policy violations per resource/stack - the compliance dataset users report on (high)+- [x] `GET /api/orgs/{orgName}/resources/summary` — resources under management, the org's headline usage/billing metric (high)+- [x] `GET /api/orgs/{orgName}/members` — org membership lookup that resolves the user logins appearing on stack updates and audit logs (high)+- [x] `GET /api/stacks/{orgName}/{projectName}/{stackName}/tags` — stack tags (environment, owner, cost centre) - the lookup that makes stack and update data groupable (high)- [ ] `GET /api/orgs/{orgName}/teams (and /teams/{teamName})` — team lookup for ownership and access reporting on stacks (medium)- [ ] `GET /api/orgs/{orgName}/policyresults/policies` — policy definitions lookup that names the policies referenced by violations (medium)- [ ] `GET /api/orgs/{orgName}/policyresults/compliance` — aggregated compliance posture over time (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/canonical_descriptions.pyindex 56cb04826f26..80330742fb1b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/canonical_descriptions.py@@ -102,4 +102,72 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"managed": "Whether this resource is managed by Pulumi IaC stacks or discovered by Insights scanning.",},},+ "policy_issues": {+ "description": "Policy issues that Policy Packs detected during stack updates or continuous compliance scans, both open and closed.",+ "docs_url": "https://www.pulumi.com/docs/reference/cloud-rest-api/policy-results/",+ "columns": {+ "id": "The unique identifier of the policy issue.",+ "entityType": "The type of entity this issue applies to: stack or insights-account.",+ "entityProject": "The project name (for stack entities) or parent Insights account name (for resource entities).",+ "entityId": "The identifier of the entity this issue applies to.",+ "kind": "The kind of policy issue (audit or preventative).",+ "level": "The enforcement level of the policy (e.g. advisory, mandatory, disabled).",+ "severity": "The severity of the policy violation.",+ "priority": "The priority level of the policy issue.",+ "status": "The current triage status of the policy issue (e.g. open, in_progress, ignored, fixed, by_design).",+ "message": "A human-readable message describing the policy violation.",+ "observedAt": "The timestamp when the issue was first observed.",+ "lastModified": "The timestamp when the issue was last modified.",+ "policyName": "The name of the policy that was violated.",+ "policyPack": "The name of the policy pack that produced this issue.",+ "policyPackTag": "The tag of the policy pack version that produced this issue.",+ "policyGroupName": "The name of the policy group this issue belongs to.",+ "policyGroupType": "The type of the policy group this issue belongs to.",+ "resourceName": "The name of the resource that violated the policy.",+ "resourceType": "The type of the resource that violated the policy.",+ "resourceProvider": "The provider of the resource that violated the policy.",+ "resourceURN": "The URN of the resource that violated the policy.",+ "resourceVersion": "The resource version where the issue was detected.",+ "stackVersion": "The stack version where the issue was detected.",+ "assignedTo": "The user the policy issue is assigned to.",+ },+ },+ "resource_summary": {+ "description": "Daily resources under management (RUM) and resource hours under management (RHUM) for the organization over the last year.",+ "docs_url": "https://www.pulumi.com/docs/reference/cloud-rest-api/",+ "columns": {+ "date": "The day of this row as YYYY-MM-DD, built from year, month, and day.",+ "year": "The 4-digit year.",+ "month": "The month of the year, from 1 to 12.",+ "day": "The day of the month, from 1 to 31.",+ "resources": "Resources under management: the average number of resources under management in the period.",+ "resourceHours": "Resource hours under management: the number of hours that resources under management ran in the period.",+ },+ },+ "members": {+ "description": "Members of the organization, with the login that stack updates and audit logs reference.",+ "docs_url": "https://www.pulumi.com/docs/reference/cloud-rest-api/organizations/",+ "columns": {+ "userLogin": "The member's login name, copied from user.githubLogin.",+ "user": "The display information of the member (name, login, avatar URL).",+ "created": "When the member joined the organization.",+ "fgaRole": "The role assigned to the member, either a built-in role (member, admin, billingManager) or a custom role.",+ "role": "Deprecated built-in role of the member; use fgaRole instead.",+ "knownToPulumi": "Whether the member has a Pulumi account.",+ "virtualAdmin": "Whether the member has admin access in Pulumi without admin access on the backing identity provider.",+ "suspended": "Whether the membership is suspended.",+ "links": "Links to the member in the Pulumi Console.",+ },+ },+ "stack_tags": {+ "description": "One row per tag on every stack, including the built-in pulumi:, gitHub:, and vcs: tags.",+ "docs_url": "https://www.pulumi.com/docs/reference/cloud-rest-api/stacks/",+ "columns": {+ "orgName": "The organization of the stack.",+ "projectName": "The project of the stack.",+ "stackName": "The name of the stack.",+ "name": "The tag name.",+ "value": "The tag value.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.posthog-doc.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.posthog-doc.mdxindex 6e023f5ea7e3..a5f4c5b2c69d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.posthog-doc.mdx+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.posthog-doc.mdx@@ -21,8 +21,9 @@ import SyncModes from '../_snippets/sync-modes.mdx'import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'[Pulumi Cloud](https://www.pulumi.com/product/pulumi-cloud/) is the managed control plane for Pulumi-infrastructure as code. This connector pulls your stacks, their full update history, Pulumi Deployments-runs, the Insights resource index, and organization audit logs into the PostHog Data warehouse, so you+infrastructure as code. This connector pulls your stacks and their tags, their full update history, Pulumi+Deployments runs, the Insights resource index, policy issues, organization members, daily resources under+management, and organization audit logs into the PostHog Data warehouse, so youcan measure deployment frequency, change-failure rate, and lead time for infrastructure changes alongsideyour product data.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.pyindex 007db25b7f79..323613caf057 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/pulumi_cloud.py@@ -34,19 +34,25 @@ STACK_UPDATES_LOOKBACK_SECONDS = 24 * 60 * 60# `startTime` lower bound is inclusive, so re-pull a window rather than risk dropping events that# share the watermark second. Merge dedupes the re-pulled rows on the synthetic `event_id`.AUDIT_LOGS_LOOKBACK_SECONDS = 15 * 60+# The resources summary accepts at most one year of lookback.+RESOURCE_SUMMARY_LOOKBACK_DAYS = 365class PulumiCloudRetryableError(Exception):pass[email protected](frozen=True)class PulumiCloudResumeConfig:# Opaque pagination token to resume from: the `continuationToken` for stacks/audit logs, or the# resource-search `cursor`. None means "start from the first page".next_token: str | None = None# 1-based page number to resume the deployments listing from.page: int | None = None+ # Row offset (`startRow`) to resume the policy issues listing from.+ offset: int | None = None+ # Whether the policy issues listing resumes in its closed-issues pass (active issues come first).+ closed_issues: bool = False# Stable "org/project/stack" keys of the fan-out stacks already fully processed in an earlier# attempt of this job. We resume by processing any stack NOT in this set, so a stack created# between a crash and the retry is picked up rather than silently skipped (fan-out persists the@@ -101,8 +107,12 @@ def _fetch(headers: dict[str, str],logger: FilteringBoundLogger,params: Optional[dict[str, Any]] = None,+ json_body: Optional[dict[str, Any]] = None,) -> Any:- response = session.get(url, headers=headers, params=params, timeout=60)+ if json_body is None:+ response = session.get(url, headers=headers, params=params, timeout=60)+ else:+ response = session.post(url, headers=headers, params=params, json=json_body, timeout=60)if response.status_code == 429 or response.status_code >= 500:raise PulumiCloudRetryableError(f"Pulumi Cloud API error (retryable): status={response.status_code}, url={url}")@@ -114,6 +124,9 @@ def _fetch(logger.error(f"Pulumi Cloud API error: status={response.status_code}, url={url}")response.raise_for_status()+ if response.status_code == 204:+ return {}+return response.json()@@ -444,6 +457,177 @@ def _get_resource_rows(logger.warning(f"Pulumi Cloud: resources hit the page cap ({MAX_PAGES}) for org={organization}")+def _policy_issues_request(start_row: int) -> dict[str, Any]:+ # The grid request format requires every list and the filter model, even when empty.+ return {+ "startRow": start_row,+ "endRow": start_row + PAGE_SIZE,+ "rowGroupCols": [],+ "valueCols": [],+ "groupKeys": [],+ "filterModel": {"type": "AND", "conditions": []},+ "sortModel": [],+ }+++def _get_policy_issue_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ organization: str,+ resumable_source_manager: ResumableSourceManager[PulumiCloudResumeConfig],+ config: PulumiCloudEndpointConfig,+) -> Iterator[list[dict[str, Any]]]:+ """Read active issues, then closed issues. The endpoint returns only one of the two per call."""+ url = f"{PULUMI_CLOUD_BASE_URL}{_format_path(config.path, organization)}"++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ resume_closed = resume.closed_issues if resume is not None else False+ resume_offset = resume.offset if resume is not None and resume.offset else 0++ for closed in (False, True):+ if resume_closed and not closed:+ continue+ start_row = resume_offset if closed == resume_closed else 0+ for _ in range(MAX_PAGES):+ data = _fetch(+ session,+ url,+ headers,+ logger,+ params={"closed": "true" if closed else "false"},+ json_body=_policy_issues_request(start_row),+ )+ issues = data.get("policyIssues") or []+ if not issues:+ break+ start_row += len(issues)+ # Advance by the rows received and trust `rowCount` when present, so a server-side page+ # cap below PAGE_SIZE can't end the walk early.+ row_count = data.get("rowCount")+ has_more = start_row < row_count if isinstance(row_count, int) else len(issues) >= PAGE_SIZE+ if has_more:+ resumable_source_manager.save_state(PulumiCloudResumeConfig(offset=start_row, closed_issues=closed))+ elif not closed:+ resumable_source_manager.save_state(PulumiCloudResumeConfig(offset=0, closed_issues=True))+ yield issues+ if not has_more:+ break+ else:+ logger.warning(f"Pulumi Cloud: policy_issues hit the page cap ({MAX_PAGES}) for org={organization}")+++def _resource_summary_date(row: dict[str, Any]) -> str | None:+ year, month, day = row.get("year"), row.get("month"), row.get("day")+ if not isinstance(year, int) or not isinstance(month, int) or not isinstance(day, int):+ return None+ return f"{year:04d}-{month:02d}-{day:02d}"+++def _get_resource_summary_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ organization: str,+ config: PulumiCloudEndpointConfig,+) -> Iterator[list[dict[str, Any]]]:+ url = f"{PULUMI_CLOUD_BASE_URL}{_format_path(config.path, organization)}"+ data = _fetch(+ session,+ url,+ headers,+ logger,+ params={"granularity": "daily", "lookbackDays": RESOURCE_SUMMARY_LOOKBACK_DAYS},+ )+ rows = data.get("summary") or []+ for row in rows:+ row["date"] = _resource_summary_date(row)+ if rows:+ yield rows+++def _get_member_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ organization: str,+ resumable_source_manager: ResumableSourceManager[PulumiCloudResumeConfig],+ config: PulumiCloudEndpointConfig,+) -> Iterator[list[dict[str, Any]]]:+ url = f"{PULUMI_CLOUD_BASE_URL}{_format_path(config.path, organization)}"++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ token = resume.next_token if resume else None++ for _ in range(MAX_PAGES):+ # Ignored for callers without admin access; for admins it also lists suspended members.+ params: dict[str, Any] = {"includeSuspended": "true"}+ if token:+ params["continuationToken"] = token+ data = _fetch(session, url, headers, logger, params=params)+ members = data.get("members") or []+ token = data.get("continuationToken") or None+ for member in members:+ user = member.get("user")+ member["userLogin"] = user.get("githubLogin") if isinstance(user, dict) else None+ if token:+ resumable_source_manager.save_state(PulumiCloudResumeConfig(next_token=token))+ if members:+ yield members+ else:+ resumable_source_manager.safe_point()+ if not token:+ return+ logger.warning(f"Pulumi Cloud: members hit the page cap ({MAX_PAGES}) for org={organization}")+++def _get_stack_tag_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ organization: str,+ resumable_source_manager: ResumableSourceManager[PulumiCloudResumeConfig],+ config: PulumiCloudEndpointConfig,+) -> Iterator[list[dict[str, Any]]]:+ stacks = [stack for page, _ in _iter_stack_pages(session, headers, logger, organization) for stack in page]++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ completed_stack_keys = list(resume.completed_stack_keys) if resume is not None else []+ completed = set(completed_stack_keys)++ for stack_summary in stacks:+ org = stack_summary.get("orgName")+ project = stack_summary.get("projectName")+ stack = stack_summary.get("stackName")+ if not org or not project or not stack:+ continue+ stack_key = f"{org}/{project}/{stack}"+ if stack_key in completed:+ continue++ url = f"{PULUMI_CLOUD_BASE_URL}{_format_path(config.path, org, project, stack)}"+ try:+ data = _fetch(session, url, headers, logger)+ except requests.HTTPError as e:+ # A stack deleted after the listing 404s; treat it as tagless instead of failing the sync.+ if e.response is None or e.response.status_code != 404:+ raise+ data = {}+ tags = data.get("tags") or {}+ rows = [+ {"orgName": org, "projectName": project, "stackName": stack, "name": name, "value": value}+ for name, value in tags.items()+ ]++ completed_stack_keys.append(stack_key)+ completed.add(stack_key)+ resumable_source_manager.save_state(PulumiCloudResumeConfig(completed_stack_keys=list(completed_stack_keys)))+ if rows:+ yield rows+ else:+ resumable_source_manager.safe_point()++def get_rows(access_token: str,organization: str,@@ -490,6 +674,14 @@ def get_rows()elif endpoint == "resources":yield from _get_resource_rows(session, headers, logger, organization, resumable_source_manager, config)+ elif endpoint == "policy_issues":+ yield from _get_policy_issue_rows(session, headers, logger, organization, resumable_source_manager, config)+ elif endpoint == "resource_summary":+ yield from _get_resource_summary_rows(session, headers, logger, organization, config)+ elif endpoint == "members":+ yield from _get_member_rows(session, headers, logger, organization, resumable_source_manager, config)+ elif endpoint == "stack_tags":+ yield from _get_stack_tag_rows(session, headers, logger, organization, resumable_source_manager, config)else:raise ValueError(f"Unknown Pulumi Cloud endpoint: {endpoint}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/settings.pyindex b149c4d074a6..1b5bb21e8826 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/settings.py@@ -3,10 +3,10 @@ from typing import Literal, Optionalfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType-PaginationStyle = Literal["continuation_token", "page", "cursor"]+PaginationStyle = Literal["continuation_token", "page", "cursor", "offset", "single_page"]-@dataclass+@dataclass(frozen=True)class PulumiCloudEndpointConfig:name: strpath: str@@ -42,8 +42,10 @@ class PulumiCloudEndpointConfig:# newest-first ("pageSize=1 with page=1 returns only the most recent update"), so the paginator# stops client-side once an entire page predates the watermark — each incremental run only pays# for the new pages instead of re-walking every stack's full history.-# - `stacks`, `deployments`, and `resources` are current-state listings/indexes with no reliable-# server-side timestamp filter, so they ship as full refresh.+# - `stacks`, `deployments`, `resources`, `policy_issues`, `members`, and `stack_tags` are+# current-state listings/indexes with no reliable server-side timestamp filter, so they ship as+# full refresh. `resource_summary` re-reads a fixed one-year window of daily rows each run, and+# the current day's row keeps changing until the day ends, so it is full refresh too.PULUMI_CLOUD_ENDPOINTS: dict[str, PulumiCloudEndpointConfig] = {"stacks": PulumiCloudEndpointConfig(name="stacks",@@ -112,6 +114,41 @@ PULUMI_CLOUD_ENDPOINTS: dict[str, PulumiCloudEndpointConfig] = {partition_key="created",description="Every resource in the organization's Pulumi Insights resource index, one row per resource",),+ "policy_issues": PulumiCloudEndpointConfig(+ name="policy_issues",+ # POST-only grid query; it supersedes the deprecated GET /policyresults/violationsv2.+ path="/api/orgs/{org}/policyresults/issues",+ primary_keys=["id"],+ pagination="offset",+ partition_key="observedAt",+ description="Policy issues (open and closed) that Policy Packs detected on stacks and Insights resources, with severity, enforcement level, and triage status",+ ),+ "resource_summary": PulumiCloudEndpointConfig(+ name="resource_summary",+ path="/api/orgs/{org}/resources/summary",+ primary_keys=["year", "month", "day"],+ pagination="single_page",+ description="Daily resources under management (RUM) and resource hours under management (RHUM) for the organization over the last year",+ ),+ "members": PulumiCloudEndpointConfig(+ name="members",+ path="/api/orgs/{org}/members",+ # The source copies `user.githubLogin` to a top-level `userLogin`: it is the login that stack+ # updates and audit logs reference, and it is unique within the organization.+ primary_keys=["userLogin"],+ pagination="continuation_token",+ partition_key="created",+ description="Members of the organization, with their login, role, and join date",+ ),+ "stack_tags": PulumiCloudEndpointConfig(+ name="stack_tags",+ # Pulumi has no GET for /tags, so the tags come from the stack detail endpoint.+ path="/api/stacks/{org}/{project}/{stack}",+ primary_keys=["orgName", "projectName", "stackName", "name"],+ pagination="single_page",+ fan_out_over_stacks=True,+ description="One row per tag on every stack (for example environment, owner, or cost center), for grouping stack and update data",+ ),}ENDPOINTS = tuple(PULUMI_CLOUD_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/tests/test_pulumi_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/tests/test_pulumi_cloud.pyindex a9f3fc997ca5..251cb835e987 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/tests/test_pulumi_cloud.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pulumi_cloud/tests/test_pulumi_cloud.py@@ -433,3 +433,158 @@ class TestSourceResponse:assert response.sort_mode == expected_sortassert response.partition_keys == ([partition_key] if partition_key else None)assert response.primary_keys == PULUMI_CLOUD_ENDPOINTS[endpoint].primary_keys+++class TestPolicyIssues:+ @staticmethod+ def _respond(active: list[list[str]], closed: list[list[str]]) -> Callable[[RecordedRequest], ScriptedResponse]:+ def respond(request: RecordedRequest) -> ScriptedResponse:+ pages = closed if request.param("closed") == "true" else active+ total = sum(len(page) for page in pages)+ start_row = request.json()["startRow"]+ seen = 0+ for page in pages:+ if seen == start_row:+ return _json({"policyIssues": [{"id": i} for i in page], "rowCount": total})+ seen += len(page)+ return _json({"policyIssues": [], "rowCount": total})++ return respond++ @staticmethod+ def _calls(result: DriveResult) -> list[tuple[str | None, int]]:+ return [(r.param("closed"), r.json()["startRow"]) for r in result.requests]++ def test_walks_active_then_closed_issues_by_row_offset(self) -> None:+ # Pages shorter than PAGE_SIZE with a larger rowCount model a server-side page cap: a+ # short-page stop would silently drop the rest, and a PAGE_SIZE stride would skip rows.+ result = _run_rows("policy_issues", self._respond(active=[["a1", "a2"], ["a3"]], closed=[["c1"]]))++ assert [r.method for r in result.requests] == ["POST"] * 3+ assert self._calls(result) == [("false", 0), ("false", 2), ("true", 0)]+ assert [r["id"] for r in result.rows] == ["a1", "a2", "a3", "c1"]+ body = result.requests[0].json()+ assert body["endRow"] == PAGE_SIZE+ assert body["filterModel"] == {"type": "AND", "conditions": []}+ assert [(s.offset, s.closed_issues) for s in result.saved_states] == [(2, False), (0, True)]++ @parameterized.expand(+ [+ ("mid_active_pass", PulumiCloudResumeConfig(offset=2), [("false", 2), ("true", 0)], ["a3", "c1"]),+ ("closed_pass", PulumiCloudResumeConfig(offset=0, closed_issues=True), [("true", 0)], ["c1"]),+ ]+ )+ def test_resume(+ self,+ _name: str,+ state: PulumiCloudResumeConfig,+ expected_calls: list[tuple[str, int]],+ expected_ids: list[str],+ ) -> None:+ result = _run_rows(+ "policy_issues", self._respond(active=[["a1", "a2"], ["a3"]], closed=[["c1"]]), resume_state=state+ )++ assert self._calls(result) == expected_calls+ assert [r["id"] for r in result.rows] == expected_ids+++class TestResourceSummary:+ @parameterized.expand(+ [+ (+ "daily_rows",+ _json(+ {+ "summary": [+ {"year": 2026, "month": 3, "day": 7, "resources": 40, "resourceHours": 960},+ {"year": 2026, "month": 3, "resources": 41, "resourceHours": 984},+ ]+ }+ ),+ ["2026-03-07", None],+ ),+ ("no_content", ScriptedResponse(status=204), []),+ ]+ )+ def test_requests_daily_year_and_builds_date(+ self, _name: str, response: ScriptedResponse, expected_dates: list[str | None]+ ) -> None:+ result = _run_rows("resource_summary", [response])++ assert result.params("granularity") == ["daily"]+ assert result.params("lookbackDays") == ["365"]+ assert [r["date"] for r in result.rows] == expected_dates+++class TestMembers:+ def test_follows_continuation_token_and_lifts_login_to_top_level(self) -> None:+ result = _run_rows(+ "members",+ [+ _json(+ {+ "members": [{"user": {"githubLogin": "ada", "name": "Ada"}, "role": "admin"}],+ "continuationToken": "m-2",+ }+ ),+ _json({"members": [{"user": {"githubLogin": "lin", "name": "Lin"}, "role": "member"}]}),+ ],+ )++ assert result.params("continuationToken") == [None, "m-2"]+ assert result.params("includeSuspended") == ["true", "true"]+ assert [r["userLogin"] for r in result.rows] == ["ada", "lin"]+ assert [s.next_token for s in result.saved_states] == ["m-2"]++ def test_resume_starts_from_the_saved_token(self) -> None:+ result = _run_rows(+ "members",+ [_json({"members": []})],+ resume_state=PulumiCloudResumeConfig(next_token="m-2"),+ )++ assert result.params("continuationToken") == ["m-2"]+ assert result.rows == []+++class TestStackTags:+ @staticmethod+ def _respond(request: RecordedRequest) -> ScriptedResponse:+ if request.path == STACKS_PATH:+ return _json({"stacks": [_stack_summary("proj", "dev"), _stack_summary("proj", "prod/eu")]})+ tags = {+ "/api/stacks/my-org/proj/dev": {"env": "dev", "pulumi:project": "proj"},+ "/api/stacks/my-org/proj/prod%2Feu": {},+ }+ return _json({"id": request.path, "version": 1, "tags": tags[request.path]})++ def test_one_row_per_tag_across_stacks(self) -> None:+ result = _run_rows("stack_tags", self._respond)++ assert [(r["stackName"], r["name"], r["value"]) for r in result.rows] == [+ ("dev", "env", "dev"),+ ("dev", "pulumi:project", "proj"),+ ]+ assert result.saved_states[-1].completed_stack_keys == ["my-org/proj/dev", "my-org/proj/prod/eu"]++ def test_resume_skips_completed_stacks(self) -> None:+ result = _run_rows(+ "stack_tags",+ self._respond,+ resume_state=PulumiCloudResumeConfig(completed_stack_keys=["my-org/proj/dev"]),+ )++ assert [r.path for r in result.requests] == [STACKS_PATH, "/api/stacks/my-org/proj/prod%2Feu"]+ assert result.rows == []++ def test_stack_deleted_after_listing_is_skipped(self) -> None:+ def respond(request: RecordedRequest) -> ScriptedResponse:+ if request.path == "/api/stacks/my-org/proj/dev":+ return ScriptedResponse(status=404, json={"code": 404})+ return self._respond(request)++ result = _run_rows("stack_tags", respond)++ assert result.rows == []+ assert result.saved_states[-1].completed_stack_keys == ["my-org/proj/dev", "my-org/proj/prod/eu"]