:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): sync Trunk.io merge queue pull requests (#76794)
Tom Owers28341cac0521
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex a84536cd79f2..7dd946532c56 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@@ -8716,15 +8716,17 @@ Diffed against: <https://trigger.dev/docs/llms.txt>Note: Trigger.dev also ships a TRQL query endpoint (management/query/execute) that exposes run data as a SQL-like surface; its schema endpoint (management/query/schema) lists every queryable table and would be the cheapest way to widen coverage. Env vars and queue concurrency controls were excluded as config.-## TrunkIo — adequate+## TrunkIo — gaps-Today (3): `FailingTests`, `QuarantinedTests`, `UnhealthyTests`+Today (4): `FailingTests`, `MergeQueuePullRequests`, `QuarantinedTests`, `UnhealthyTests`-Diffed against: <https://docs.trunk.io/flaky-tests/reference/api-reference.md>+Diffed against: <https://docs.trunk.io/openapi.json> (spec-verified 2026-08-03; supersedes the 2026-07-26 prose-docs pass)-No material gaps found.+- [x] `listPullRequests` — merge queue history: state, stateChangedAt, priority, batching flags and author per submitted PR. Cursor-paginated (`cursor`/`take`, `nextCursor`) with a `since` filter on conclusion time, so it is a genuine incremental collection (high)+- [ ] `flaky-tests/get-test-details` — column-level, not a missing table: it returns the same 20 fields as a `list-failing-tests` row, so it adds nothing to `FailingTests`. Its only value is backfilling `most_common_failures` and `failure_rate_last_7d`/`_24h` onto `UnhealthyTests` rows whose test has not failed inside the `FailingTests` window, at the cost of one call per unhealthy test (low)+- [ ] `getQueue` — merge queue configuration (concurrency, batching, merge method, required statuses) plus a point-in-time `enqueuedPullRequests` snapshot that duplicates `listPullRequests`. Full-refresh only, so it captures the current config and never its history — it cannot answer "did merge time change when we bumped concurrency" retrospectively (low)-Note: The Flaky Tests REST API has exactly five endpoints: three list endpoints (distinct failed tests in a time range, unhealthy tests, quarantined tests) - all three already exposed as FailingTests, UnhealthyTests and QuarantinedTests - plus a single test-case detail lookup and a write op (link a ticket). Trunk's other API is the Merge Queue API (docs.trunk.io/merge-queue/reference/merge), a POST-based control plane (submit/cancel/restart PR, getQueue, getSubmittedPullRequest, Prometheus metrics) that requires per-branch parameters rather than exposing listable collections, so it is not a warehouse gap for this source.+Note: the 2026-07-26 pass recorded Merge Queue as a control plane with no listable collections. The OpenAPI spec contradicts that — `/listPullRequests` is a paginated collection with an incremental filter — hence the correction. It does need a `targetBranch` the flaky-tests endpoints don't (a queue covers one branch), which is why the table ships opt-in via a source config field. Of the remaining 21 paths: `/getMergeQueueTestingDetails` needs a `testRunId` no readable endpoint returns, so a connector cannot reach it; `/getMergeQueueMetrics` is `text/plain` Prometheus; `/status` is Trunk's own service health rather than customer data; the other 11 are writes (submit/cancel/restart PR, queue CRUD, `link-ticket-to-test-case`, alpha `create-ci-run`) or device-auth token flows.## TVMaze — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/trunkio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/trunkio.pyindex bd405c9a7ba0..4c630209dd2c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/trunkio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/trunkio.py@@ -11,3 +11,4 @@ class TrunkIoSourceConfig(config.Config):repo_host: strrepo_owner: strrepo_name: str+ merge_queue_target_branch: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/canonical_descriptions.pyindex 7b2d31409484..3ec6c124b6b9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/canonical_descriptions.py@@ -1,8 +1,10 @@from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)+from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.settings import MERGE_QUEUE_PULL_REQUESTS_FLAKY_TESTS_DOCS_URL = "https://docs.trunk.io/flaky-tests/api"+_MERGE_QUEUE_DOCS_URL = "https://docs.trunk.io/merge-queue/reference/merge"CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"UnhealthyTests": {@@ -64,4 +66,24 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"synced_through": "PostHog-added: the end of the time window this row was synced in, used to track incremental progress.",},},+ MERGE_QUEUE_PULL_REQUESTS: {+ "description": "Pull requests submitted to the repository's merge queue for one target branch, with the state each one reached and how it was prioritized.",+ "docs_url": _MERGE_QUEUE_DOCS_URL,+ "columns": {+ "id": "A unique identifier for this pull request's entry in the merge queue.",+ "state": "The pull request's state in the queue: not_ready, pending, testing, tests_passed, merged, failed, cancelled or pending_failure.",+ "stateChangedAt": "The time the pull request last changed state.",+ "priorityValue": "The numeric priority the pull request was queued at.",+ "priorityName": "The name of the priority the pull request was queued at.",+ "usedDefaultPriorityName": "The default priority name applied when the pull request did not set one.",+ "skipTheLine": "Whether the pull request jumped ahead of the rest of the queue.",+ "noBatch": "Whether the pull request was tested on its own rather than batched with others.",+ "prNumber": "The pull request number in the source control provider.",+ "prTitle": "The title of the pull request.",+ "prSha": "The commit SHA of the pull request.",+ "prBaseBranch": "The base branch of the pull request.",+ "prAuthor": "The author of the pull request.",+ "synced_through": "PostHog-added: the start of the sync run this row was fetched in, used to track incremental progress.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/settings.pyindex a534532c9b24..c402185dde2b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/settings.py@@ -18,16 +18,25 @@ UNHEALTHY_STATUSES = ("FLAKY", "BROKEN")FAILING_TESTS_WINDOW_DAYS = 7FAILING_TESTS_DEFAULT_LOOKBACK_DAYS = 30+# The Merge Queue API is a separate surface from Flaky Tests: `/listPullRequests` paginates with+# top-level `cursor`/`take` body params rather than the nested `page_query` object, and it is+# scoped to one merge queue, i.e. one target branch.+MERGE_QUEUE_PAGE_SIZE = 100++MERGE_QUEUE_PULL_REQUESTS = "MergeQueuePullRequests"+ENDPOINTS = ("UnhealthyTests","QuarantinedTests","FailingTests",+ MERGE_QUEUE_PULL_REQUESTS,)DESCRIPTIONS: dict[str, str] = {"UnhealthyTests": "Tests Trunk currently considers flaky or broken, combining both status filters.","QuarantinedTests": "Tests currently quarantined (failures suppressed) in this repository.","FailingTests": "Distinct tests that failed at least once within a given time window.",+ MERGE_QUEUE_PULL_REQUESTS: "Pull requests submitted to the merge queue for one target branch, with queue state and priority.",}PRIMARY_KEYS: dict[str, list[str]] = {@@ -36,12 +45,27 @@ PRIMARY_KEYS: dict[str, list[str]] = {# unstable), so the natural key is the tuple that identifies the test case itself."QuarantinedTests": ["name", "parent", "file", "classname", "variant"],"FailingTests": ["id"],+ MERGE_QUEUE_PULL_REQUESTS: ["id"],}-# `FailingTests` is the only endpoint with a real server-side time filter (start_time/end_time).-# `synced_through` is a synthetic per-row field (not part of the API response) stamped with the-# end of the window each row was fetched in, so the pipeline's incremental watermark advances as-# we walk forward through time.+# `synced_through` is a synthetic per-row field (not part of any API response) carrying the point+# in time the row's endpoint is covered up to, so the pipeline's incremental watermark advances+# without depending on the order rows arrive in:+#+# - `FailingTests` has a server-side `start_time`/`end_time` filter capped at 7 days, so each row+# is stamped with the end of the window it was fetched in as the sync walks forward.+# - `MergeQueuePullRequests` has a server-side `since` filter on conclusion time but no documented+# ordering, so every row in a run is stamped with the run's start time. The next run re-reads+# from there, which overlaps by one run's duration rather than risking a gap; the overlap is+# deduped by the merge on `id`.INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {"FailingTests": [incremental_field("synced_through", IncrementalFieldType.DateTime)],+ MERGE_QUEUE_PULL_REQUESTS: [incremental_field("synced_through", IncrementalFieldType.DateTime)],+}++# Merge Queue is a separate Trunk product from Flaky Tests and needs a target branch the other+# endpoints don't, so the table is offered but left unselected rather than failing every sync for+# the Flaky-Tests-only majority.+SHOULD_SYNC_DEFAULT: dict[str, bool] = {+ MERGE_QUEUE_PULL_REQUESTS: False,}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/source.pyindex bc298d51ee46..f763523c41c7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/source.py@@ -27,18 +27,26 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.sDESCRIPTIONS,ENDPOINTS,INCREMENTAL_FIELDS,+ MERGE_QUEUE_PULL_REQUESTS,PRIMARY_KEYS,+ SHOULD_SYNC_DEFAULT,)from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.trunk_io import (TrunkIoResumeConfig,TrunkRepo,failing_tests,+ merge_queue_pull_requests,quarantined_tests,unhealthy_tests,validate_credentials as validate_trunk_io_credentials,)from products.warehouse_sources.backend.types import ExternalDataSourceType+MISSING_TARGET_BRANCH_ERROR = (+ f"Trunk.io {MERGE_QUEUE_PULL_REQUESTS} needs a merge queue target branch. "+ "Add one to this source's settings, or turn this table off."+)+@SourceRegistry.registerclass TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):@@ -53,6 +61,7 @@ class TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):return {"401": "Trunk.io authentication failed. Check your API token, organization slug, and repository details.","Unauthorized": "Trunk.io authentication failed. Check your API token, organization slug, and repository details.",+ MISSING_TARGET_BRANCH_ERROR: MISSING_TARGET_BRANCH_ERROR,}def get_canonical_descriptions(self) -> CanonicalDescriptions:@@ -71,7 +80,13 @@ class TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):force_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, descriptions=DESCRIPTIONS)+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ descriptions=DESCRIPTIONS,+ should_sync_default=SHOULD_SYNC_DEFAULT,+ )def validate_credentials(self,@@ -110,6 +125,20 @@ class TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):if inputs.should_use_incremental_fieldelse None,)+ elif endpoint == MERGE_QUEUE_PULL_REQUESTS:+ target_branch = (config.merge_queue_target_branch or "").strip()+ if not target_branch:+ raise ValueError(MISSING_TARGET_BRANCH_ERROR)+ items = merge_queue_pull_requests(+ config.api_token,+ repo,+ target_branch,+ resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )else:raise ValueError(f"Unknown Trunk.io endpoint: {endpoint}")@@ -125,12 +154,13 @@ class TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):name=SchemaExternalDataSourceType.TRUNK_IO,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Trunk.io (Trunk Technologies, Inc.)",- caption="""Enter a Trunk.io API token to sync flaky test data for a single repository.+ caption="""Enter a Trunk.io API token to sync flaky test and merge queue data for a single repository.Supported tables:- `UnhealthyTests`- `QuarantinedTests`- `FailingTests`+- `MergeQueuePullRequests` (needs a merge queue target branch below)Create an API token in the Trunk app under Settings > Organization > General > API.""",@@ -180,6 +210,15 @@ Create an API token in the Trunk app under Settings > Organization > General > Aplaceholder="my-repo",secret=False,),+ SourceFieldInputConfig(+ name="merge_queue_target_branch",+ label="Merge queue target branch",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="main",+ secret=False,+ caption="Only needed for the `MergeQueuePullRequests` table. A Trunk merge queue covers one target branch, so this is the branch your queue merges into.",+ ),],),releaseStatus=ReleaseStatus.ALPHA,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io.pyindex 822ac8fe2c0d..de7b8c1901d1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io.py@@ -15,10 +15,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.sFAILING_TESTS_WINDOW_DAYS,)from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.trunk_io import (+ TrunkCursorPaginator,TrunkIoResumeConfig,TrunkPageQueryPaginator,TrunkRepo,failing_tests,+ merge_queue_pull_requests,quarantined_tests,unhealthy_tests,validate_credentials,@@ -390,6 +392,154 @@ class TestFailingTests:manager.clear_state.assert_called_once()+class TestTrunkCursorPaginator:+ @parameterized.expand(+ [+ ("first_page_omits_cursor", "", False),+ ("resumed_page_sends_cursor", "cursor-1", True),+ ]+ )+ def test_cursor_only_sent_once_we_have_one(self, _label: str, cursor: str, expect_cursor: bool) -> None:+ # `cursor` is uuid-typed on Trunk's side, so an empty string is not a valid "first page"+ # value the way `page_token` is on the flaky-tests endpoints.+ paginator = TrunkCursorPaginator(cursor=cursor)+ request = Request(method="POST", url="https://api.trunk.io/v1/listPullRequests")+ paginator.init_request(request)++ assert request.json["take"] == 100+ assert ("cursor" in request.json) is expect_cursor++ @parameterized.expand(+ [+ ("has_next", {"nextCursor": "cursor-2"}, True),+ ("empty_cursor", {"nextCursor": ""}, False),+ ("missing_cursor", {}, False),+ ]+ )+ def test_update_state(self, _label: str, body: dict[str, Any], expected_has_next: bool) -> None:+ paginator = TrunkCursorPaginator()+ response = MagicMock()+ response.json.return_value = body+ paginator.update_state(response)++ assert paginator.has_next_page is expected_has_next+ assert paginator.get_resume_state() == ({"cursor": "cursor-2"} if expected_has_next else None)+++class TestMergeQueuePullRequests:+ @freeze_time("2024-06-15T00:00:00Z")+ def test_fresh_run_paginates_and_stamps_one_synced_through(self) -> None:+ patcher, sent_bodies = _drive_session(+ [+ _make_http_response({"pullRequests": [{"id": "pr-1"}], "nextCursor": "cursor-1"}),+ _make_http_response({"pullRequests": [{"id": "pr-2"}], "nextCursor": ""}),+ ]+ )+ try:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ pages = list(+ merge_queue_pull_requests(+ "token",+ REPO,+ "main",+ manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ )+ finally:+ patcher.stop()++ assert [row["id"] for page in pages for row in page] == ["pr-1", "pr-2"]+ # One stamp for the whole run, taken at its start, because a per-page `now()` would push+ # the watermark past rows a later page had not been fetched for yet.+ assert {row["synced_through"] for page in pages for row in page} == {"2024-06-15T00:00:00Z"}+ assert sent_bodies[0]["targetBranch"] == "main"+ assert "since" not in sent_bodies[0]+ assert sent_bodies[1]["cursor"] == "cursor-1"+ manager.clear_state.assert_called_once()++ def test_incremental_run_sends_since(self) -> None:+ patcher, sent_bodies = _drive_session([_make_http_response({"pullRequests": [], "nextCursor": ""})])+ try:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ list(+ merge_queue_pull_requests(+ "token",+ REPO,+ "main",+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-06-01T00:00:00Z",+ )+ )+ finally:+ patcher.stop()++ assert sent_bodies[0]["since"] == "2024-06-01T00:00:00Z"++ @freeze_time("2024-06-15T00:00:00Z")+ def test_resume_seeds_cursor_and_pins_synced_through(self) -> None:+ patcher, sent_bodies = _drive_session(+ [_make_http_response({"pullRequests": [{"id": "pr-3"}], "nextCursor": ""})]+ )+ try:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = TrunkIoResumeConfig(+ cursor="cursor-mid", synced_through="2024-06-14T00:00:00Z"+ )++ pages = list(+ merge_queue_pull_requests(+ "token",+ REPO,+ "main",+ manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ )+ finally:+ patcher.stop()++ assert sent_bodies[0]["cursor"] == "cursor-mid"+ # The resumed half must not claim coverage the interrupted first half never had.+ assert pages[0][0]["synced_through"] == "2024-06-14T00:00:00Z"++ @freeze_time("2024-06-15T00:00:00Z")+ def test_saves_cursor_with_stamp_after_each_non_terminal_page(self) -> None:+ patcher, _ = _drive_session(+ [+ _make_http_response({"pullRequests": [{"id": "pr-1"}], "nextCursor": "cursor-1"}),+ _make_http_response({"pullRequests": [{"id": "pr-2"}], "nextCursor": ""}),+ ]+ )+ try:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ list(+ merge_queue_pull_requests(+ "token",+ REPO,+ "main",+ manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ )+ finally:+ patcher.stop()++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [TrunkIoResumeConfig(cursor="cursor-1", synced_through="2024-06-15T00:00:00Z")]++class TestClientRedirectHandling:def test_redirect_is_refused_without_replaying_token(self) -> None:# A 30x from the API host must not be followed — `x-api-token` is a nonstandard headerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io_source.pyindex 05f3605856d6..41243e8f7878 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io_source.py@@ -1,3 +1,4 @@+import pytestfrom unittest.mock import MagicMock, patchfrom parameterized import parameterized@@ -43,6 +44,7 @@ class TestTrunkIoSource:repo_host="github.com",repo_owner="my-org",repo_name="my-repo",+ merge_queue_target_branch="main",)def test_source_type(self):@@ -59,7 +61,14 @@ class TestTrunkIoSource:def test_get_source_config_field_names(self):field_names = [f.name for f in self.source.get_source_config.fields]- assert field_names == ["api_token", "org_url_slug", "repo_host", "repo_owner", "repo_name"]+ assert field_names == [+ "api_token",+ "org_url_slug",+ "repo_host",+ "repo_owner",+ "repo_name",+ "merge_queue_target_branch",+ ]def test_api_token_field_is_secret(self):field = next(f for f in self.source.get_source_config.fields if f.name == "api_token")@@ -68,7 +77,12 @@ class TestTrunkIoSource:def test_get_schemas_returns_expected_endpoints(self):schemas = self.source.get_schemas(self.config, self.team_id)- assert {s.name for s in schemas} == {"UnhealthyTests", "QuarantinedTests", "FailingTests"}+ assert {s.name for s in schemas} == {+ "UnhealthyTests",+ "QuarantinedTests",+ "FailingTests",+ "MergeQueuePullRequests",+ }def test_get_schemas_filters_by_names(self):schemas = self.source.get_schemas(self.config, self.team_id, names=["QuarantinedTests"])@@ -79,6 +93,7 @@ class TestTrunkIoSource:("UnhealthyTests", False),("QuarantinedTests", False),("FailingTests", True),+ ("MergeQueuePullRequests", True),])def test_get_schemas_incremental_support(self, endpoint: str, supports_incremental: bool):@@ -111,6 +126,7 @@ class TestTrunkIoSource:("UnhealthyTests", "unhealthy_tests"),("QuarantinedTests", "quarantined_tests"),("FailingTests", "failing_tests"),+ ("MergeQueuePullRequests", "merge_queue_pull_requests"),])def test_source_for_pipeline_dispatches_to_expected_transport(self, schema_name: str, transport_fn: str):@@ -143,6 +159,7 @@ class TestTrunkIoSource:("UnhealthyTests", ["id"]),("QuarantinedTests", ["name", "parent", "file", "classname", "variant"]),("FailingTests", ["id"]),+ ("MergeQueuePullRequests", ["id"]),])def test_source_for_pipeline_primary_keys(self, schema_name: str, expected_keys: list[str]):@@ -152,6 +169,7 @@ class TestTrunkIoSource:"UnhealthyTests": "unhealthy_tests","QuarantinedTests": "quarantined_tests","FailingTests": "failing_tests",+ "MergeQueuePullRequests": "merge_queue_pull_requests",}[schema_name]with patch(@@ -162,10 +180,41 @@ class TestTrunkIoSource:assert response.primary_keys == expected_keys+ @parameterized.expand([("unset", None), ("blank", " ")])+ def test_merge_queue_without_target_branch_fails_permanently(self, _label: str, target_branch):+ # Merge Queue is scoped to one branch, so without it the sync would call the API with an+ # empty targetBranch forever. Fail once, with a message the user can act on.+ config = TrunkIoSourceConfig(+ api_token="test-token",+ org_url_slug="my-org",+ repo_host="github.com",+ repo_owner="my-org",+ repo_name="my-repo",+ merge_queue_target_branch=target_branch,+ )+ inputs = _make_inputs("MergeQueuePullRequests")++ with pytest.raises(ValueError) as excinfo:+ self.source.source_for_pipeline(config, MagicMock(spec=ResumableSourceManager), inputs)++ assert any(key in str(excinfo.value) for key in self.source.get_non_retryable_errors())++ def test_merge_queue_table_is_not_synced_by_default(self):+ # Flaky-Tests-only orgs are the majority and have no merge queue, so the table is offered+ # but left unselected rather than failing their syncs.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["MergeQueuePullRequests"].should_sync_default is False+ assert schemas["FailingTests"].should_sync_default is True+def test_get_non_retryable_errors_covers_auth_failures(self):errors = self.source.get_non_retryable_errors()assert any("401" in key for key in errors)def test_get_canonical_descriptions_covers_all_endpoints(self):descriptions = self.source.get_canonical_descriptions()- assert set(descriptions.keys()) == {"UnhealthyTests", "QuarantinedTests", "FailingTests"}+ assert set(descriptions.keys()) == {+ "UnhealthyTests",+ "QuarantinedTests",+ "FailingTests",+ "MergeQueuePullRequests",+ }diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/trunk_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/trunk_io.pyindex a4511a4551df..ceebee16d9a9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/trunk_io.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/trunk_io.py@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.sBASE_URL,FAILING_TESTS_DEFAULT_LOOKBACK_DAYS,FAILING_TESTS_WINDOW_DAYS,+ MERGE_QUEUE_PAGE_SIZE,PAGE_SIZE,UNHEALTHY_STATUSES,)@@ -29,6 +30,8 @@ class TrunkIoResumeConfig:page_token: str = ""status: Optional[str] = Nonewindow_start: Optional[str] = None+ cursor: Optional[str] = None+ synced_through: Optional[str] = None@dataclasses.dataclass@@ -89,6 +92,59 @@ class TrunkPageQueryPaginator(BasePaginator):return f"TrunkPageQueryPaginator(page_token={self.page_token!r})"+class TrunkCursorPaginator(BasePaginator):+ """The Merge Queue endpoints take `cursor`/`take` as top-level POST body params and return+ `nextCursor`, unlike the flaky-tests endpoints' nested `page_query` object."""++ def __init__(self, take: int = MERGE_QUEUE_PAGE_SIZE, cursor: str = "") -> None:+ super().__init__()+ self.take = take+ self.cursor = cursor+ if cursor:+ self._has_next_page = True++ def init_request(self, request: Request) -> None:+ self._apply(request)++ def update_request(self, request: Request) -> None:+ self._apply(request)++ def _apply(self, request: Request) -> None:+ if request.json is None:+ request.json = {}+ request.json["take"] = self.take+ # `cursor` is typed as a uuid, so send it only once we have one, because an empty string+ # is not the documented "first page" value the way `page_token` is on the flaky-tests+ # endpoints.+ if self.cursor:+ request.json["cursor"] = self.cursor+ else:+ request.json.pop("cursor", None)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ try:+ next_cursor = response.json().get("nextCursor") or ""+ except Exception:+ next_cursor = ""+ if next_cursor:+ self.cursor = next_cursor+ self._has_next_page = True+ else:+ self._has_next_page = False++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return {"cursor": self.cursor} if self._has_next_page else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ cursor = state.get("cursor")+ if cursor:+ self.cursor = cursor+ self._has_next_page = True++ def __str__(self) -> str:+ return f"TrunkCursorPaginator(cursor={self.cursor!r})"++def _client(api_token: str) -> RESTClient:# Pin to the API origin and never follow redirects: the token rides a nonstandard# `x-api-token` header that `requests` won't strip on an off-origin redirect, so a 30x@@ -247,6 +303,48 @@ def failing_tests(resumable_source_manager.clear_state()+def merge_queue_pull_requests(+ api_token: str,+ repo: TrunkRepo,+ target_branch: str,+ resumable_source_manager: ResumableSourceManager[TrunkIoResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> Iterator[list[dict[str, Any]]]:+ client = _client(api_token)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = (resume.cursor if resume else None) or ""+ # Pin the stamp across a resume so the second half of an interrupted run doesn't claim+ # coverage the first half never had.+ synced_through = (resume.synced_through if resume else None) or _format_rfc3339(datetime.now(UTC))++ body: dict[str, Any] = {"repo": repo.as_dict(), "targetBranch": target_branch}+ if should_use_incremental_field and db_incremental_field_last_value:+ body["since"] = _format_rfc3339(_coerce_datetime(db_incremental_field_last_value))++ def checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state and state.get("cursor"):+ resumable_source_manager.save_state(+ TrunkIoResumeConfig(cursor=str(state["cursor"]), synced_through=synced_through)+ )++ for page in client.paginate(+ path="/listPullRequests",+ method="post",+ json=body,+ paginator=TrunkCursorPaginator(cursor=cursor),+ data_selector="pullRequests",+ resume_hook=checkpoint,+ ):+ if page:+ for row in page:+ row["synced_through"] = synced_through+ yield page++ resumable_source_manager.clear_state()++def validate_credentials(api_token: str, org_url_slug: str, repo: TrunkRepo) -> tuple[bool, str | None]:session = make_tracked_session(redact_values=(api_token,), allow_redirects=False)try: