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(aviator): sync branches, bot pull requests and user actions (#99678)

Tom Owers18d9eb3596f8
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 939c3ba3d886..322098ce2af0 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
@@ -623,14 +623,14 @@ Note: The live docs URL now 301s to docs.apilayer.com and lands in an auth-gated
## Aviator — gaps
-Today (5): `config_history`, `merge_queue_analytics`, `queue_stats`, `queued_pull_requests`, `repositories`
+Today (8): `bot_pull_requests`, `branches`, `config_history`, `merge_queue_analytics`, `queue_stats`, `queued_pull_requests`, `repositories`, `user_actions`
Diffed against: <https://docs.aviator.co/api/reference/json-api.md>
-- [ ] `GET /api/v1/branches` — base branches with pause/active status - the lookup that resolves the base_branch carried on queued PRs and queue stats (high)
-- [ ] `GET /api/v1/user_actions` — paginated action/audit history (actor, action, entity, target, timestamp) - the only transition history Aviator exposes (medium)
-- [ ] `GET /api/v1/bot_pull_request` — the batch/draft PR Aviator creates in parallel mode, linking queued PRs to the batch that actually merged them (medium)
-- [ ] `GET /api/v1/pull_request` — full per-PR merge state (status, blocked reason) for PRs not currently in the queued list (medium)
+- [x] `GET /api/v1/branches` — base branches with pause/active status - the lookup that resolves the base_branch carried on queued PRs and queue stats (high)
+- [x] `GET /api/v1/user_actions` — paginated action/audit history (actor, action, entity, target, timestamp) - the only transition history Aviator exposes (medium)
+- [x] `GET /api/v1/bot_pull_request` — the batch/draft PR Aviator creates in parallel mode, linking queued PRs to the batch that actually merged them (medium)
+- [ ] `GET /api/v1/pull_request` — full per-PR merge state (status, blocked reason) for PRs not currently in the queued list (medium) — **not listable.** It is a point lookup requiring `org`, `repo` and one of `branch`/`number`; the API exposes no way to enumerate PRs outside the queue, so the stated premise cannot be met. The PRs we can enumerate come from `GET /pull_request/queued`, which already returns the same per-PR fields, and its one extra field (`bot_pull_request`) is now covered by the `bot_pull_requests` table.
- [ ] `GET /api/releases/{project}/environments/{env}/deployments` — deployment history per environment from the Releases product - complements merge-queue data with what shipped (medium)
- [ ] `GET /api/v1/config` — current YAML config per repo; we sync config_history but not the current state it diffs against (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.posthog-doc.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.posthog-doc.mdx
index fdd3c419df8f..bb5d795b82a8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.posthog-doc.mdx
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.posthog-doc.mdx
@@ -25,9 +25,10 @@ import AlphaRelease from '../_snippets/alpha-release.mdx'
<AlphaRelease />
[Aviator](https://www.aviator.co/) is a developer productivity suite built around a merge queue for GitHub.
-This connector pulls your Aviator data — repositories, daily merge-queue analytics, currently queued pull
-requests, live queue depth, and merge-queue config history — into the PostHog Data warehouse so you can
-join it with your product and engineering data.
+This connector pulls your Aviator data — repositories, base branches, daily merge-queue analytics,
+currently queued pull requests, batch (bot) pull requests, live queue depth, merge-queue config history,
+and the account audit log — into the PostHog Data warehouse so you can join it with your product and
+engineering data.
## Prerequisites
@@ -50,6 +51,12 @@ and re-reads a short trailing window each run, because recent daily aggregates c
tables are current-state snapshots or small lists with no server-side timestamp filter, so they sync as
full refresh.
+Two tables are off by default because they do not apply to every account:
+
+- **Bot pull requests** only has data if a repository runs the merge queue in parallel mode. Aviator only
+ looks a batch up by pull request, so this table makes one request per queued pull request.
+- **User actions** is the account audit log, which needs an Aviator Enterprise plan.
+
## Configuration
<SourceParameters />
@@ -63,6 +70,7 @@ full refresh.
- **401 Unauthorized** — the API token is invalid or has been revoked. Create a new user access token in
your Aviator account settings and reconnect.
- **403 Forbidden** — the token is valid but does not have access to a repository's data. Check the
- token's repository access in Aviator and reconnect.
+ token's repository access in Aviator and reconnect. **User actions** also returns this on plans below
+ Enterprise — deselect the table if you do not have audit log access.
<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.py
index 76289d859ba4..953b8d3d4c5a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/aviator.py
@@ -22,6 +22,9 @@ AVIATOR_BASE_URL = "https://api.aviator.co/api/v1"
REPO_PAGE_SIZE = 10
# Bound the config-history paginator so a misbehaving API can't loop forever.
CONFIG_HISTORY_MAX_PAGES = 1000
+# GET /user_actions documents no page size and no total, so bound it the same way. The endpoint
+# returns newest-first, so a capped run keeps the most recent history rather than the oldest.
+USER_ACTIONS_MAX_PAGES = 1000
# Re-pull a trailing window of daily analytics each incremental run: recent days' aggregates can
# still be revised upstream. Merge dedupes the re-pulled days on the [repo, date] primary key.
ANALYTICS_LOOKBACK_DAYS = 7
@@ -79,12 +82,17 @@ def _fetch(
headers: dict[str, str],
logger: FilteringBoundLogger,
params: Optional[dict[str, Any]] = None,
+ json_body: Optional[dict[str, Any]] = None,
+ none_on_not_found: bool = False,
) -> Any:
- response = session.get(url, headers=headers, params=params, timeout=60)
+ response = session.get(url, headers=headers, params=params, json=json_body, timeout=60)
if response.status_code == 429 or response.status_code >= 500:
raise AviatorRetryableError(f"Aviator API error (retryable): status={response.status_code}, url={url}")
+ if none_on_not_found and response.status_code == 404:
+ return None
+
if not response.ok:
# Log only status and URL — never the response body. Aviator error bodies can echo
# request-specific data (config-history diffs, token-like values), which must not spill
@@ -122,6 +130,47 @@ def _iter_repositories(
page += 1
+def _iter_user_actions(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger
+) -> Iterator[dict[str, Any]]:
+ """Page through GET /user_actions yielding each audit entry, newest first."""
+ page = 1
+ while page <= USER_ACTIONS_MAX_PAGES:
+ data = _fetch(session, f"{AVIATOR_BASE_URL}/user_actions", headers, logger, params={"page": page})
+ items = data if isinstance(data, list) else []
+ if not items:
+ break
+ for item in items:
+ # `timestamp` leads the composite primary key and the endpoint exposes no id, so an
+ # entry without one cannot be identified at all — drop it.
+ timestamp = item.get("timestamp")
+ if not timestamp:
+ logger.warning("Aviator: skipping user action without a timestamp")
+ continue
+ yield {
+ "timestamp": timestamp,
+ "actor": item.get("actor"),
+ "action": item.get("action"),
+ "entity": item.get("entity"),
+ "target": item.get("target"),
+ }
+ page += 1
+ else:
+ logger.warning(f"Aviator user_actions hit the page cap ({USER_ACTIONS_MAX_PAGES})")
+
+
+def _iter_queued_pull_request_numbers(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger, org: str, name: str
+) -> Iterator[Any]:
+ """Yield the number of every pull request currently in a repository's merge queue."""
+ url = f"{AVIATOR_BASE_URL}{AVIATOR_ENDPOINTS['queued_pull_requests'].path}"
+ payload = _fetch(session, url, headers, logger, params={"org": org, "repo": name})
+ for pull_request in payload.get("pull_requests", []):
+ number = pull_request.get("number")
+ if number is not None:
+ yield number
+
+
def _parse_date(value: Any) -> date:
if isinstance(value, datetime):
return value.date()
@@ -211,6 +260,64 @@ def _extract_fan_out_rows(
}
return
+ if endpoint == "branches":
+ # The docs label these "query parameters", but the documented curl sends them as a JSON body
+ # on the GET — and the nested repository object cannot be expressed as flat query params, so
+ # the body is the only form matching the spec. `pattern` is optional; omit it to list them all.
+ payload = _fetch(session, url, headers, logger, json_body={"repository": {"org": org, "name": name}})
+ for branch in payload.get("branches", []):
+ # `pattern` is part of the (org, repo, pattern) primary key. A row missing it would merge
+ # under a null key, collapsing every patternless branch in the repo into one row — skip it.
+ pattern = branch.get("pattern")
+ if not pattern:
+ logger.warning(f"Aviator: skipping branch without a pattern for {org}/{name}")
+ continue
+ yield {
+ "org": org,
+ "repo": name,
+ "pattern": pattern,
+ "paused": branch.get("paused"),
+ "paused_message": branch.get("paused_message"),
+ }
+ return
+
+ if endpoint == "bot_pull_requests":
+ # GET /bot_pull_request is a per-PR lookup, so the queue is the only enumerable set of PR
+ # numbers to resolve batches from. Several queued PRs share one batch, so dedupe the results:
+ # merge only dedupes across syncs, and duplicate keys within one batch multi-match on merge.
+ seen_bot_pr_numbers: set[Any] = set()
+ for pull_request_number in _iter_queued_pull_request_numbers(session, headers, logger, org, name):
+ payload = _fetch(
+ session,
+ url,
+ headers,
+ logger,
+ params={"org": org, "repo": name, "number": pull_request_number},
+ # Aviator only creates bot PRs in parallel mode, so a repo on serial mode — or a PR
+ # not yet batched — legitimately has none.
+ none_on_not_found=True,
+ )
+ if not payload:
+ continue
+ bot_pr_number = payload.get("number")
+ if bot_pr_number is None or bot_pr_number in seen_bot_pr_numbers:
+ continue
+ seen_bot_pr_numbers.add(bot_pr_number)
+ yield {
+ "org": org,
+ "repo": name,
+ "number": bot_pr_number,
+ "github_url": payload.get("github_url"),
+ "target_branch": payload.get("target_branch"),
+ "head_commit_sha": payload.get("head_commit_sha"),
+ # `head_branch_oid` is documented as a legacy alias for head_commit_sha, so it is dropped.
+ "codemix_pre_batch_sha": payload.get("codemix_pre_batch_sha"),
+ "pull_request_numbers": [
+ pr.get("number") for pr in payload.get("pull_requests", []) if pr.get("number") is not None
+ ],
+ }
+ return
+
if endpoint == "config_history":
page = 1
while page <= CONFIG_HISTORY_MAX_PAGES:
@@ -243,14 +350,25 @@ def _extract_fan_out_rows(
raise ValueError(f"Unknown fan-out endpoint: {endpoint}")
-def _get_repository_rows(
+_TOP_LEVEL_ITERATORS: dict[str, Any] = {
+ "repositories": _iter_repositories,
+ "user_actions": _iter_user_actions,
+}
+
+
+def _get_top_level_rows(
session: requests.Session,
headers: dict[str, str],
logger: FilteringBoundLogger,
batcher: Batcher,
+ endpoint: str,
) -> Iterator[Any]:
- for repo in _iter_repositories(session, headers, logger):
- batcher.batch(repo)
+ iterator = _TOP_LEVEL_ITERATORS.get(endpoint)
+ if iterator is None:
+ raise ValueError(f"Unknown top-level endpoint: {endpoint}")
+
+ for row in iterator(session, headers, logger):
+ batcher.batch(row)
if batcher.should_yield():
yield batcher.get_table()
@@ -339,7 +457,7 @@ def get_rows(
db_incremental_field_last_value,
)
else:
- yield from _get_repository_rows(session, headers, logger, batcher)
+ yield from _get_top_level_rows(session, headers, logger, batcher, endpoint)
if batcher.should_yield(include_incomplete_chunk=True):
yield batcher.get_table()
@@ -371,7 +489,7 @@ def aviator_source(
# Fan-out runs persist the incremental watermark only at successful job end (desc mode): a
# partial run's max date says nothing about repos it never reached, so per-batch persistence
# could advance the watermark past rows a crashed run still owes.
- sort_mode="desc" if config.fan_out_over_repos else "asc",
+ sort_mode=config.sort_mode,
partition_count=1,
partition_size=1,
partition_mode="datetime" if config.partition_key else None,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/canonical_descriptions.py
index b2b28c33ba4e..9576252e4d4b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/canonical_descriptions.py
@@ -80,6 +80,42 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"waiting": "Number of PRs queued but not yet being processed.",
},
},
+ "branches": {
+ "description": "Base branches configured on each repository's merge queue, as glob patterns with their pause state.",
+ "docs_url": "https://docs.aviator.co/api/reference/json-api",
+ "columns": {
+ "org": "GitHub organization that owns the repository.",
+ "repo": "Repository name.",
+ "pattern": "Glob pattern matching the base branch, for example `master` or `release-*`.",
+ "paused": "Whether merging into branches matching this pattern is currently paused.",
+ "paused_message": "Custom message posted on the top pull request while the branch is paused.",
+ },
+ },
+ "bot_pull_requests": {
+ "description": "Batch (bot) pull requests Aviator creates in parallel mode, linking each batch to the queued pull requests it carries.",
+ "docs_url": "https://docs.aviator.co/api/reference/json-api",
+ "columns": {
+ "org": "GitHub organization that owns the repository.",
+ "repo": "Repository name.",
+ "number": "Pull request number of the bot PR itself.",
+ "github_url": "GitHub URL of the bot PR.",
+ "target_branch": "Branch the bot PR merges into.",
+ "head_commit_sha": "Commit SHA at the head of the bot PR's branch.",
+ "codemix_pre_batch_sha": "Commit SHA just before the validating pull requests joined the bot branch, so it includes dependent changes but not the validating ones.",
+ "pull_request_numbers": "JSON array of the numbers of the pull requests batched into this bot PR.",
+ },
+ },
+ "user_actions": {
+ "description": "Audit log of actions taken by users in the Aviator account. Requires an Aviator Enterprise plan.",
+ "docs_url": "https://docs.aviator.co/api/reference/json-api",
+ "columns": {
+ "timestamp": "ISO 8601 timestamp, with timezone, for when the action was performed.",
+ "actor": "Email address of the user who performed the action.",
+ "action": "Type of action the user performed.",
+ "entity": "Type of entity that changed, such as user, merge_queue, repository, account, billing, integrations or flexreview.",
+ "target": "Entity the action was performed on, or null when the action has no specific target.",
+ },
+ },
"config_history": {
"description": "History of merge-queue YAML config changes per repository, as diffs.",
"docs_url": "https://docs.aviator.co/api/reference/json-api",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/settings.py
index 7c8d56999c91..9f12a48e3dcc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/settings.py
@@ -1,10 +1,12 @@
-from dataclasses import dataclass, field
-from typing import Optional
+from dataclasses import field
+from typing import Literal, Optional
+
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@frozen
class AviatorEndpointConfig:
name: str
path: str
@@ -18,6 +20,10 @@ class AviatorEndpointConfig:
# When True the endpoint is called once per repository discovered via GET /repo, injecting
# the repo's org/name into the request. When False it is a single top-level request.
fan_out_over_repos: bool = False
+ # Order rows arrive in. Fan-out endpoints report "desc" so the incremental watermark persists
+ # only at successful job end — a partial run's max value says nothing about repos it never
+ # reached. Top-level endpoints declare whatever the API actually returns.
+ sort_mode: Literal["asc", "desc"] = "asc"
default_incremental_field: Optional[str] = None
# First-sync window (days) for date-windowed incremental endpoints, so the initial sync
# doesn't try to pull the entire history at once.
@@ -35,7 +41,8 @@ class AviatorEndpointConfig:
# list with no reliable server-side timestamp filter, so it ships as full refresh. GET /config/history
# documents optional `start`/`end` params, but we could not curl-verify that they actually filter
# server-side (no test credentials), so it stays full refresh conservatively — config changes are
-# low volume, so re-reading them each sync is cheap.
+# low volume, so re-reading them each sync is cheap. GET /user_actions carries a `timestamp` but only
+# filters on `entity`, `action` and `page`, so it is full refresh too.
AVIATOR_ENDPOINTS: dict[str, AviatorEndpointConfig] = {
"repositories": AviatorEndpointConfig(
name="repositories",
@@ -50,6 +57,7 @@ AVIATOR_ENDPOINTS: dict[str, AviatorEndpointConfig] = {
primary_keys=["repo", "date"],
partition_key="date",
fan_out_over_repos=True,
+ sort_mode="desc",
default_incremental_field="date",
# Merge-queue analytics are daily aggregates; a year of history is a reasonable first sync.
default_lookback_days=365,
@@ -69,6 +77,7 @@ AVIATOR_ENDPOINTS: dict[str, AviatorEndpointConfig] = {
primary_keys=["org", "repo", "number"],
partition_key="created_at",
fan_out_over_repos=True,
+ sort_mode="desc",
),
"queue_stats": AviatorEndpointConfig(
name="queue_stats",
@@ -76,6 +85,38 @@ AVIATOR_ENDPOINTS: dict[str, AviatorEndpointConfig] = {
# Live queue depth: a single current-state row per repository.
primary_keys=["org", "repo"],
fan_out_over_repos=True,
+ sort_mode="desc",
+ ),
+ "branches": AviatorEndpointConfig(
+ name="branches",
+ path="/branches",
+ # GET /branches returns one entry per base-branch glob configured on the repo; the pattern
+ # is unique within a repository, so (org, repo, pattern) is the key.
+ primary_keys=["org", "repo", "pattern"],
+ fan_out_over_repos=True,
+ sort_mode="desc",
+ ),
+ "bot_pull_requests": AviatorEndpointConfig(
+ name="bot_pull_requests",
+ path="/bot_pull_request",
+ # The batch PR's own number, unique within a repository.
+ primary_keys=["org", "repo", "number"],
+ fan_out_over_repos=True,
+ sort_mode="desc",
+ # Aviator only creates bot PRs in parallel mode, and the endpoint is a per-PR lookup, so the
+ # table costs one request per queued PR. Off by default: repos on serial mode sync nothing.
+ should_sync_default=False,
+ ),
+ "user_actions": AviatorEndpointConfig(
+ name="user_actions",
+ path="/user_actions",
+ # The audit log carries no id, so the whole record is the key.
+ primary_keys=["timestamp", "actor", "action", "entity", "target"],
+ partition_key="timestamp",
+ # The endpoint documents it returns actions newest-first.
+ sort_mode="desc",
+ # Audit logs are an Aviator Enterprise feature, so the endpoint is unavailable on other plans.
+ should_sync_default=False,
),
"config_history": AviatorEndpointConfig(
name="config_history",
@@ -84,6 +125,7 @@ AVIATOR_ENDPOINTS: dict[str, AviatorEndpointConfig] = {
primary_keys=["org", "repo", "applied_at"],
partition_key="applied_at",
fan_out_over_repos=True,
+ sort_mode="desc",
),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator.py
index 5a2c7f872a98..7478894f7996 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator.py
@@ -5,6 +5,7 @@ import pytest
import time_machine
from unittest.mock import MagicMock, patch
+import requests
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.aviator import aviator
@@ -314,6 +315,141 @@ class TestFanOutExtraction:
]
+class TestBranchesFanOut:
+ def test_request_sends_the_repository_as_a_json_body(self, monkeypatch: Any) -> None:
+ # GET /branches takes a nested repository object that flat query params cannot express, so
+ # the documented form is a JSON body. Sending it as `params` instead is rejected by the API.
+ captured: dict[str, Any] = {}
+
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, **kwargs: Any) -> Any:
+ captured.update(kwargs)
+ return {"branches": [{"pattern": "release-*", "paused": True, "paused_message": "held"}]}
+
+ rows = _run_fan_out("branches", fake_fetch, [{"org": "o", "name": "r"}], _FakeResumableManager(), monkeypatch)
+
+ assert captured == {"json_body": {"repository": {"org": "o", "name": "r"}}}
+ assert rows == [{"org": "o", "repo": "r", "pattern": "release-*", "paused": True, "paused_message": "held"}]
+
+ def test_branch_without_a_pattern_is_skipped(self, monkeypatch: Any) -> None:
+ # pattern is part of the (org, repo, pattern) primary key; a null-keyed row would collapse
+ # every patternless branch in the repo into a single persisted row, so such rows are dropped.
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, **kwargs: Any) -> Any:
+ return {"branches": [{"pattern": "master", "paused": False}, {"paused": True}]}
+
+ rows = _run_fan_out("branches", fake_fetch, [{"org": "o", "name": "r"}], _FakeResumableManager(), monkeypatch)
+ assert [r["pattern"] for r in rows] == ["master"]
+
+
+class TestBotPullRequestsFanOut:
+ @staticmethod
+ def _fetch_for(queued: list[int], bot_prs: dict[int, Any]) -> Any:
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, **kwargs: Any) -> Any:
+ if url.endswith("/pull_request/queued"):
+ return {"pull_requests": [{"number": n} for n in queued]}
+ return bot_prs.get(kwargs["params"]["number"])
+
+ return fake_fetch
+
+ def test_queued_prs_sharing_a_batch_yield_one_row(self, monkeypatch: Any) -> None:
+ # Every queued PR in a batch resolves to the same bot PR. Merge only dedupes across syncs, so
+ # emitting all three would put duplicate (org, repo, number) keys in one batch, and every
+ # later merge would multi-match them.
+ batch = {
+ "number": 201,
+ "github_url": "https://github.com/o/r/pull/201",
+ "target_branch": "master",
+ "head_commit_sha": "abc",
+ "head_branch_oid": "abc",
+ "codemix_pre_batch_sha": "def",
+ "pull_requests": [{"number": 89}, {"number": 90}, {"number": 91}],
+ }
+ fake_fetch = self._fetch_for([89, 90, 91], {89: batch, 90: batch, 91: batch})
+
+ rows = _run_fan_out(
+ "bot_pull_requests", fake_fetch, [{"org": "o", "name": "r"}], _FakeResumableManager(), monkeypatch
+ )
+
+ # head_branch_oid is a documented legacy alias for head_commit_sha, so it is not carried.
+ # The pipeline lands the member list as a JSON string, which is what the warehouse column holds.
+ assert rows == [
+ {
+ "org": "o",
+ "repo": "r",
+ "number": 201,
+ "github_url": "https://github.com/o/r/pull/201",
+ "target_branch": "master",
+ "head_commit_sha": "abc",
+ "codemix_pre_batch_sha": "def",
+ "pull_request_numbers": "[89,90,91]",
+ }
+ ]
+
+ def test_queued_prs_without_a_batch_are_skipped(self, monkeypatch: Any) -> None:
+ # Serial-mode repos never create bot PRs, so the lookup 404s for every queued PR. That must
+ # sync an empty table rather than fail the whole run.
+ fake_fetch = self._fetch_for([89, 90], {89: None, 90: {"number": 202, "pull_requests": []}})
+
+ rows = _run_fan_out(
+ "bot_pull_requests", fake_fetch, [{"org": "o", "name": "r"}], _FakeResumableManager(), monkeypatch
+ )
+ assert [(r["number"], r["pull_request_numbers"]) for r in rows] == [(202, "[]")]
+
+
+class TestUserActions:
+ @staticmethod
+ def _run(pages: dict[int, Any], monkeypatch: Any) -> list[dict]:
+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any, **kwargs: Any) -> Any:
+ return pages[kwargs["params"]["page"]]
+
+ monkeypatch.setattr(aviator, "_fetch", fake_fetch)
+ rows: list[dict] = []
+ for table in get_rows(
+ api_token="av_uat_test",
+ endpoint="user_actions",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ ):
+ rows.extend(table.to_pylist())
+ return rows
+
+ def test_pagination_stops_on_the_first_empty_page(self, monkeypatch: Any) -> None:
+ # The endpoint documents no page size and no total, so an empty page is the only end signal.
+ pages = {
+ 1: [
+ {
+ "timestamp": "2026-06-15T10:00:00Z",
+ "actor": "[email protected]",
+ "action": "queue",
+ "entity": "merge_queue",
+ "target": "89",
+ }
+ ],
+ 2: [
+ {
+ "timestamp": "2026-06-14T10:00:00Z",
+ "actor": "[email protected]",
+ "action": "login",
+ "entity": "account",
+ "target": None,
+ }
+ ],
+ 3: [],
+ }
+ rows = self._run(pages, monkeypatch)
+ assert [r["timestamp"] for r in rows] == ["2026-06-15T10:00:00Z", "2026-06-14T10:00:00Z"]
+ assert rows[1]["target"] is None
+
+ def test_entry_without_a_timestamp_is_skipped(self, monkeypatch: Any) -> None:
+ # timestamp leads the composite primary key and the endpoint exposes no id, so an entry
+ # without one cannot be identified at all.
+ pages = {
+ 1: [{"timestamp": "2026-06-15T10:00:00Z", "action": "keep"}, {"action": "no timestamp"}],
+ 2: [],
+ }
+ rows = self._run(pages, monkeypatch)
+ assert [r["action"] for r in rows] == ["keep"]
+
+
class TestFanOutResume:
def _fetch_stats(self, session: Any, url: str, headers: dict, logger: Any, params: dict | None = None) -> Any:
p = params or {}
@@ -386,11 +522,10 @@ class TestFetchRetries:
assert result == {"ok": True}
assert session.get.call_count == 2
- def test_client_error_raises_without_retry(self) -> None:
- import requests
-
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_error_raises_without_retry(self, _name: str, status: int) -> None:
bad = requests.Response()
- bad.status_code = 401
+ bad.status_code = status
session = MagicMock()
session.get.return_value = bad
@@ -398,6 +533,19 @@ class TestFetchRetries:
aviator._fetch(session, "https://api.aviator.co/api/v1/repo", {}, MagicMock())
assert session.get.call_count == 1
+ def test_not_found_returns_none_only_when_opted_in(self) -> None:
+ # The bot-PR lookup treats 404 as "this PR has no batch"; every other caller must still raise,
+ # otherwise a mistyped path would silently sync an empty table.
+ bad = requests.Response()
+ bad.status_code = 404
+ session = MagicMock()
+ session.get.return_value = bad
+
+ result = aviator._fetch(
+ session, "https://api.aviator.co/api/v1/bot_pull_request", {}, MagicMock(), none_on_not_found=True
+ )
+ assert result is None
+
class TestSourceResponseSortMode:
@parameterized.expand(
@@ -407,6 +555,10 @@ class TestSourceResponseSortMode:
("queued_pull_requests", "desc", "created_at"),
("queue_stats", "desc", None),
("config_history", "desc", "applied_at"),
+ ("branches", "desc", None),
+ ("bot_pull_requests", "desc", None),
+ # Top-level, but the endpoint documents newest-first ordering, so it is desc too.
+ ("user_actions", "desc", "timestamp"),
]
)
def test_sort_mode_and_partition(self, endpoint: str, expected_sort: str, partition_key: str | None) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator_source.py
index 58a95a10b450..2a7eff78bb90 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviator/tests/test_aviator_source.py
@@ -57,6 +57,9 @@ class TestAviatorSource:
("queued_pull_requests", False, []),
("queue_stats", False, []),
("config_history", False, []),
+ ("branches", False, []),
+ ("bot_pull_requests", False, []),
+ ("user_actions", False, []),
]
)
def test_incremental_support_per_endpoint(