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): sync azure devops commits, pr reviews and teams (#99673)

Tom Owers0262623687c7
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 b01a6b57ed79..239a70360ecd 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
@@ -660,14 +660,15 @@ Note: The wiki.awin.com URLs in the source config are dead - they now 302 to the
## AzureDevOps — **thin**
-Today (5): `builds`, `projects`, `pull_requests`, `repositories`, `work_item_revisions`
+Today (11): `builds`, `commits`, `projects`, `pull_request_reviewers`, `pull_request_thread_comments`, `pull_request_threads`, `pull_requests`, `repositories`, `team_members`, `teams`, `work_item_revisions`
Diffed against: <https://github.com/MicrosoftDocs/vsts-rest-api-specs/tree/master/specification>
-- [ ] `git Commits (GET /{project}/_apis/git/repositories/{repositoryId}/commits)` — commit history is the base fact table for any DORA or engineering-velocity analysis (high)
-- [ ] `git Pull Request Threads + Thread Comments` — review discussion and timestamps - required for review latency and cycle time on the PRs we already sync (high)
-- [ ] `git Pull Request Reviewers (and Pull Request Iteration Statuses)` — approval votes per reviewer; the membership table that turns pull_requests into review analytics (high)
-- [ ] `core Teams (GET /_apis/teams, /projects/{projectId}/teams) and Team Members` — lookup resolving team ownership for projects, work items and boards (high)
+- [x] `git Commits (GET /{project}/_apis/git/repositories/{repositoryId}/commits)` — commit history is the base fact table for any DORA or engineering-velocity analysis (high)
+- [x] `git Pull Request Threads + Thread Comments` — review discussion and timestamps - required for review latency and cycle time on the PRs we already sync (high)
+- [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)
@@ -677,7 +678,7 @@ Diffed against: <https://github.com/MicrosoftDocs/vsts-rest-api-specs/tree/maste
- [ ] `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); five tables is a small fraction. 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. 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 6fa527b9a187..86cc4035b243 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
@@ -53,6 +53,15 @@ class AzureDevOpsAuthError(Exception):
pass
[email protected](frozen=True)
+class PullRequestRef:
+ """One pull request located well enough to reach its child endpoints."""
+
+ project: str
+ repository_id: str
+ pull_request_id: int
+
+
@dataclasses.dataclass
class AzureDevOpsResumeConfig:
# Only the org-level work item revisions stream persists resume state —
@@ -95,6 +104,56 @@ def _flatten_revision(item: dict[str, Any]) -> dict[str, Any]:
return item
+def _flatten_commit(item: dict[str, Any], project: str, repository: dict[str, Any]) -> dict[str, Any]:
+ # The committer date is nested under `committer`; the pipeline needs it at the
+ # row root to partition and to track the incremental watermark.
+ return {
+ **item,
+ "project_name": project,
+ "repository_id": repository.get("id"),
+ "repository_name": repository.get("name"),
+ "committer_date": (item.get("committer") or {}).get("date"),
+ }
+
+
+def _with_pull_request_ref(item: dict[str, Any], ref: PullRequestRef) -> dict[str, Any]:
+ return {
+ **item,
+ "project_name": ref.project,
+ "repository_id": ref.repository_id,
+ "pull_request_id": ref.pull_request_id,
+ }
+
+
+def _flatten_thread_comments(thread: dict[str, Any], ref: PullRequestRef) -> list[dict[str, Any]]:
+ return [
+ {
+ **comment,
+ "project_name": ref.project,
+ "repository_id": ref.repository_id,
+ "pull_request_id": ref.pull_request_id,
+ "thread_id": thread.get("id"),
+ }
+ for comment in (thread.get("comments") or [])
+ ]
+
+
+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.
+ return {**item, "project_id": project.get("id"), "project_name": project.get("name")}
+
+
+def _flatten_team_member(item: dict[str, Any], project: dict[str, Any], team: dict[str, Any]) -> dict[str, Any]:
+ return {
+ **item,
+ "project_id": project.get("id"),
+ "team_id": team.get("id"),
+ "team_name": team.get("name"),
+ "identity_id": (item.get("identity") or {}).get("id"),
+ }
+
+
# 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."
@@ -221,25 +280,56 @@ def get_rows(
if not token or not items:
return
- def iterate_skip(path: str, extra: dict[str, Any]) -> Iterator[list[dict[str, Any]]]:
+ def iterate_skip(path: str, extra: dict[str, Any], use_base_params: bool = True) -> Iterator[list[dict[str, Any]]]:
skip = 0
while True:
- params = {**base_params(), **extra, "$top": PAGE_SIZE, "$skip": skip}
+ params = {**(base_params() if use_base_params else {}), **extra, "$top": PAGE_SIZE, "$skip": skip}
response = fetch(path, params)
items = response.json().get("value", []) or []
- if items:
- yield items
- if len(items) < PAGE_SIZE:
+ if not items:
return
- skip += PAGE_SIZE
+ yield items
+ # Advance by what the server returned rather than by $top: several
+ # endpoints cap the page size below what we ask for, and treating a
+ # short page as the last one would silently truncate the table.
+ skip += len(items)
- def project_names() -> list[str]:
+ def projects() -> list[dict[str, Any]]:
# Project enumeration is independent of the data endpoint being synced,
# so it must not carry that endpoint's incremental filter.
- names: list[str] = []
+ items: list[dict[str, Any]] = []
for page in iterate_header_token("/_apis/projects", {}, use_base_params=False):
- names.extend(item["name"] for item in page if item.get("name"))
- return names
+ items.extend(page)
+ return items
+
+ def project_names() -> list[str]:
+ return [item["name"] for item in projects() if item.get("name")]
+
+ def repositories_for(project: str) -> list[dict[str, Any]]:
+ path = AZURE_DEVOPS_ENDPOINTS["repositories"].path.replace("{project}", quote(project))
+ return fetch(path, {}).json().get("value", []) or []
+
+ def teams_for(project: dict[str, Any]) -> Iterator[list[dict[str, Any]]]:
+ path = AZURE_DEVOPS_ENDPOINTS["teams"].path.replace("{project}", quote(str(project["id"])))
+ yield from iterate_skip(path, {}, use_base_params=False)
+
+ def pull_request_refs() -> Iterator[PullRequestRef]:
+ pr_path = AZURE_DEVOPS_ENDPOINTS["pull_requests"].path
+ for project in project_names():
+ path = pr_path.replace("{project}", quote(project))
+ for page in iterate_skip(path, {"searchCriteria.status": "all"}, use_base_params=False):
+ for pull_request in page:
+ repository_id = (pull_request.get("repository") or {}).get("id")
+ pull_request_id = pull_request.get("pullRequestId")
+ if repository_id and pull_request_id is not None:
+ yield PullRequestRef(project, repository_id, pull_request_id)
+
+ def pull_request_child_path(ref: PullRequestRef) -> str:
+ return (
+ config.path.replace("{project}", quote(ref.project))
+ .replace("{repositoryId}", quote(str(ref.repository_id)))
+ .replace("{pullRequestId}", quote(str(ref.pull_request_id)))
+ )
if endpoint == "projects":
yield from iterate_header_token(config.path, {})
@@ -269,6 +359,63 @@ def get_rows(
yield from iterate_skip(config.path.replace("{project}", quote(project)), extra)
return
+ if endpoint == "commits":
+ for project in project_names():
+ for repository in repositories_for(project):
+ if repository.get("isDisabled") or not repository.get("id"):
+ continue
+ path = config.path.replace("{project}", quote(project)).replace(
+ "{repositoryId}", quote(str(repository["id"]))
+ )
+ # Oldest-first keeps each repository's pages aligned with the
+ # fromDate filter; the stream is still declared `desc` because the
+ # fan-out interleaves repositories.
+ for page in iterate_skip(path, {"searchCriteria.showOldestCommitsFirst": "true"}):
+ yield [_flatten_commit(item, project, repository) for item in page]
+ return
+
+ if endpoint in ("pull_request_threads", "pull_request_thread_comments"):
+ want_comments = endpoint == "pull_request_thread_comments"
+ for ref in pull_request_refs():
+ threads = fetch(pull_request_child_path(ref), {}).json().get("value", []) or []
+ if want_comments:
+ rows = [row for thread in threads for row in _flatten_thread_comments(thread, ref)]
+ else:
+ rows = [_with_pull_request_ref(thread, ref) for thread in threads]
+ if rows:
+ yield rows
+ return
+
+ if endpoint == "pull_request_reviewers":
+ 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]
+ return
+
+ if endpoint == "teams":
+ for project_row in projects():
+ if not project_row.get("id"):
+ continue
+ for page in teams_for(project_row):
+ yield [_flatten_team(item, project_row) for item in page]
+ return
+
+ if endpoint == "team_members":
+ 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"]))
+ )
+ for page in iterate_skip(path, {}, use_base_params=False):
+ yield [_flatten_team_member(item, project_row, team) for item in page]
+ 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 06518d8f3cd3..995939427ef8 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
@@ -77,6 +77,108 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"repository": "The repository the pull request belongs to.",
},
},
+ "commits": {
+ "description": "A Git commit reachable from a repository in an Azure DevOps project.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/git/commits/get-commits",
+ "columns": {
+ "commitId": "ID (SHA-1) of the commit.",
+ "comment": "Comment or message of the commit.",
+ "commentTruncated": "Whether the comment is truncated from the full commit message.",
+ "author": "Author of the commit, with name, email and authored date.",
+ "committer": "Committer of the commit, with name, email and commit date.",
+ "committer_date": "Time at which the commit was committed, lifted from the committer object.",
+ "parents": "Commit IDs of this commit's parents.",
+ "changeCounts": "Counts of the types of changes (edits, deletes, adds) in the commit.",
+ "remoteUrl": "URL of the commit in the Azure DevOps web UI.",
+ "url": "API URL of the commit.",
+ "repository_id": "Identifier of the repository the commit was read from.",
+ "repository_name": "Name of the repository the commit was read from.",
+ "project_name": "Name of the project the repository belongs to.",
+ },
+ },
+ "pull_request_threads": {
+ "description": "A comment thread on a pull request, covering both reviewer discussion and the system events Azure DevOps records as threads (votes, reviewer changes, merge attempts).",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-request-threads/list",
+ "columns": {
+ "id": "The comment thread ID. Unique within its pull request.",
+ "status": "Status of the thread (unknown, active, fixed, wontFix, closed, byDesign, pending).",
+ "publishedDate": "Time at which the thread was published.",
+ "lastUpdatedDate": "Time at which the thread was last updated.",
+ "isDeleted": "Whether the thread is deleted, which happens when all its comments are deleted.",
+ "comments": "The comments in the thread. Also synced as their own table.",
+ "threadContext": "File path and line positions the thread was left on, for threads on code.",
+ "pullRequestThreadContext": "Which diff iterations were being viewed when the thread was created.",
+ "properties": "Key-value properties Azure DevOps attaches to the thread, including the thread type for system threads.",
+ "identities": "Identities referenced by the thread.",
+ "repository_id": "Identifier of the repository the pull request targets.",
+ "pull_request_id": "Identifier of the pull request the thread belongs to.",
+ "project_name": "Name of the project the pull request belongs to.",
+ },
+ },
+ "pull_request_thread_comments": {
+ "description": "A single comment inside a pull request comment thread.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-request-threads/list",
+ "columns": {
+ "id": "The comment ID. IDs start at 1 and are unique within a pull request.",
+ "parentCommentId": "ID of the comment this one replies to.",
+ "author": "The identity that wrote the comment.",
+ "content": "The comment content.",
+ "commentType": "Type of the comment at creation time (unknown, text, codeChange, system).",
+ "publishedDate": "Time at which the comment was first published.",
+ "lastUpdatedDate": "Time at which the comment was last updated.",
+ "lastContentUpdatedDate": "Time at which the comment content was last edited.",
+ "isDeleted": "Whether the comment was soft-deleted.",
+ "usersLiked": "Identities that liked the comment.",
+ "thread_id": "Identifier of the thread the comment belongs to.",
+ "repository_id": "Identifier of the repository the pull request targets.",
+ "pull_request_id": "Identifier of the pull request the comment belongs to.",
+ "project_name": "Name of the project the pull request belongs to.",
+ },
+ },
+ "pull_request_reviewers": {
+ "description": "A reviewer on a pull request, with their approval vote.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-request-reviewers/list",
+ "columns": {
+ "id": "Identifier of the reviewer identity.",
+ "displayName": "Display name of the reviewer.",
+ "uniqueName": "Unique name of the reviewer, usually an email address.",
+ "vote": "The reviewer's vote: 10 approved, 5 approved with suggestions, 0 no vote, -5 waiting for author, -10 rejected.",
+ "isRequired": "Whether branch policy requires this reviewer on the pull request.",
+ "isFlagged": "Whether the reviewer is flagged for attention on the pull request.",
+ "hasDeclined": "Whether the reviewer declined to review the pull request.",
+ "votedFor": "Votes rolled up from groups or teams this reviewer contributed to.",
+ "reviewerUrl": "API URL of this reviewer on the pull request.",
+ "url": "API URL of the reviewer identity.",
+ "repository_id": "Identifier of the repository the pull request targets.",
+ "pull_request_id": "Identifier of the pull request being reviewed.",
+ "project_name": "Name of the project the pull request belongs to.",
+ },
+ },
+ "teams": {
+ "description": "A team in an Azure DevOps project.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/core/teams/get-teams",
+ "columns": {
+ "id": "Team identifier. Unique across the organization.",
+ "name": "Name of the team.",
+ "description": "Description of the team.",
+ "url": "API URL of the team.",
+ "identityUrl": "API URL of the identity backing the team.",
+ "project_id": "Identifier of the project the team belongs to.",
+ "project_name": "Name of the project the team belongs to.",
+ },
+ },
+ "team_members": {
+ "description": "Membership of a team, one row per member.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/core/teams/get-team-members-with-extended-properties",
+ "columns": {
+ "identity": "The member's identity, with display name and unique name.",
+ "identity_id": "Identifier of the member identity, lifted from the identity object.",
+ "isTeamAdmin": "Whether the member administers the team.",
+ "team_id": "Identifier of the team.",
+ "team_name": "Name of the team.",
+ "project_id": "Identifier of the project the team belongs to.",
+ },
+ },
"work_item_revisions": {
"description": "A historical revision of a work item, from the reporting (append-only) feed.",
"docs_url": "https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/reporting-work-item-revisions/read-reporting-revisions-get",
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 1cea16943f68..8b292aff9aee 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
@@ -7,14 +7,15 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# 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: $top/$skip offset paging
+# - pull_requests/commits/teams/team_members: $top/$skip offset paging
# - work_item_revisions: body continuationToken + isLastBatch (reporting endpoint)
-# - repositories: single per-project response
-@dataclass
+# - repositories/pull request threads/reviewers: single response per parent
+@dataclass(frozen=True)
class AzureDevOpsEndpointConfig:
name: str
- # Path template under https://dev.azure.com/{organization}; `{project}` is
- # substituted during the per-project fan-out.
+ # Path template under https://dev.azure.com/{organization}. `{project}`,
+ # `{repositoryId}`, `{pullRequestId}` and `{teamId}` are substituted during
+ # the fan-out that reaches the endpoint.
path: str
primary_keys: list[str] = field(default_factory=lambda: ["id"])
incremental_fields: list[IncrementalField] = field(default_factory=list)
@@ -68,6 +69,62 @@ AZURE_DEVOPS_ENDPOINTS: dict[str, AzureDevOpsEndpointConfig] = {
},
],
),
+ "commits": AzureDevOpsEndpointConfig(
+ name="commits",
+ path="/{project}/_apis/git/repositories/{repositoryId}/commits",
+ # A commit SHA is unique within a repository, but the same commit can be
+ # reachable from several repositories in one organization (forks, imports).
+ primary_keys=["repository_id", "commitId"],
+ partition_key="committer_date",
+ incremental_param="searchCriteria.fromDate",
+ # Pages arrive oldest-first within a repository, but the fan-out visits
+ # repositories 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, so a partial run can't advance it past a repository it
+ # never reached.
+ sort_mode="desc",
+ incremental_fields=[
+ {
+ "label": "committer_date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "committer_date",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "pull_request_threads": AzureDevOpsEndpointConfig(
+ name="pull_request_threads",
+ path="/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/threads",
+ # Thread IDs restart per pull request.
+ primary_keys=["repository_id", "pull_request_id", "id"],
+ partition_key="publishedDate",
+ ),
+ "pull_request_thread_comments": AzureDevOpsEndpointConfig(
+ name="pull_request_thread_comments",
+ # Comments arrive nested in the threads response; they get their own table
+ # rather than a second request.
+ path="/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/threads",
+ primary_keys=["repository_id", "pull_request_id", "thread_id", "id"],
+ partition_key="publishedDate",
+ ),
+ "pull_request_reviewers": AzureDevOpsEndpointConfig(
+ name="pull_request_reviewers",
+ path="/{project}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}/reviewers",
+ 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
+ # per project through the generally available Core endpoint.
+ path="/_apis/projects/{project}/teams",
+ ),
+ "team_members": AzureDevOpsEndpointConfig(
+ name="team_members",
+ path="/_apis/projects/{project}/teams/{teamId}/members",
+ # Members carry no identifier of their own; the identity ID is lifted to the
+ # row root during the fan-out.
+ primary_keys=["team_id", "identity_id"],
+ ),
"work_item_revisions": AzureDevOpsEndpointConfig(
name="work_item_revisions",
path="/_apis/wit/reporting/workitemrevisions",
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 01f7939542c3..2833b34be97e 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
@@ -237,6 +237,7 @@ class TestGetRows:
_response({"value": [{"id": "p1", "name": "Alpha"}]}),
_response(full_page),
_response({"value": [{"pullRequestId": 999}]}),
+ _response({"value": []}),
]
manager = _make_manager()
@@ -248,6 +249,29 @@ class TestGetRows:
assert parse_qs(urlparse(urls[0]).query)["$skip"] == ["0"]
assert parse_qs(urlparse(urls[1]).query)["$skip"] == ["200"]
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_skip_pagination_walks_on_after_a_short_page(self, mock_session):
+ # Several Azure DevOps endpoints cap the page size below the requested $top.
+ # Stopping at the first short page would silently truncate the table.
+ mock_session.return_value.get.side_effect = [
+ _response({"value": [{"id": "p1", "name": "Alpha"}]}),
+ _response({"value": [{"pullRequestId": i} for i in range(100)]}),
+ _response({"value": [{"pullRequestId": 100}]}),
+ _response({"value": []}),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("myorg", "pat", "pull_requests", mock.MagicMock(), manager, AZURE_DEVOPS_VERSION_7_2))
+
+ assert [len(batch) for batch in batches] == [100, 1]
+ skips = [
+ parse_qs(urlparse(call.args[0]).query)["$skip"][0]
+ for call in mock_session.return_value.get.call_args_list[1:]
+ ]
+ assert skips == ["0", "100", "101"]
+
@mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
)
@@ -354,6 +378,240 @@ class TestGetRows:
list(get_rows("myorg", "pat", "projects", mock.MagicMock(), manager, AZURE_DEVOPS_VERSION_7_2))
+class TestFanOutEndpoints:
+ 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_commits_fan_out_skips_disabled_repositories_and_flattens_the_committer_date(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": "repo-1", "name": "core"}, {"id": "repo-2", "isDisabled": True}]}),
+ _response({"value": [{"commitId": "abc", "committer": {"date": "2024-01-02T03:04:05Z"}}]}),
+ _response({"value": []}),
+ ]
+
+ batches = list(get_rows("myorg", "pat", "commits", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2))
+
+ row = batches[0][0]
+ assert row["committer_date"] == "2024-01-02T03:04:05Z"
+ assert (row["repository_id"], row["repository_name"], row["project_name"]) == ("repo-1", "core", "Alpha")
+ commit_url = mock_session.return_value.get.call_args_list[2].args[0]
+ parsed = urlparse(commit_url)
+ # The disabled repository must never be requested — commits on it 404.
+ assert parsed.path == "/myorg/Alpha/_apis/git/repositories/repo-1/commits"
+ assert parse_qs(parsed.query)["searchCriteria.showOldestCommitsFirst"] == ["true"]
+ assert len(mock_session.return_value.get.call_args_list) == 4
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_commits_incremental_sends_from_date(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": "repo-1", "name": "core"}]}),
+ _response({"value": []}),
+ ]
+
+ list(
+ get_rows(
+ "myorg",
+ "pat",
+ "commits",
+ 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),
+ )
+ )
+
+ commit_query = parse_qs(urlparse(mock_session.return_value.get.call_args_list[2].args[0]).query)
+ assert commit_query["searchCriteria.fromDate"] == ["2024-01-02T00:00:00Z"]
+ # The repository listing is a fan-out parent, not the endpoint being synced.
+ repo_query = parse_qs(urlparse(mock_session.return_value.get.call_args_list[1].args[0]).query)
+ assert "searchCriteria.fromDate" not in repo_query
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_commits_full_refresh_omits_from_date(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": "repo-1", "name": "core"}]}),
+ _response({"value": []}),
+ ]
+
+ list(
+ get_rows(
+ "myorg",
+ "pat",
+ "commits",
+ 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),
+ )
+ )
+
+ commit_query = parse_qs(urlparse(mock_session.return_value.get.call_args_list[2].args[0]).query)
+ assert "searchCriteria.fromDate" not in commit_query
+
+ THREADS = {
+ "value": [
+ {
+ "id": 141,
+ "publishedDate": "2024-01-02T03:04:05Z",
+ "comments": [
+ {"id": 1, "content": "looks good"},
+ {"id": 2, "parentCommentId": 1, "content": "thanks"},
+ ],
+ }
+ ]
+ }
+
+ def _pull_request_parents(self, child_body: dict[str, Any]) -> list[mock.MagicMock]:
+ # The pull request walk is lazy: each PR's child endpoint is requested before
+ # the next page of pull requests is asked for.
+ return [
+ _response(self.PROJECTS),
+ _response({"value": [{"pullRequestId": 22, "repository": {"id": "repo-1"}}]}),
+ _response(child_body),
+ _response({"value": []}),
+ ]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_pull_request_threads_carry_their_parent_identifiers(self, mock_session):
+ mock_session.return_value.get.side_effect = self._pull_request_parents(self.THREADS)
+
+ batches = list(
+ get_rows(
+ "myorg", "pat", "pull_request_threads", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2
+ )
+ )
+
+ row = batches[0][0]
+ assert (row["id"], row["repository_id"], row["pull_request_id"]) == (141, "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/threads"
+ )
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_pull_request_thread_comments_flatten_out_of_the_same_response(self, mock_session):
+ mock_session.return_value.get.side_effect = self._pull_request_parents(self.THREADS)
+
+ batches = list(
+ get_rows(
+ "myorg",
+ "pat",
+ "pull_request_thread_comments",
+ mock.MagicMock(),
+ _make_manager(),
+ AZURE_DEVOPS_VERSION_7_2,
+ )
+ )
+
+ rows = batches[0]
+ assert [row["id"] for row in rows] == [1, 2]
+ assert {row["thread_id"] for row in rows} == {141}
+ assert {(row["repository_id"], row["pull_request_id"]) for row in rows} == {("repo-1", 22)}
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_pull_request_reviewers_carry_their_parent_identifiers(self, mock_session):
+ mock_session.return_value.get.side_effect = self._pull_request_parents(
+ {"value": [{"id": "identity-1", "vote": 10}]}
+ )
+
+ batches = list(
+ get_rows(
+ "myorg", "pat", "pull_request_reviewers", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2
+ )
+ )
+
+ row = batches[0][0]
+ assert (row["id"], row["vote"], row["repository_id"], row["pull_request_id"]) == (
+ "identity-1",
+ 10,
+ "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/reviewers"
+ )
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_pull_request_children_skip_pull_requests_without_a_repository(self, mock_session):
+ # A PR row missing its repository can't address the child endpoint; requesting
+ # it anyway would build a path with a literal {repositoryId} placeholder.
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"pullRequestId": 22}, {"repository": {"id": "repo-1"}}]}),
+ _response({"value": []}),
+ ]
+
+ batches = list(
+ get_rows(
+ "myorg", "pat", "pull_request_reviewers", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2
+ )
+ )
+
+ assert batches == []
+ assert len(mock_session.return_value.get.call_args_list) == 3
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_teams_are_read_by_project_id_not_project_name(self, mock_session):
+ # The Core teams route takes a project ID; passing the display name 404s.
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": "team-1", "name": "QA"}]}),
+ _response({"value": []}),
+ ]
+
+ batches = list(get_rows("myorg", "pat", "teams", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2))
+
+ row = batches[0][0]
+ assert (row["id"], row["project_id"], row["project_name"]) == ("team-1", "proj-guid", "Alpha")
+ assert urlparse(mock_session.return_value.get.call_args_list[1].args[0]).path == (
+ "/myorg/_apis/projects/proj-guid/teams"
+ )
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session"
+ )
+ def test_team_members_lift_the_identity_id_to_the_row_root(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(self.PROJECTS),
+ _response({"value": [{"id": "team-1", "name": "QA"}]}),
+ _response({"value": [{"isTeamAdmin": True, "identity": {"id": "identity-1", "displayName": "Ada"}}]}),
+ _response({"value": []}),
+ _response({"value": []}),
+ ]
+
+ batches = list(
+ get_rows("myorg", "pat", "team_members", mock.MagicMock(), _make_manager(), AZURE_DEVOPS_VERSION_7_2)
+ )
+
+ row = batches[0][0]
+ # identity_id and team_id are the composite primary key, so both must be present.
+ assert (row["identity_id"], row["team_id"], row["team_name"]) == ("identity-1", "team-1", "QA")
+ assert row["project_id"] == "proj-guid"
+ assert urlparse(mock_session.return_value.get.call_args_list[2].args[0]).path == (
+ "/myorg/_apis/projects/proj-guid/teams/team-1/members"
+ )
+
+
class TestAzureDevOpsSourceResponse:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
def test_response_metadata_per_endpoint(self, endpoint):
@@ -381,7 +639,13 @@ class TestAzureDevOpsSourceResponse:
@pytest.mark.parametrize("config", list(AZURE_DEVOPS_ENDPOINTS.values()))
def test_partition_keys_are_stable_fields(self, config):
if config.partition_key:
- assert config.partition_key in {"queueTime", "creationDate", "changed_date"}
+ assert config.partition_key in {
+ "queueTime",
+ "creationDate",
+ "changed_date",
+ "committer_date",
+ "publishedDate",
+ }
class TestApiVersionDispatch: