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 build, release and test tables (#100954)

Tom Owers37493eb1c55e
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 1f9b40f7606b..122215835aa8 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 (11): `builds`, `commits`, `projects`, `pull_request_reviewers`, `pull_request_thread_comments`, `pull_request_threads`, `pull_requests`, `repositories`, `team_members`, `teams`, `work_item_revisions`
+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`
Diffed against: <https://github.com/MicrosoftDocs/vsts-rest-api-specs/tree/master/specification>
@@ -673,16 +673,16 @@ Diffed against: <https://github.com/MicrosoftDocs/vsts-rest-api-specs/tree/maste
- [x] `git Pull Request Reviewers (and Pull Request Iteration Statuses)` — approval votes per reviewer; the membership table that turns pull_requests into review analytics (high)
- [x] `core Teams (GET /_apis/teams, /projects/{projectId}/teams) and Team Members` — lookup resolving team ownership for projects, work items and boards (high)
- [ ] `git Pull Request Iteration Statuses (GET .../pullRequests/{pullRequestId}/iterations/{iterationId}/statuses)` — per-iteration policy and status checks; needs a fan-out one level deeper than the reviewers table above (medium)
-- [ ] `build Definitions (GET /{project}/_apis/build/definitions)` — lookup resolving definition.id carried on every build row we already sync (high)
-- [ ] `build Timeline (GET /{project}/_apis/build/builds/{buildId}/timeline/{timelineId})` — per-job/step records and durations - where build time actually goes (high)
-- [ ] `release Releases + release Deployments` — deployment frequency and environment promotion history; entirely absent today (high)
-- [ ] `testResults Runs + Resultsbybuild` — test pass/fail results per build - the standard quality metric alongside builds (high)
+- [x] `build Definitions (GET /{project}/_apis/build/definitions)` — lookup resolving definition.id carried on every build row we already sync (high)
+- [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)
-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. 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. 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 86cc4035b243..bea096c9b035 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
@@ -1,7 +1,7 @@
import re
import dataclasses
from collections.abc import Iterator
-from datetime import UTC, date, datetime
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
from urllib.parse import quote, urlencode
@@ -9,7 +9,10 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.settings import (
+ AZURE_DEVOPS_BASE_URL,
AZURE_DEVOPS_ENDPOINTS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSION
@@ -17,8 +20,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-AZURE_DEVOPS_BASE_URL = "https://dev.azure.com"
-
# Source version labels. The legacy label predates versioning and keeps sending
# api-version 7.1 so existing syncs are unchanged; 7.2 is the current GA stable API.
AZURE_DEVOPS_VERSION_LEGACY = UNVERSIONED_API_VERSION
@@ -43,6 +44,8 @@ REQUEST_TIMEOUT_SECONDS = 60
# Rate limiting is 200 TSTUs per identity per sliding 5-minute window; 429s
# carry Retry-After but exponential backoff is sufficient.
MAX_RETRY_ATTEMPTS = 5
+# The test run query rejects a minLastUpdatedDate/maxLastUpdatedDate span wider than this.
+TEST_RUN_WINDOW = timedelta(days=7)
class AzureDevOpsRetryableError(Exception):
@@ -95,6 +98,37 @@ def _format_datetime(value: Any) -> str:
return str(value)
+def _parse_datetime(value: Any) -> Optional[datetime]:
+ """Read an incremental cursor back into a datetime, or None when it isn't one."""
+ if isinstance(value, datetime):
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime(value.year, value.month, value.day, tzinfo=UTC)
+ if isinstance(value, str):
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+ return None
+
+
+@frozen
+class LastUpdatedWindow:
+ """One minLastUpdatedDate/maxLastUpdatedDate pair for the test run query."""
+
+ min_last_updated: str
+ max_last_updated: str
+
+
+def _last_updated_windows(since: datetime, until: datetime) -> Iterator[LastUpdatedWindow]:
+ start = since
+ while start < until:
+ end = min(start + TEST_RUN_WINDOW, until)
+ yield LastUpdatedWindow(min_last_updated=_format_datetime(start), max_last_updated=_format_datetime(end))
+ start = end
+
+
def _flatten_revision(item: dict[str, Any]) -> dict[str, Any]:
# Revision payloads nest everything interesting under `fields`; copy the
# watermark field to the top level so the pipeline can track it.
@@ -138,12 +172,27 @@ def _flatten_thread_comments(thread: dict[str, Any], ref: PullRequestRef) -> lis
]
-def _flatten_team(item: dict[str, Any], project: dict[str, Any]) -> dict[str, Any]:
- # This endpoint leaves WebApiTeam's optional project fields unset, so the
- # fan-out parent supplies them.
+def _with_project_ref(item: dict[str, Any], project: dict[str, Any]) -> dict[str, Any]:
+ # Project-fan-out rows either leave the project unset or nest it, and project_id is
+ # part of the primary key on several of them, so the parent supplies both fields.
return {**item, "project_id": project.get("id"), "project_name": project.get("name")}
+def _flatten_timeline_record(
+ record: dict[str, Any], project: str, build: dict[str, Any], timeline_id: Any
+) -> dict[str, Any]:
+ # A record only makes sense against the run it describes. The build supplies both the
+ # stable partition field and the watermark field, which the record itself does not carry.
+ return {
+ **record,
+ "project_name": project,
+ "build_id": build.get("id"),
+ "build_queue_time": build.get("queueTime"),
+ "build_finish_time": build.get("finishTime"),
+ "timeline_id": timeline_id,
+ }
+
+
def _flatten_team_member(item: dict[str, Any], project: dict[str, Any], team: dict[str, Any]) -> dict[str, Any]:
return {
**item,
@@ -231,8 +280,8 @@ def get_rows(
wait=wait_exponential_jitter(initial=2, max=120),
reraise=True,
)
- def fetch(path: str, params: dict[str, Any]) -> requests.Response:
- url = f"{AZURE_DEVOPS_BASE_URL}/{quote(org)}{path}?{urlencode({**params, 'api-version': wire_version})}"
+ def fetch(path: str, params: dict[str, Any], base_url: str = AZURE_DEVOPS_BASE_URL) -> requests.Response:
+ url = f"{base_url}/{quote(org)}{path}?{urlencode({**params, 'api-version': wire_version})}"
response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
if response.status_code == 429 or response.status_code >= 500:
@@ -265,14 +314,14 @@ def get_rows(
return params
def iterate_header_token(
- path: str, extra: dict[str, Any], use_base_params: bool = True
+ path: str, extra: dict[str, Any], use_base_params: bool = True, base_url: str = AZURE_DEVOPS_BASE_URL
) -> Iterator[list[dict[str, Any]]]:
token: Optional[str] = None
while True:
params = {**(base_params() if use_base_params else {}), **extra, "$top": PAGE_SIZE}
if token:
params["continuationToken"] = token
- response = fetch(path, params)
+ response = fetch(path, params, base_url)
items = response.json().get("value", []) or []
if items:
yield items
@@ -313,6 +362,16 @@ 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 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
+ # filters on whichever time queryOrder names, so ordering by finish time makes
+ # the cursor a finish time: a build still running has none and is skipped until
+ # it ends, and a retried build's finish time moves forward so its timeline is
+ # read again.
+ path = AZURE_DEVOPS_ENDPOINTS["builds"].path.replace("{project}", quote(project))
+ yield from iterate_header_token(path, {"queryOrder": "finishTimeAscending"})
+
def pull_request_refs() -> Iterator[PullRequestRef]:
pr_path = AZURE_DEVOPS_ENDPOINTS["pull_requests"].path
for project in project_names():
@@ -351,6 +410,75 @@ def get_rows(
)
return
+ if endpoint == "build_definitions":
+ for project_row in projects():
+ if not project_row.get("name"):
+ continue
+ # lastModifiedAscending gives the listing a stable order to page through.
+ for page in iterate_header_token(
+ config.path.replace("{project}", quote(project_row["name"])), {"queryOrder": "lastModifiedAscending"}
+ ):
+ yield [_with_project_ref(item, project_row) for item in page]
+ return
+
+ if endpoint == "build_timeline_records":
+ for project in project_names():
+ for build_page in builds_for(project):
+ for build in build_page:
+ if build.get("id") is None:
+ continue
+ path = config.path.replace("{project}", quote(project)).replace(
+ "{buildId}", quote(str(build["id"]))
+ )
+ response = fetch(path, {})
+ # A build that never ran has no timeline; Azure DevOps answers 204
+ # with an empty body rather than an empty object.
+ timeline = {} if response.status_code == 204 else response.json()
+ rows = [
+ _flatten_timeline_record(record, project, build, timeline.get("id"))
+ for record in (timeline.get("records") or [])
+ ]
+ if rows:
+ yield rows
+ return
+
+ if endpoint in ("releases", "release_deployments"):
+ for project_row in projects():
+ if not project_row.get("name"):
+ continue
+ for page in iterate_header_token(
+ config.path.replace("{project}", quote(project_row["name"])),
+ {"queryOrder": "ascending"},
+ base_url=config.base_url,
+ ):
+ yield [_with_project_ref(item, project_row) for item in page]
+ return
+
+ if endpoint == "test_runs":
+ # Both window bounds are mandatory on the filtered query and may span at most
+ # 7 days, so an incremental sync walks windows from the watermark to now. Full
+ # refresh takes the unfiltered listing, which pages on $skip instead.
+ since = _parse_datetime(db_incremental_field_last_value) if incremental_value is not None else None
+ for project_row in projects():
+ if not project_row.get("name"):
+ continue
+ path = config.path.replace("{project}", quote(project_row["name"]))
+ if since is None:
+ for page in iterate_skip(path, {}, use_base_params=False):
+ yield [_with_project_ref(item, project_row) for item in page]
+ continue
+ for window in _last_updated_windows(since, datetime.now(UTC)):
+ for page in iterate_header_token(
+ path,
+ {
+ "minLastUpdatedDate": window.min_last_updated,
+ "maxLastUpdatedDate": window.max_last_updated,
+ },
+ use_base_params=False,
+ ):
+ yield [_with_project_ref(item, project_row) for item in page]
+ return
+
if endpoint == "pull_requests":
extra = {"searchCriteria.status": "all"}
if incremental_value is not None:
@@ -398,7 +526,7 @@ def get_rows(
if not project_row.get("id"):
continue
for page in teams_for(project_row):
- yield [_flatten_team(item, project_row) for item in page]
+ yield [_with_project_ref(item, project_row) for item in page]
return
if endpoint == "team_members":
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 995939427ef8..c939b4302595 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
@@ -190,4 +190,141 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"url": "API URL of the work item revision.",
},
},
+ "build_definitions": {
+ "description": "A build pipeline definition — the configuration a build run is produced from.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/build/definitions/list",
+ "columns": {
+ "id": "Identifier of the definition, unique within its project.",
+ "project_id": "Identifier of the project the definition belongs to.",
+ "project_name": "Name of the project the definition belongs to.",
+ "name": "Name of the definition.",
+ "path": "Folder path of the definition.",
+ "type": "Type of the definition (build or xaml).",
+ "queueStatus": "Whether builds can be queued against this definition (enabled, paused, disabled).",
+ "revision": "Revision number of the definition, incremented on each change.",
+ "createdDate": "Time at which this version of the definition was created.",
+ "authoredBy": "The identity that authored the definition.",
+ "queue": "The default agent pool queue for builds run against this definition.",
+ "uri": "URI of the definition.",
+ "url": "API URL of the definition.",
+ },
+ },
+ "build_timeline_records": {
+ "description": "One record in a build's timeline — a stage, phase, job or task, with its own timing and result.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/build/timeline/get",
+ "columns": {
+ "id": "Identifier of the timeline record.",
+ "build_id": "Identifier of the build the record belongs to.",
+ "timeline_id": "Identifier of the timeline the record was read from.",
+ "build_queue_time": "Time at which the build was queued.",
+ "build_finish_time": "Time at which the build finished.",
+ "project_name": "Name of the project the build belongs to.",
+ "parentId": "Identifier of the record's parent record.",
+ "type": "Type of the record (Stage, Phase, Job, Task, Checkpoint).",
+ "name": "Name of the record.",
+ "identifier": "String identifier that stays the same across attempts.",
+ "attempt": "Attempt number of the record.",
+ "state": "State of the record (pending, inProgress, completed).",
+ "result": "Result of a completed record (succeeded, failed, canceled, skipped, abandoned, succeededWithIssues).",
+ "resultCode": "Result code of the record.",
+ "startTime": "Time at which the record started.",
+ "finishTime": "Time at which the record finished.",
+ "percentComplete": "Completion percentage of the record.",
+ "errorCount": "Number of errors produced by the record.",
+ "warningCount": "Number of warnings produced by the record.",
+ "workerName": "Name of the agent that ran the record.",
+ "queueId": "Identifier of the queue the record ran on.",
+ "order": "Ordinal value of the record relative to its siblings.",
+ "task": "The task the record represents.",
+ "log": "Reference to the log the record produced.",
+ "issues": "Errors and warnings raised by the record.",
+ "lastModified": "Time at which the record was last modified.",
+ "url": "API URL of the timeline record.",
+ },
+ },
+ "releases": {
+ "description": "A classic release created from a release pipeline definition.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/release/releases/list",
+ "columns": {
+ "id": "Identifier of the release, unique within its project.",
+ "project_id": "Identifier of the project the release belongs to.",
+ "project_name": "Name of the project the release belongs to.",
+ "name": "Name of the release.",
+ "status": "Status of the release (draft, active, abandoned).",
+ "reason": "Reason the release was created (manual, continuousIntegration, schedule, pullRequest).",
+ "createdOn": "Time at which the release was created.",
+ "modifiedOn": "Time at which the release was last modified.",
+ "createdBy": "The identity that created the release.",
+ "modifiedBy": "The identity that last modified the release.",
+ "createdFor": "The identity the release was created for.",
+ "description": "Description of the release.",
+ "releaseDefinition": "The release pipeline definition the release was created from.",
+ "releaseDefinitionRevision": "Revision of the release definition used.",
+ "definitionSnapshotRevision": "Revision of the definition snapshot taken for the release.",
+ "keepForever": "Whether the release is excluded from retention policies.",
+ "tags": "Tags attached to the release.",
+ "poolName": "Name of the agent pool used.",
+ "logsContainerUrl": "URL of the release logs container.",
+ },
+ },
+ "release_deployments": {
+ "description": "One deployment of a release to an environment — the grain for deployment frequency and promotion history.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/release/deployments/list",
+ "columns": {
+ "id": "Identifier of the deployment, unique within its project.",
+ "project_id": "Identifier of the project the deployment belongs to.",
+ "project_name": "Name of the project the deployment belongs to.",
+ "release": "The release being deployed.",
+ "releaseDefinition": "The release pipeline definition the deployment belongs to.",
+ "releaseEnvironment": "The environment the release was deployed to.",
+ "definitionEnvironmentId": "Identifier of the environment in the release definition.",
+ "deploymentStatus": "Status of the deployment (notDeployed, inProgress, succeeded, partiallySucceeded, failed).",
+ "operationStatus": "Operation status of the deployment (queued, approved, rejected, phaseInProgress, canceled, and so on).",
+ "reason": "Reason the deployment was started (manual, automated, scheduled, redeployTrigger).",
+ "attempt": "Attempt number of the deployment.",
+ "queuedOn": "Time at which the deployment was queued.",
+ "startedOn": "Time at which the deployment started.",
+ "completedOn": "Time at which the deployment completed.",
+ "scheduledDeploymentTime": "Time the deployment is scheduled for.",
+ "lastModifiedOn": "Time at which the deployment was last modified.",
+ "lastModifiedBy": "The identity that last modified the deployment.",
+ "requestedBy": "The identity that requested the deployment.",
+ "requestedFor": "The identity the deployment was requested for.",
+ "preDeployApprovals": "Approvals recorded before the deployment ran.",
+ "postDeployApprovals": "Approvals recorded after the deployment ran.",
+ "conditions": "Conditions and gates associated with the deployment.",
+ },
+ },
+ "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",
+ "columns": {
+ "id": "Identifier of the test run.",
+ "project_id": "Identifier of the project the run belongs to.",
+ "project_name": "Name of the project the run belongs to.",
+ "name": "Name of the test run.",
+ "state": "State of the run (NotStarted, InProgress, Completed, Waiting, Aborted).",
+ "isAutomated": "Whether the run is automated.",
+ "totalTests": "Total number of tests in the run.",
+ "passedTests": "Number of passed tests in the run.",
+ "unanalyzedTests": "Number of failed tests in the run.",
+ "incompleteTests": "Number of incomplete tests in the run.",
+ "notApplicableTests": "Number of not applicable tests in the run.",
+ "runStatistics": "Test counts broken down by outcome.",
+ "startedDate": "Time at which the run started.",
+ "completedDate": "Time at which the run completed.",
+ "createdDate": "Time at which the run was created.",
+ "lastUpdatedDate": "Time at which the run was last updated.",
+ "build": "The build the run was published against.",
+ "buildConfiguration": "Build configuration details for the run.",
+ "release": "The release the run was published against.",
+ "pipelineReference": "The pipeline stage and job the run belongs to.",
+ "plan": "The test plan the run belongs to.",
+ "owner": "The identity that owns the run.",
+ "errorMessage": "Error message associated with the run.",
+ "tags": "Tags attached to the run.",
+ "webAccessUrl": "URL of the run in the Azure DevOps web UI.",
+ "url": "API URL of the test run.",
+ },
+ },
}
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 8b292aff9aee..f525bfd8d5c9 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
@@ -3,20 +3,26 @@ from typing import Literal, Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+AZURE_DEVOPS_BASE_URL = "https://dev.azure.com"
+# Release Management is the one area served from its own host.
+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: continuationToken via the x-ms-continuationtoken header
-# - pull_requests/commits/teams/team_members: $top/$skip offset paging
+# - projects/builds/build_definitions/releases/release_deployments: 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: single response per parent
+# - repositories/pull request threads/reviewers/build timelines: single response per parent
@dataclass(frozen=True)
class AzureDevOpsEndpointConfig:
name: str
- # Path template under https://dev.azure.com/{organization}. `{project}`,
- # `{repositoryId}`, `{pullRequestId}` and `{teamId}` are substituted during
- # the fan-out that reaches the endpoint.
+ # Path template under {base_url}/{organization}. `{project}`, `{repositoryId}`,
+ # `{pullRequestId}`, `{buildId}` and `{teamId}` 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"])
incremental_fields: list[IncrementalField] = field(default_factory=list)
# Query param that pushes the incremental cursor server-side.
@@ -51,6 +57,41 @@ AZURE_DEVOPS_ENDPOINTS: dict[str, AzureDevOpsEndpointConfig] = {
},
],
),
+ "build_definitions": AzureDevOpsEndpointConfig(
+ name="build_definitions",
+ path="/{project}/_apis/build/definitions",
+ # Definition IDs restart per project.
+ primary_keys=["project_id", "id"],
+ partition_key="createdDate",
+ # The listing filters on build times (builtAfter/notBuiltAfter), never on when
+ # the definition itself changed, so there is no cursor to sync incrementally on.
+ ),
+ "build_timeline_records": AzureDevOpsEndpointConfig(
+ name="build_timeline_records",
+ path="/{project}/_apis/build/builds/{buildId}/timeline",
+ # Record IDs are GUIDs; the build is carried so a row identifies the run it
+ # describes without joining.
+ primary_keys=["build_id", "id"],
+ # Queue time never moves, unlike the finish time the cursor tracks.
+ partition_key="build_queue_time",
+ # A timeline takes no filter of its own, so the watermark bounds the parent build
+ # listing instead. It tracks the build's finish time rather than its queue time,
+ # because a record changes until its build ends and again on every retry — see
+ # `builds_for` in azure_devops.py.
+ incremental_param="minTime",
+ # The fan-out visits projects one after another, so the stream as a whole is
+ # not ascending. `desc` makes the pipeline finalize the watermark only after a
+ # fully successful sync.
+ sort_mode="desc",
+ incremental_fields=[
+ {
+ "label": "build_finish_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "build_finish_time",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
"pull_requests": AzureDevOpsEndpointConfig(
name="pull_requests",
path="/{project}/_apis/git/pullrequests",
@@ -141,6 +182,57 @@ AZURE_DEVOPS_ENDPOINTS: dict[str, AzureDevOpsEndpointConfig] = {
},
],
),
+ "releases": AzureDevOpsEndpointConfig(
+ name="releases",
+ path="/{project}/_apis/release/releases",
+ base_url=AZURE_DEVOPS_RELEASE_BASE_URL,
+ # Release IDs restart per project.
+ primary_keys=["project_id", "id"],
+ partition_key="createdOn",
+ # A release keeps changing after it is created — its status, its modified time,
+ # its environments — and the listing only filters on creation time, so a cursor
+ # would stop re-reading rows that are still moving. Full refresh instead; the
+ # per-environment history lives in release_deployments, which does have a
+ # modified-time filter.
+ ),
+ "release_deployments": AzureDevOpsEndpointConfig(
+ name="release_deployments",
+ path="/{project}/_apis/release/deployments",
+ base_url=AZURE_DEVOPS_RELEASE_BASE_URL,
+ # Deployment IDs restart per project.
+ primary_keys=["project_id", "id"],
+ # A deployment's status changes as it promotes, so the queue time is the
+ # stable field and the modified time is the cursor.
+ partition_key="queuedOn",
+ incremental_param="minModifiedTime",
+ sort_mode="desc",
+ incremental_fields=[
+ {
+ "label": "lastModifiedOn",
+ "type": IncrementalFieldType.DateTime,
+ "field": "lastModifiedOn",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "test_runs": AzureDevOpsEndpointConfig(
+ name="test_runs",
+ path="/{project}/_apis/test/runs",
+ primary_keys=["project_id", "id"],
+ partition_key="createdDate",
+ # The cursor is pushed through minLastUpdatedDate/maxLastUpdatedDate, which the
+ # vendor caps at a 7-day span, so azure_devops.py walks windows rather than
+ # sending one filter param. Full refresh takes the unfiltered listing instead.
+ sort_mode="desc",
+ incremental_fields=[
+ {
+ "label": "lastUpdatedDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "lastUpdatedDate",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
}
ENDPOINTS = tuple(AZURE_DEVOPS_ENDPOINTS.keys())
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 2833b34be97e..a5ca20d14171 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
@@ -1,4 +1,4 @@
-from datetime import UTC, date, datetime
+from datetime import UTC, date, datetime, timedelta
from typing import Any
from urllib.parse import parse_qs, urlparse
@@ -15,10 +15,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.azure_devo
_UNREACHABLE_MESSAGE,
AZURE_DEVOPS_VERSION_7_2,
AZURE_DEVOPS_VERSION_LEGACY,
+ TEST_RUN_WINDOW,
AzureDevOpsAuthError,
AzureDevOpsResumeConfig,
_flatten_revision,
_format_datetime,
+ _last_updated_windows,
_validate_organization,
azure_devops_source,
get_rows,
@@ -27,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.azure_devo
)
from products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.settings import (
AZURE_DEVOPS_ENDPOINTS,
+ AZURE_DEVOPS_RELEASE_BASE_URL,
ENDPOINTS,
)
@@ -612,6 +615,280 @@ class TestFanOutEndpoints:
)
+class TestLastUpdatedWindows:
+ def test_splits_a_long_span_into_windows_no_wider_than_the_cap(self):
+ since = datetime(2024, 1, 1, tzinfo=UTC)
+ until = since + timedelta(days=20)
+
+ windows = list(_last_updated_windows(since, until))
+
+ assert len(windows) == 3
+ assert windows[0].min_last_updated == "2024-01-01T00:00:00Z"
+ assert windows[-1].max_last_updated == "2024-01-21T00:00:00Z"
+ # A gap between windows would drop every run updated inside it.
+ assert [window.max_last_updated for window in windows[:-1]] == [
+ window.min_last_updated for window in windows[1:]
+ ]
+ for window in windows:
+ assert (
+ datetime.fromisoformat(window.max_last_updated.replace("Z", "+00:00"))
+ - datetime.fromisoformat(window.min_last_updated.replace("Z", "+00:00"))
+ <= TEST_RUN_WINDOW
+ )
+
+ @pytest.mark.parametrize("offset_days", [0, -1])
+ def test_yields_nothing_when_the_watermark_is_not_behind(self, offset_days):
+ since = datetime(2024, 1, 10, tzinfo=UTC)
+ assert list(_last_updated_windows(since, since + timedelta(days=offset_days))) == []
+
+
+class TestBuildEndpoints:
+ 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_build_definitions_carry_the_project_reference(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": 7, "name": "core-ci", "createdDate": "2024-01-02T03:04:05Z"}]}),
+ ]
+
+ batches = list(
+ get_rows("myorg", "pat", "build_definitions", 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["id"], row["project_id"], row["project_name"]) == (7, "proj-guid", "Alpha")
+ parsed = urlparse(mock_session.return_value.get.call_args_list[1].args[0])
+ assert parsed.path == "/myorg/Alpha/_apis/build/definitions"
+ assert parse_qs(parsed.query)["queryOrder"] == ["lastModifiedAscending"]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_build_timeline_records_carry_the_build_they_describe(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response(
+ {"value": [{"id": 41, "queueTime": "2024-01-02T03:04:05Z", "finishTime": "2024-01-02T03:20:00Z"}]}
+ ),
+ _response({"id": "timeline-1", "records": [{"id": "rec-1", "type": "Job", "result": "failed"}]}),
+ ]
+
+ batches = list(
+ get_rows(
+ "myorg", "pat", "build_timeline_records", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2
+ )
+ )
+
+ row = batches[0][0]
+ # build_id is half the composite primary key; the queue time partitions and the
+ # finish time is the watermark, and only the parent build carries either.
+ assert (row["id"], row["build_id"], row["timeline_id"]) == ("rec-1", 41, "timeline-1")
+ assert row["build_queue_time"] == "2024-01-02T03:04:05Z"
+ assert row["build_finish_time"] == "2024-01-02T03:20:00Z"
+ assert row["project_name"] == "Alpha"
+ assert urlparse(mock_session.return_value.get.call_args_list[2].args[0]).path == (
+ "/myorg/Alpha/_apis/build/builds/41/timeline"
+ )
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_build_timeline_records_skip_a_build_with_no_timeline(self, mock_session):
+ # Azure DevOps answers 204 with an empty body for a build that never ran;
+ # parsing that as JSON would fail the whole sync.
+ empty_timeline = mock.MagicMock()
+ empty_timeline.status_code = 204
+ empty_timeline.ok = True
+ empty_timeline.headers = {}
+ empty_timeline.json.side_effect = AssertionError("must not parse an empty 204 body")
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": 41, "queueTime": "2024-01-02T03:04:05Z"}]}),
+ empty_timeline,
+ ]
+
+ batches = list(
+ get_rows(
+ "myorg", "pat", "build_timeline_records", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2
+ )
+ )
+
+ assert batches == []
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_build_timeline_incremental_bounds_the_parent_build_listing(self, mock_session):
+ # The timeline endpoint takes no filter of its own, so the watermark has to reach
+ # the builds listing — otherwise every sync re-fetches every build's timeline.
+ # minTime filters on whichever time queryOrder names, so ordering by finish time
+ # is what keeps a still-running build out until it ends.
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": []}),
+ ]
+
+ list(
+ get_rows(
+ "myorg",
+ "pat",
+ "build_timeline_records",
+ mock.MagicMock(),
+ _make_manager(),
+ AZURE_DEVOPS_VERSION_7_2,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
+ )
+ )
+
+ builds_query = parse_qs(urlparse(mock_session.return_value.get.call_args_list[1].args[0]).query)
+ assert builds_query["minTime"] == ["2024-01-02T00:00:00Z"]
+ assert builds_query["queryOrder"] == ["finishTimeAscending"]
+
+
+class TestReleaseEndpoints:
+ PROJECTS = {"value": [{"id": "proj-guid", "name": "Alpha"}]}
+
+ @pytest.mark.parametrize(
+ "endpoint, path",
+ [
+ ("releases", "/myorg/Alpha/_apis/release/releases"),
+ ("release_deployments", "/myorg/Alpha/_apis/release/deployments"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_release_endpoints_are_read_from_the_release_host(self, mock_session, endpoint, path):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": 5, "name": "Release-5"}]}),
+ ]
+
+ batches = list(
+ get_rows(
+ "myorg",
+ "pat",
+ endpoint,
+ mock.MagicMock(),
+ _make_manager(),
+ AZURE_DEVOPS_VERSION_7_2,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
+ )
+ )
+
+ row = batches[0][0]
+ assert (row["id"], row["project_id"], row["project_name"]) == (5, "proj-guid", "Alpha")
+ # Release Management is served from its own host; dev.azure.com 404s these routes.
+ projects_url, release_url = (call.args[0] for call in mock_session.return_value.get.call_args_list)
+ assert projects_url.startswith("https://dev.azure.com/")
+ assert release_url.startswith(f"{AZURE_DEVOPS_RELEASE_BASE_URL}/")
+ parsed = urlparse(release_url)
+ assert parsed.path == path
+ assert parse_qs(parsed.query)["queryOrder"] == ["ascending"]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_deployments_track_the_modified_time_and_releases_track_nothing(self, mock_session):
+ # A deployment's status moves as it promotes, and the listing filters on the
+ # modified time. The releases listing has no such filter, so a cursor there would
+ # freeze rows that are still changing — it stays full refresh.
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": []}),
+ _response(self.PROJECTS),
+ _response({"value": []}),
+ ]
+
+ def sync(endpoint: str) -> dict[str, list[str]]:
+ list(
+ get_rows(
+ "myorg",
+ "pat",
+ endpoint,
+ mock.MagicMock(),
+ _make_manager(),
+ AZURE_DEVOPS_VERSION_7_2,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
+ )
+ )
+ return parse_qs(urlparse(mock_session.return_value.get.call_args_list[-1].args[0]).query)
+
+ assert sync("release_deployments")["minModifiedTime"] == ["2024-01-02T00:00:00Z"]
+ assert "minCreatedTime" not in sync("releases")
+
+
+class TestTestRunEndpoint:
+ 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_full_refresh_walks_the_unfiltered_listing(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": 3, "totalTests": 10, "passedTests": 9}]}),
+ _response({"value": []}),
+ ]
+
+ batches = list(
+ get_rows(
+ "myorg",
+ "pat",
+ "test_runs",
+ mock.MagicMock(),
+ _make_manager(),
+ AZURE_DEVOPS_VERSION_7_2,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
+ )
+ )
+
+ assert batches[0][0]["project_id"] == "proj-guid"
+ query = parse_qs(urlparse(mock_session.return_value.get.call_args_list[1].args[0]).query)
+ assert query["$skip"] == ["0"]
+ assert "minLastUpdatedDate" not in query
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_incremental_sends_both_window_bounds(self, mock_session):
+ # Both bounds are mandatory on the filtered query and the span may not exceed
+ # the cap, so sending minLastUpdatedDate alone is rejected.
+ since = datetime.now(UTC) - timedelta(days=2)
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": 3}]}),
+ ]
+
+ list(
+ get_rows(
+ "myorg",
+ "pat",
+ "test_runs",
+ mock.MagicMock(),
+ _make_manager(),
+ AZURE_DEVOPS_VERSION_7_2,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=since,
+ )
+ )
+
+ query = parse_qs(urlparse(mock_session.return_value.get.call_args_list[1].args[0]).query)
+ assert query["minLastUpdatedDate"] == [_format_datetime(since)]
+ window_start = datetime.fromisoformat(query["minLastUpdatedDate"][0].replace("Z", "+00:00"))
+ window_end = datetime.fromisoformat(query["maxLastUpdatedDate"][0].replace("Z", "+00:00"))
+ assert window_end - window_start <= TEST_RUN_WINDOW
+ assert "$skip" not in query
+
+
class TestAzureDevOpsSourceResponse:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
def test_response_metadata_per_endpoint(self, endpoint):
@@ -645,6 +922,10 @@ class TestAzureDevOpsSourceResponse:
"changed_date",
"committer_date",
"publishedDate",
+ "createdDate",
+ "createdOn",
+ "queuedOn",
+ "build_queue_time",
}