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(warehouse_sources): add Azure DevOps work item, pipeline and PR work item tables (#101617)

Tom Owersdb55f0b70284
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 1f02c025282b..864e71171562 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
@@ -664,7 +664,7 @@ Note: The wiki.awin.com URLs in the source config are dead - they now 302 to the
## AzureDevOps — **thin**
-Today (16): `build_definitions`, `build_timeline_records`, `builds`, `commits`, `projects`, `pull_request_reviewers`, `pull_request_thread_comments`, `pull_request_threads`, `pull_requests`, `release_deployments`, `releases`, `repositories`, `team_members`, `teams`, `test_runs`, `work_item_revisions`
+Today (23): `build_definitions`, `build_timeline_records`, `builds`, `commits`, `pipeline_runs`, `pipelines`, `projects`, `pull_request_reviewers`, `pull_request_thread_comments`, `pull_request_threads`, `pull_request_work_items`, `pull_requests`, `release_deployments`, `releases`, `repositories`, `team_members`, `teams`, `test_runs`, `work_item_classification_nodes`, `work_item_revisions`, `work_item_type_states`, `work_item_types`, `work_iterations`
Diffed against: <https://github.com/MicrosoftDocs/vsts-rest-api-specs/tree/master/specification>
@@ -677,12 +677,12 @@ Diffed against: <https://github.com/MicrosoftDocs/vsts-rest-api-specs/tree/maste
- [x] `build Timeline (GET /{project}/_apis/build/builds/{buildId}/timeline/{timelineId})` — per-job/step records and durations - where build time actually goes (high)
- [x] `release Releases + release Deployments` — deployment frequency and environment promotion history; entirely absent today (high)
- [x] `testResults Runs + Resultsbybuild` — test pass/fail results per build - the standard quality metric alongside builds (high); landed as `test_runs` from the generally available `test` area. `testResults` Resultsbybuild is preview-only at every API version and sits on a third host, and its shallow per-case rows would need an unbounded per-build fan-out, so it is still open
-- [ ] `work Iterations (GET /{project}/{team}/_apis/work/teamsettings/iterations)` — sprint lookup resolving the iteration path on work item revisions (high)
-- [ ] `wit Work Item Types + Work Item Type States (and Classification Nodes)` — lookup tables resolving type and state values on work_item_revisions, including state category (medium)
-- [ ] `pipelines Pipelines + Runs (GET /{project}/_apis/pipelines, /{pipelineId}/runs)` — the current YAML pipelines model; builds alone misses pipeline-level run data (medium)
-- [ ] `git Pull Request Work Items` — join table linking PRs to the work items they close - connects the two halves we already sync (medium)
+- [x] `work Iterations (GET /{project}/{team}/_apis/work/teamsettings/iterations)` — sprint lookup resolving the iteration path on work item revisions (high)
+- [x] `wit Work Item Types + Work Item Type States (and Classification Nodes)` — lookup tables resolving type and state values on work_item_revisions, including state category (medium)
+- [x] `pipelines Pipelines + Runs (GET /{project}/_apis/pipelines, /{pipelineId}/runs)` — the current YAML pipelines model; builds alone misses pipeline-level run data (medium)
+- [x] `git Pull Request Work Items` — join table linking PRs to the work items they close - connects the two halves we already sync (medium)
-Note: Azure DevOps is one of the largest APIs in this batch (47 spec areas in the official MicrosoftDocs/vsts-rest-api-specs repo), so the tables here are still a small fraction. The organization-wide `GET /_apis/teams` is preview-only, so teams are read per project through the generally available Core endpoint instead. Release Management is served from `vsrm.dev.azure.com` rather than `dev.azure.com`, so `releases` and `release_deployments` address their own host. Build definition listings filter on build times only, never on when the definition changed, so `build_definitions` is full refresh, and the release listing filters on creation time only, so `releases` is too. `build_timeline_records` has no filter of its own and pushes the watermark onto the parent build listing, ordered by finish time so a running or retried build is read again. Diffed against the 7.1 specs for build, core, git, wit, work, release, pipelines, testResults, testPlan, policy, graph, audit and memberEntitlementManagement. Also notable but below the cut: policy Evaluations, git Pushes, graph Users/userentitlements, audit auditlog, testPlan Plans/Suites.
+Note: Azure DevOps is one of the largest APIs in this batch (47 spec areas in the official MicrosoftDocs/vsts-rest-api-specs repo), so the tables here are still a small fraction. The organization-wide `GET /_apis/teams` is preview-only, so teams are read per project through the generally available Core endpoint instead. Release Management is served from `vsrm.dev.azure.com` rather than `dev.azure.com`, so `releases` and `release_deployments` address their own host. Build definition listings filter on build times only, never on when the definition changed, so `build_definitions` is full refresh, and the release listing filters on creation time only, so `releases` is too. `build_timeline_records` has no filter of its own and pushes the watermark onto the parent build listing, ordered by finish time so a running or retried build is read again. `work_iterations` is team-scoped — teams subscribe to iterations from one project tree — so it fans out over teams and keys on the team, while `work_item_classification_nodes` is the project-wide area and iteration tree that resolves the paths on work items; it arrives as a nested tree in one response, so the fan-out flattens it to a row per node and logs when a tree is deeper than the depth requested. The pipeline run listing takes no time filter, so `pipeline_runs` is full refresh; it documents no paging parameters either, so the fan-out follows a continuation token when one comes back but never asks for a page size. Diffed against the 7.1 specs for build, core, git, wit, work, release, pipelines, testResults, testPlan, policy, graph, audit and memberEntitlementManagement. Also notable but below the cut: policy Evaluations, git Pushes, graph Users/userentitlements, audit auditlog, testPlan Plans/Suites.
## Babelforce — gaps
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/azure_devops.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/azure_devops.py
index bea096c9b035..49e9434bc1bb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/azure_devops.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/azure_devops.py
@@ -46,6 +46,9 @@ REQUEST_TIMEOUT_SECONDS = 60
MAX_RETRY_ATTEMPTS = 5
# The test run query rejects a minLastUpdatedDate/maxLastUpdatedDate span wider than this.
TEST_RUN_WINDOW = timedelta(days=7)
+# Classification nodes arrive as a tree in one response, cut off at the requested depth.
+# Area and iteration trees deeper than this are rare; the fan-out logs when one is hit.
+CLASSIFICATION_NODE_DEPTH = 10
class AzureDevOpsRetryableError(Exception):
@@ -203,6 +206,67 @@ def _flatten_team_member(item: dict[str, Any], project: dict[str, Any], team: di
}
+def _with_team_ref(item: dict[str, Any], project: dict[str, Any], team: dict[str, Any]) -> dict[str, Any]:
+ return {
+ **item,
+ "project_id": project.get("id"),
+ "project_name": project.get("name"),
+ "team_id": team.get("id"),
+ "team_name": team.get("name"),
+ }
+
+
+def _with_work_item_type_ref(
+ item: dict[str, Any], project: dict[str, Any], work_item_type: dict[str, Any]
+) -> dict[str, Any]:
+ # A state row carries only a name, a colour and a category, so the type it belongs to
+ # has to come from the parent — two thirds of the primary key live here.
+ return {
+ **item,
+ "project_id": project.get("id"),
+ "project_name": project.get("name"),
+ "work_item_type": work_item_type.get("name"),
+ "work_item_type_reference_name": work_item_type.get("referenceName"),
+ }
+
+
+def _with_pipeline_ref(item: dict[str, Any], project: dict[str, Any], pipeline: dict[str, Any]) -> dict[str, Any]:
+ return {
+ **item,
+ "project_id": project.get("id"),
+ "project_name": project.get("name"),
+ "pipeline_id": pipeline.get("id"),
+ "pipeline_name": pipeline.get("name"),
+ }
+
+
+def _flatten_classification_nodes(
+ root: dict[str, Any], project: dict[str, Any], logger: FilteringBoundLogger
+) -> list[dict[str, Any]]:
+ """Walk one area or iteration tree into a row per node, dropping the nested subtree so a
+ node is not repeated inside each of its ancestors."""
+ rows: list[dict[str, Any]] = []
+ stack: list[tuple[dict[str, Any], Any]] = [(root, None)]
+ while stack:
+ node, parent_id = stack.pop()
+ children = node.get("children") or []
+ if node.get("hasChildren") and not children:
+ logger.warning(
+ f"Azure DevOps: classification node tree in project {project.get('name')} is deeper than "
+ f"{CLASSIFICATION_NODE_DEPTH} levels; children of node {node.get('id')} are not synced"
+ )
+ rows.append(
+ {
+ **{key: value for key, value in node.items() if key != "children"},
+ "project_id": project.get("id"),
+ "project_name": project.get("name"),
+ "parent_id": parent_id,
+ }
+ )
+ stack.extend((child, node.get("id")) for child in children)
+ return rows
+
+
# Actionable reasons returned by the create-time credential probe. The sync-time equivalents live in
# AzureDevOpsSource.get_non_retryable_errors, keyed on the raw HTTP error text raise_for_status emits.
_INVALID_ORGANIZATION_MESSAGE = "That doesn't look like a valid Azure DevOps organization name. Enter just the organization name, for example myorg."
@@ -314,11 +378,20 @@ def get_rows(
return params
def iterate_header_token(
- path: str, extra: dict[str, Any], use_base_params: bool = True, base_url: str = AZURE_DEVOPS_BASE_URL
+ path: str,
+ extra: dict[str, Any],
+ use_base_params: bool = True,
+ base_url: str = AZURE_DEVOPS_BASE_URL,
+ # `None` leaves $top off, for an endpoint that documents no page size. Asking for one
+ # there risks a server that honours $top but sends no token back, which would cut the
+ # listing down to a single short page.
+ page_size: Optional[int] = PAGE_SIZE,
) -> Iterator[list[dict[str, Any]]]:
token: Optional[str] = None
while True:
- params = {**(base_params() if use_base_params else {}), **extra, "$top": PAGE_SIZE}
+ params = {**(base_params() if use_base_params else {}), **extra}
+ if page_size is not None:
+ params["$top"] = page_size
if token:
params["continuationToken"] = token
response = fetch(path, params, base_url)
@@ -362,6 +435,10 @@ def get_rows(
path = AZURE_DEVOPS_ENDPOINTS["teams"].path.replace("{project}", quote(str(project["id"])))
yield from iterate_skip(path, {}, use_base_params=False)
+ def pipelines_for(project: dict[str, Any]) -> Iterator[list[dict[str, Any]]]:
+ path = AZURE_DEVOPS_ENDPOINTS["pipelines"].path.replace("{project}", quote(str(project["id"])))
+ yield from iterate_header_token(path, {}, use_base_params=False)
+
def builds_for(project: str) -> Iterator[list[dict[str, Any]]]:
# The timeline endpoint takes no filter, so the endpoint's minTime watermark
# lands here and bounds which builds an incremental sync visits at all. minTime
@@ -442,6 +519,31 @@ def get_rows(
yield rows
return
+ if endpoint == "pipelines":
+ for project_row in projects():
+ if not project_row.get("id"):
+ continue
+ for page in pipelines_for(project_row):
+ yield [_with_project_ref(item, project_row) for item in page]
+ return
+
+ if endpoint == "pipeline_runs":
+ for project_row in projects():
+ if not project_row.get("id"):
+ continue
+ for pipeline_page in pipelines_for(project_row):
+ for pipeline in pipeline_page:
+ if pipeline.get("id") is None:
+ continue
+ path = config.path.replace("{project}", quote(str(project_row["id"]))).replace(
+ "{pipelineId}", quote(str(pipeline["id"]))
+ )
+ # The run listing documents no paging parameters, but Azure DevOps sends a
+ # continuation token on listings that overflow, so follow one when it comes.
+ for page in iterate_header_token(path, {}, use_base_params=False, page_size=None):
+ yield [_with_pipeline_ref(item, project_row, pipeline) for item in page]
+ return
+
if endpoint in ("releases", "release_deployments"):
for project_row in projects():
if not project_row.get("name"):
@@ -514,11 +616,11 @@ def get_rows(
yield rows
return
- if endpoint == "pull_request_reviewers":
+ if endpoint in ("pull_request_reviewers", "pull_request_work_items"):
for ref in pull_request_refs():
- reviewers = fetch(pull_request_child_path(ref), {}).json().get("value", []) or []
- if reviewers:
- yield [_with_pull_request_ref(item, ref) for item in reviewers]
+ items = fetch(pull_request_child_path(ref), {}).json().get("value", []) or []
+ if items:
+ yield [_with_pull_request_ref(item, ref) for item in items]
return
if endpoint == "teams":
@@ -544,6 +646,56 @@ def get_rows(
yield [_flatten_team_member(item, project_row, team) for item in page]
return
+ if endpoint in ("work_item_types", "work_item_type_states"):
+ want_states = endpoint == "work_item_type_states"
+ types_path = AZURE_DEVOPS_ENDPOINTS["work_item_types"].path
+ for project_row in projects():
+ if not project_row.get("id"):
+ continue
+ project_segment = quote(str(project_row["id"]))
+ types = fetch(types_path.replace("{project}", project_segment), {}).json().get("value", []) or []
+ if not want_states:
+ if types:
+ yield [_with_project_ref(item, project_row) for item in types]
+ continue
+ for work_item_type in types:
+ if not work_item_type.get("name"):
+ continue
+ path = config.path.replace("{project}", project_segment).replace(
+ "{workItemType}", quote(work_item_type["name"])
+ )
+ states = fetch(path, {}).json().get("value", []) or []
+ if states:
+ yield [_with_work_item_type_ref(item, project_row, work_item_type) for item in states]
+ return
+
+ if endpoint == "work_item_classification_nodes":
+ for project_row in projects():
+ if not project_row.get("id"):
+ continue
+ path = config.path.replace("{project}", quote(str(project_row["id"])))
+ roots = fetch(path, {"$depth": CLASSIFICATION_NODE_DEPTH}).json().get("value", []) or []
+ rows = [row for root in roots for row in _flatten_classification_nodes(root, project_row, logger)]
+ if rows:
+ yield rows
+ return
+
+ if endpoint == "work_iterations":
+ for project_row in projects():
+ if not project_row.get("id"):
+ continue
+ for team_page in teams_for(project_row):
+ for team in team_page:
+ if not team.get("id"):
+ continue
+ path = config.path.replace("{project}", quote(str(project_row["id"]))).replace(
+ "{teamId}", quote(str(team["id"]))
+ )
+ iterations = fetch(path, {}).json().get("value", []) or []
+ if iterations:
+ yield [_with_team_ref(item, project_row, team) for item in iterations]
+ return
+
# work_item_revisions: org-level reporting endpoint with a body
# continuationToken that doubles as a resumable watermark.
resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/canonical_descriptions.py
index c939b4302595..6d7e431fea09 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/canonical_descriptions.py
@@ -295,6 +295,115 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"conditions": "Conditions and gates associated with the deployment.",
},
},
+ "pull_request_work_items": {
+ "description": "A link between a pull request and a work item it resolves or references.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-request-work-items/list",
+ "columns": {
+ "id": "Identifier of the linked work item.",
+ "url": "API URL of the linked work item.",
+ "project_name": "Name of the project the pull request belongs to.",
+ "repository_id": "Identifier of the repository the pull request belongs to.",
+ "pull_request_id": "Identifier of the pull request the work item is linked to.",
+ },
+ },
+ "pipelines": {
+ "description": "A YAML pipeline defined in an Azure DevOps project.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/pipelines/list",
+ "columns": {
+ "id": "Identifier of the pipeline.",
+ "name": "Name of the pipeline.",
+ "folder": "Folder the pipeline is filed under.",
+ "revision": "Revision number of the pipeline, incremented on each change.",
+ "url": "API URL of the pipeline.",
+ "project_id": "Identifier of the project the pipeline belongs to.",
+ "project_name": "Name of the project the pipeline belongs to.",
+ },
+ },
+ "pipeline_runs": {
+ "description": "A run of a YAML pipeline, with its state, result and timings.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/list",
+ "columns": {
+ "id": "Identifier of the run.",
+ "name": "Name of the run.",
+ "state": "State of the run (unknown, inProgress, canceling, completed).",
+ "result": "Result of a completed run (unknown, succeeded, failed, canceled).",
+ "createdDate": "Time at which the run was created.",
+ "finishedDate": "Time at which the run finished.",
+ "templateParameters": "Template parameters the run was started with.",
+ "pipeline": "The pipeline the run belongs to.",
+ "resources": "Repositories, pipelines and containers the run consumed.",
+ "url": "API URL of the run.",
+ "project_id": "Identifier of the project the run belongs to.",
+ "project_name": "Name of the project the run belongs to.",
+ "pipeline_id": "Identifier of the pipeline the run belongs to.",
+ "pipeline_name": "Name of the pipeline the run belongs to.",
+ },
+ },
+ "work_item_types": {
+ "description": "A work item type defined by a project's process, such as Bug, Task or User Story.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work-item-types/list",
+ "columns": {
+ "name": "Display name of the work item type.",
+ "referenceName": "Reference name of the work item type, as used in work item field values.",
+ "description": "Description of the work item type.",
+ "color": "Colour of the work item type.",
+ "icon": "Icon of the work item type.",
+ "isDisabled": "Whether the work item type is disabled for the project.",
+ "states": "States the work item type can be in.",
+ "transitions": "Allowed transitions between the type's states.",
+ "fields": "Fields defined on the work item type.",
+ "fieldInstances": "Field definitions as instantiated on the work item type.",
+ "xmlForm": "XML definition of the work item form.",
+ "url": "API URL of the work item type.",
+ "project_id": "Identifier of the project the type is defined in.",
+ "project_name": "Name of the project the type is defined in.",
+ },
+ },
+ "work_item_type_states": {
+ "description": "A state a work item type can be in, with the state category that groups it.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work-item-type-states/list",
+ "columns": {
+ "name": "Name of the state, as it appears in the System.State field.",
+ "color": "Colour of the state.",
+ "category": "Category the state belongs to (Proposed, InProgress, Resolved, Completed, Removed).",
+ "project_id": "Identifier of the project the state is defined in.",
+ "project_name": "Name of the project the state is defined in.",
+ "work_item_type": "Name of the work item type the state belongs to.",
+ "work_item_type_reference_name": "Reference name of the work item type the state belongs to.",
+ },
+ },
+ "work_item_classification_nodes": {
+ "description": "One node of a project's area or iteration tree, resolving the area and iteration paths on work items.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/classification-nodes/get-root-nodes",
+ "columns": {
+ "id": "Identifier of the node within the project.",
+ "identifier": "Globally unique identifier of the node.",
+ "name": "Name of the node.",
+ "path": "Full path of the node, matching the area or iteration path on a work item.",
+ "structureType": "Type of tree the node belongs to (area or iteration).",
+ "hasChildren": "Whether the node has child nodes.",
+ "attributes": "Node attributes; for an iteration node, its start and finish dates.",
+ "url": "API URL of the node.",
+ "parent_id": "Identifier of the node's parent, or null for a root node.",
+ "project_id": "Identifier of the project the node belongs to.",
+ "project_name": "Name of the project the node belongs to.",
+ },
+ },
+ "work_iterations": {
+ "description": "An iteration (sprint) a team is subscribed to, with its dates and relative timeframe.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/work/iterations/list",
+ "columns": {
+ "id": "Identifier of the iteration.",
+ "name": "Name of the iteration.",
+ "path": "Full iteration path, matching the iteration path on a work item.",
+ "attributes": "Start date, finish date and relative timeframe of the iteration.",
+ "url": "API URL of the team's iteration.",
+ "project_id": "Identifier of the project the iteration belongs to.",
+ "project_name": "Name of the project the iteration belongs to.",
+ "team_id": "Identifier of the team subscribed to the iteration.",
+ "team_name": "Name of the team subscribed to the iteration.",
+ },
+ },
"test_runs": {
"description": "A test run published against a build or release, with its pass and fail counts.",
"docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/test/runs/list",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/settings.py
index f525bfd8d5c9..e05bc6a06921 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/settings.py
@@ -10,17 +10,18 @@ AZURE_DEVOPS_RELEASE_BASE_URL = "https://vsrm.dev.azure.com"
# Azure DevOps mixes pagination styles per endpoint, dispatched by name in
# azure_devops.py:
-# - projects/builds/build_definitions/releases/release_deployments: continuationToken
-# via the x-ms-continuationtoken header
+# - projects/builds/build_definitions/releases/release_deployments/pipelines:
+# continuationToken via the x-ms-continuationtoken header
# - pull_requests/commits/teams/team_members/test_runs: $top/$skip offset paging
# - work_item_revisions: body continuationToken + isLastBatch (reporting endpoint)
-# - repositories/pull request threads/reviewers/build timelines: single response per parent
+# - repositories/pull request threads/reviewers/work items/build timelines/pipeline runs/
+# work item types/type states/classification nodes/team iterations: single response per parent
@dataclass(frozen=True)
class AzureDevOpsEndpointConfig:
name: str
# Path template under {base_url}/{organization}. `{project}`, `{repositoryId}`,
- # `{pullRequestId}`, `{buildId}` and `{teamId}` are substituted during the
- # fan-out that reaches the endpoint.
+ # `{pullRequestId}`, `{buildId}`, `{teamId}`, `{pipelineId}` and `{workItemType}`
+ # are substituted during the fan-out that reaches the endpoint.
path: str
base_url: str = AZURE_DEVOPS_BASE_URL
primary_keys: list[str] = field(default_factory=lambda: ["id"])
@@ -92,6 +93,21 @@ AZURE_DEVOPS_ENDPOINTS: dict[str, AzureDevOpsEndpointConfig] = {
},
],
),
+ "pipelines": AzureDevOpsEndpointConfig(
+ name="pipelines",
+ path="/{project}/_apis/pipelines",
+ # Pipeline IDs restart per project.
+ primary_keys=["project_id", "id"],
+ ),
+ "pipeline_runs": AzureDevOpsEndpointConfig(
+ name="pipeline_runs",
+ path="/{project}/_apis/pipelines/{pipelineId}/runs",
+ # Run IDs restart per project.
+ primary_keys=["project_id", "id"],
+ partition_key="createdDate",
+ # The run listing takes no time filter — it answers with the pipeline's most recent
+ # runs — so there is no cursor to sync incrementally on.
+ ),
"pull_requests": AzureDevOpsEndpointConfig(
name="pull_requests",
path="/{project}/_apis/git/pullrequests",
@@ -153,6 +169,13 @@ AZURE_DEVOPS_ENDPOINTS: dict[str, AzureDevOpsEndpointConfig] = {
path="/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/reviewers",
primary_keys=["repository_id", "pull_request_id", "id"],
),
+ "pull_request_work_items": AzureDevOpsEndpointConfig(
+ name="pull_request_work_items",
+ path="/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/workitems",
+ # The row is a link, not the work item itself: the same work item can be linked
+ # from pull requests in several repositories.
+ primary_keys=["repository_id", "pull_request_id", "id"],
+ ),
"teams": AzureDevOpsEndpointConfig(
name="teams",
# The organization-wide GET /_apis/teams is preview-only, so teams are read
@@ -182,6 +205,32 @@ AZURE_DEVOPS_ENDPOINTS: dict[str, AzureDevOpsEndpointConfig] = {
},
],
),
+ "work_item_types": AzureDevOpsEndpointConfig(
+ name="work_item_types",
+ path="/{project}/_apis/wit/workitemtypes",
+ # A type is defined by the project's process, so the same reference name
+ # describes a different type in another project.
+ primary_keys=["project_id", "referenceName"],
+ ),
+ "work_item_type_states": AzureDevOpsEndpointConfig(
+ name="work_item_type_states",
+ path="/{project}/_apis/wit/workitemtypes/{workItemType}/states",
+ # A state is named per type; only the state category is shared vocabulary.
+ primary_keys=["project_id", "work_item_type", "name"],
+ ),
+ "work_item_classification_nodes": AzureDevOpsEndpointConfig(
+ name="work_item_classification_nodes",
+ path="/{project}/_apis/wit/classificationnodes",
+ # Node IDs restart per project.
+ primary_keys=["project_id", "id"],
+ ),
+ "work_iterations": AzureDevOpsEndpointConfig(
+ name="work_iterations",
+ path="/{project}/{teamId}/_apis/work/teamsettings/iterations",
+ # Teams subscribe to iterations from the project's shared tree, so one iteration
+ # yields a row per team that uses it.
+ primary_keys=["team_id", "id"],
+ ),
"releases": AzureDevOpsEndpointConfig(
name="releases",
path="/{project}/_apis/release/releases",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/tests/test_azure_devops.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/tests/test_azure_devops.py
index a5ca20d14171..5e8db3403a82 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/tests/test_azure_devops.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_devops/tests/test_azure_devops.py
@@ -15,9 +15,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.azure_devo
_UNREACHABLE_MESSAGE,
AZURE_DEVOPS_VERSION_7_2,
AZURE_DEVOPS_VERSION_LEGACY,
+ CLASSIFICATION_NODE_DEPTH,
TEST_RUN_WINDOW,
AzureDevOpsAuthError,
AzureDevOpsResumeConfig,
+ _flatten_classification_nodes,
_flatten_revision,
_format_datetime,
_last_updated_windows,
@@ -615,6 +617,257 @@ class TestFanOutEndpoints:
)
+class TestPipelineEndpoints:
+ PROJECTS = {"value": [{"id": "proj-guid", "name": "Alpha"}]}
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_pipelines_paginate_via_header_token_and_carry_the_project(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": 3, "name": "deploy"}]}, continuation_header="tok1"),
+ _response({"value": [{"id": 4, "name": "release"}]}),
+ ]
+
+ batches = list(
+ get_rows("myorg", "pat", "pipelines", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2)
+ )
+
+ # project_id is half the composite primary key, so it must be present.
+ assert [(row["id"], row["project_id"]) for batch in batches for row in batch] == [
+ (3, "proj-guid"),
+ (4, "proj-guid"),
+ ]
+ first, second = (call.args[0] for call in mock_session.return_value.get.call_args_list[1:])
+ assert urlparse(first).path == "/myorg/proj-guid/_apis/pipelines"
+ assert parse_qs(urlparse(second).query)["continuationToken"] == ["tok1"]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_pipeline_runs_fan_out_per_pipeline_and_carry_it(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": 3, "name": "deploy"}]}),
+ _response({"value": [{"id": 91, "state": "completed", "createdDate": "2024-01-02T03:04:05Z"}]}),
+ ]
+
+ batches = list(
+ get_rows("myorg", "pat", "pipeline_runs", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2)
+ )
+
+ row = batches[0][0]
+ assert (row["id"], row["project_id"], row["pipeline_id"], row["pipeline_name"]) == (
+ 91,
+ "proj-guid",
+ 3,
+ "deploy",
+ )
+ assert urlparse(mock_session.return_value.get.call_args_list[2].args[0]).path == (
+ "/myorg/proj-guid/_apis/pipelines/3/runs"
+ )
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_pipeline_runs_follow_a_continuation_token_without_asking_for_a_page_size(self, mock_session):
+ # The listing documents no paging parameters. Reading one response would cap the table
+ # at whatever the vendor returns in it, and sending $top could shorten that response.
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": 3, "name": "deploy"}]}),
+ _response({"value": [{"id": 91}]}, continuation_header="tok1"),
+ _response({"value": [{"id": 92}]}),
+ ]
+
+ batches = list(
+ get_rows("myorg", "pat", "pipeline_runs", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2)
+ )
+
+ assert [row["id"] for batch in batches for row in batch] == [91, 92]
+ first, second = (
+ parse_qs(urlparse(call.args[0]).query) for call in mock_session.return_value.get.call_args_list[2:]
+ )
+ assert "$top" not in first
+ assert second["continuationToken"] == ["tok1"]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_pipeline_runs_skip_a_pipeline_without_an_id(self, mock_session):
+ # Requesting one anyway would build a path with a literal {pipelineId} placeholder.
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"name": "deploy"}]}),
+ ]
+
+ batches = list(
+ get_rows("myorg", "pat", "pipeline_runs", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2)
+ )
+
+ assert batches == []
+ assert len(mock_session.return_value.get.call_args_list) == 2
+
+
+class TestWorkItemLookupEndpoints:
+ PROJECTS = {"value": [{"id": "proj-guid", "name": "Alpha"}]}
+ TYPES = {"value": [{"name": "User Story", "referenceName": "Microsoft.VSTS.WorkItemTypes.UserStory"}]}
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_work_item_types_carry_the_project_reference(self, mock_session):
+ mock_session.return_value.get.side_effect = [_response(self.PROJECTS), _response(self.TYPES)]
+
+ batches = list(
+ get_rows("myorg", "pat", "work_item_types", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2)
+ )
+
+ row = batches[0][0]
+ # project_id is half the composite primary key, so it must be present.
+ assert (row["referenceName"], row["project_id"], row["project_name"]) == (
+ "Microsoft.VSTS.WorkItemTypes.UserStory",
+ "proj-guid",
+ "Alpha",
+ )
+ assert urlparse(mock_session.return_value.get.call_args_list[1].args[0]).path == (
+ "/myorg/proj-guid/_apis/wit/workitemtypes"
+ )
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_work_item_type_states_fan_out_over_types_and_encode_the_type_name(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response(self.TYPES),
+ _response({"value": [{"name": "Active", "color": "007acc", "category": "InProgress"}]}),
+ ]
+
+ batches = list(
+ get_rows(
+ "myorg", "pat", "work_item_type_states", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2
+ )
+ )
+
+ row = batches[0][0]
+ # A state row carries only name/colour/category, so the rest of the primary key
+ # has to be injected from the parent type.
+ assert (row["name"], row["category"], row["project_id"], row["work_item_type"]) == (
+ "Active",
+ "InProgress",
+ "proj-guid",
+ "User Story",
+ )
+ assert row["work_item_type_reference_name"] == "Microsoft.VSTS.WorkItemTypes.UserStory"
+ # Type names contain spaces, which must be percent-encoded into the path.
+ assert urlparse(mock_session.return_value.get.call_args_list[2].args[0]).path == (
+ "/myorg/proj-guid/_apis/wit/workitemtypes/User%20Story/states"
+ )
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_classification_nodes_request_the_full_tree_depth(self, mock_session):
+ mock_session.return_value.get.side_effect = [_response(self.PROJECTS), _response({"value": []})]
+
+ list(
+ get_rows(
+ "myorg",
+ "pat",
+ "work_item_classification_nodes",
+ mock.MagicMock(),
+ _make_manager(),
+ AZURE_DEVOPS_VERSION_7_2,
+ )
+ )
+
+ parsed = urlparse(mock_session.return_value.get.call_args_list[1].args[0])
+ assert parsed.path == "/myorg/proj-guid/_apis/wit/classificationnodes"
+ # Without $depth the API answers with the two roots and no children at all.
+ assert parse_qs(parsed.query)["$depth"] == [str(CLASSIFICATION_NODE_DEPTH)]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_work_iterations_fan_out_over_teams(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": "team-1", "name": "QA"}]}),
+ _response({"value": [{"id": "iter-guid", "name": "Sprint 1", "path": "Alpha\\Sprint 1"}]}),
+ _response({"value": []}),
+ ]
+
+ batches = list(
+ get_rows("myorg", "pat", "work_iterations", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2)
+ )
+
+ row = batches[0][0]
+ # team_id is half the composite primary key: teams share one project iteration tree,
+ # so the same iteration id comes back for every team subscribed to it.
+ assert (row["id"], row["team_id"], row["team_name"], row["project_id"]) == (
+ "iter-guid",
+ "team-1",
+ "QA",
+ "proj-guid",
+ )
+ assert urlparse(mock_session.return_value.get.call_args_list[2].args[0]).path == (
+ "/myorg/proj-guid/team-1/_apis/work/teamsettings/iterations"
+ )
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_pull_request_work_items_carry_their_parent_identifiers(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"pullRequestId": 22, "repository": {"id": "repo-1"}}]}),
+ _response({"value": [{"id": "314", "url": "https://dev.azure.com/myorg/_apis/wit/workItems/314"}]}),
+ _response({"value": []}),
+ ]
+
+ batches = list(
+ get_rows(
+ "myorg", "pat", "pull_request_work_items", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2
+ )
+ )
+
+ row = batches[0][0]
+ # The link row is only an id and a URL, so both parent identifiers must be injected.
+ assert (row["id"], row["repository_id"], row["pull_request_id"]) == ("314", "repo-1", 22)
+ assert urlparse(mock_session.return_value.get.call_args_list[2].args[0]).path == (
+ "/myorg/Alpha/_apis/git/repositories/repo-1/pullRequests/22/workitems"
+ )
+
+
+class TestFlattenClassificationNodes:
+ PROJECT = {"id": "proj-guid", "name": "Alpha"}
+
+ def test_flattens_the_tree_and_drops_the_nested_children(self):
+ root = {
+ "id": 1,
+ "name": "Alpha",
+ "structureType": "area",
+ "hasChildren": True,
+ "children": [{"id": 2, "name": "Web", "structureType": "area", "hasChildren": False}],
+ }
+
+ rows = _flatten_classification_nodes(root, self.PROJECT, mock.MagicMock())
+
+ assert sorted((row["id"], row["parent_id"]) for row in rows) == [(1, None), (2, 1)]
+ # Keeping `children` would repeat every descendant inside each of its ancestors.
+ assert all("children" not in row for row in rows)
+ assert {row["project_id"] for row in rows} == {"proj-guid"}
+
+ def test_warns_when_the_tree_is_cut_off_at_the_requested_depth(self):
+ logger = mock.MagicMock()
+
+ _flatten_classification_nodes({"id": 1, "hasChildren": True}, self.PROJECT, logger)
+
+ logger.warning.assert_called_once()
+
+
class TestLastUpdatedWindows:
def test_splits_a_long_span_into_windows_no_wider_than_the_cap(self):
since = datetime(2024, 1, 1, tzinfo=UTC)