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): support trunk io API version v2 (#113230)

Tom Owers84bb86c07ff5
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.md
index a9de6c366654..837f7cf1f4d6 100644
--- a/.agents/skills/warehouse-source-new-version/SKILL.md
+++ b/.agents/skills/warehouse-source-new-version/SKILL.md
@@ -111,6 +111,7 @@ The opposite gap also occurs: a reference rendered from one version-blind OpenAP
- A source with no dispatch may currently read its version from a constant on a shared model (e.g. the OAuth `Integration` model) that also drives version-independent flows like OAuth token minting. Repoint only the sync request path onto the resolved pin; leave that constant, since bumping it changes those other flows' version with a blast radius beyond this source.
- A collection the new version serves only under a parent scope (per team, workspace, or project) instead of account-wide is not a dropped table: keep the table and fan out over the version's parent list endpoint, which the token can also read.
- The opposite holds when the new version is a genuinely different vendor product rather than a renamed collection (the old and new labels serve different endpoints and tables): give the new version its own disjoint table set, don't force the old names onto it. That divergence is safe only because sources are never repinned — so a 2.5→3.0-style move is lossy, and its migration is documented-not-scripted, exactly like a rename that changes primary keys.
+- A third shape sits between the two: the vendor labels a new API scope `v2` but keeps the old one served with no successor for its endpoints, and ids differ between the scopes. Make the new version's table set a superset: old tables stay on their legacy wire under the new pin, new tables join them, and the old pin rejects the new tables at sync time. Dropping the old tables would strand new sources whose data still lives in the old scope.
- The shared REST framework only binds a resolved parent field into a child resource's URL **path**, not its query string (`_bind_path_params` raises "Resolve query params not supported yet"). If a new version scopes a fan-out child by a query param where the old version used a path segment, the dependent-resource `{"type": "resolve"}` machinery can't express it — iterate the parent ids explicitly in the source and bake each id into the child's params (or POST body) instead.
## Self-improvement
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 efae53f0e109..922c5900a23d 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
@@ -9000,13 +9000,15 @@ Note: Trigger.dev also ships a TRQL query endpoint (management/query/execute) th
## TrunkIo — gaps
-Today (4): `FailingTests`, `MergeQueuePullRequests`, `QuarantinedTests`, `UnhealthyTests`
+Today (6): `FailingTests`, `MergeQueuePullRequests`, `QuarantinedTests`, `TestCollections` (v2), `Tests` (v2), `UnhealthyTests`
Diffed against: <https://docs.trunk.io/openapi.json> (spec-verified 2026-08-03; supersedes the 2026-07-26 prose-docs pass)
- [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)
+- [x] `GET /v2/test-collections` — test collections, each with its own flake detection and quarantine settings. Cursor-paginated (`limit`/`cursor`, `nextCursor`), full refresh. Served on API version `v2` only (medium)
+- [x] `GET /v2/tests` — tests across every collection in the org, with status, quarantine state and labels. Cursor-paginated, full refresh; test ids differ from the repository-scoped v1 tables. Served on API version `v2` only (medium)
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.
diff --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.py
index 3ec6c124b6b9..0eb7561cba5b 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,10 +1,15 @@
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
+from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.settings import (
+ MERGE_QUEUE_PULL_REQUESTS,
+ TEST_COLLECTIONS,
+ TESTS,
+)
_FLAKY_TESTS_DOCS_URL = "https://docs.trunk.io/flaky-tests/api"
_MERGE_QUEUE_DOCS_URL = "https://docs.trunk.io/merge-queue/reference/merge"
+_V2_DOCS_URL = "https://docs.trunk.io/flaky-tests/reference/api-reference"
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"UnhealthyTests": {
@@ -86,4 +91,39 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"synced_through": "PostHog-added: the start of the sync run this row was fetched in, used to track incremental progress.",
},
},
+ TEST_COLLECTIONS: {
+ "description": "Test collections in the organization. Each collection has its own flake detection, quarantining and ticketing settings.",
+ "docs_url": _V2_DOCS_URL,
+ "columns": {
+ "id": "The collection's id.",
+ "name": "The name of the collection.",
+ "description": "The description of the collection, if any.",
+ "testCount": "The number of distinct tests seen in this collection. Stays 0 until the first upload is processed.",
+ "quarantineEnabled": "Whether quarantining is turned on for this collection.",
+ "autoQuarantineEnabled": "Whether flaky tests in this collection are quarantined automatically.",
+ "createdAt": "The time the collection was created.",
+ "updatedAt": "The time the collection was last updated.",
+ },
+ },
+ TESTS: {
+ "description": "Tests across every test collection in the organization, with their current status and quarantine state. Test ids differ from the ids in the repository-scoped tables.",
+ "docs_url": _V2_DOCS_URL,
+ "columns": {
+ "id": "A stable unique identifier for the test.",
+ "testCollectionId": "The id of the collection that owns the test.",
+ "repositoryId": "The id of the repository the test was uploaded for. Uploads made without a repository carry the nil UUID.",
+ "name": "The name of the test.",
+ "parentName": "The parent of the test, such as its test suite.",
+ "className": "The class name of the test.",
+ "file": "The file path of the test.",
+ "target": "The build target that ran the test, when one was reported.",
+ "variant": "The variant of the test.",
+ "crossVariantId": "Groups the same test across variants, when it has any.",
+ "codeowners": "Code owners for the test.",
+ "status": "The test's current status: healthy, flaky or broken.",
+ "statusSince": "When the status last changed. Empty for a test no monitor has classified yet.",
+ "quarantineState": "Whether the test is currently quarantined: quarantined or notQuarantined.",
+ "labels": "The labels on the test, with what applied each one.",
+ },
+ },
}
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.py
index c402185dde2b..fc069d1c8656 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
@@ -1,7 +1,12 @@
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+TRUNK_IO_API_VERSION_V1 = "v1"
+TRUNK_IO_API_VERSION_V2 = "v2"
+
BASE_URL = "https://api.trunk.io/v1"
+# The v2 spec lists full `/v2/...` paths against the bare origin.
+V2_BASE_URL = "https://api.trunk.io"
# Trunk's list endpoints all paginate the same way: a `page_query: {page_size, page_token}`
# object nested in the POST body (not a top-level query/json param), capped at 100 rows/page.
@@ -25,18 +30,45 @@ MERGE_QUEUE_PAGE_SIZE = 100
MERGE_QUEUE_PULL_REQUESTS = "MergeQueuePullRequests"
-ENDPOINTS = (
+# v2 is a separate, test-collection-scoped API rather than a successor to the repository-scoped
+# v1 endpoints: test ids differ between the two, and v1 is still served for orgs that have not
+# moved to collections. So a v2 pin keeps every v1 table on its v1 wire and adds the collection
+# tables on top.
+TEST_COLLECTIONS = "TestCollections"
+TESTS = "Tests"
+
+# `GET /v2/test-collections` and `GET /v2/tests` both take `limit` (max 100) and `cursor` query
+# params and return `{data, nextCursor, hasMore}`.
+V2_PAGE_SIZE = 100
+
+V1_ENDPOINTS = (
"UnhealthyTests",
"QuarantinedTests",
"FailingTests",
MERGE_QUEUE_PULL_REQUESTS,
)
+V2_ENDPOINTS = (*V1_ENDPOINTS, TEST_COLLECTIONS, TESTS)
+
+ENDPOINTS_BY_VERSION: dict[str, tuple[str, ...]] = {
+ TRUNK_IO_API_VERSION_V1: V1_ENDPOINTS,
+ TRUNK_IO_API_VERSION_V2: V2_ENDPOINTS,
+}
+
+
+def endpoints_for_version(api_version: str) -> tuple[str, ...]:
+ try:
+ return ENDPOINTS_BY_VERSION[api_version]
+ except KeyError as e:
+ raise ValueError(f"Unsupported Trunk.io API version: {api_version!r}") from e
+
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.",
+ TEST_COLLECTIONS: "Test collections in the organization, with test counts and quarantine settings.",
+ TESTS: "Tests across every test collection in the organization, with current status and quarantine state.",
}
PRIMARY_KEYS: dict[str, list[str]] = {
@@ -46,6 +78,8 @@ PRIMARY_KEYS: dict[str, list[str]] = {
"QuarantinedTests": ["name", "parent", "file", "classname", "variant"],
"FailingTests": ["id"],
MERGE_QUEUE_PULL_REQUESTS: ["id"],
+ TEST_COLLECTIONS: ["id"],
+ TESTS: ["id"],
}
# `synced_through` is a synthetic per-row field (not part of any API response) carrying the point
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.py
index 61b05fc00b78..8be269d4e6d5 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
@@ -23,16 +23,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.settings import (
DESCRIPTIONS,
- ENDPOINTS,
INCREMENTAL_FIELDS,
MERGE_QUEUE_PULL_REQUESTS,
PRIMARY_KEYS,
SHOULD_SYNC_DEFAULT,
+ TEST_COLLECTIONS,
+ TESTS,
+ TRUNK_IO_API_VERSION_V1,
+ TRUNK_IO_API_VERSION_V2,
+ endpoints_for_version,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.trunk_io import (
TrunkIoResumeConfig,
TrunkRepo,
failing_tests,
+ list_test_collections,
+ list_tests,
merge_queue_pull_requests,
quarantined_tests,
unhealthy_tests,
@@ -51,6 +57,9 @@ class TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
api_docs_url = "https://docs.trunk.io/flaky-tests/api"
+ supported_versions = (TRUNK_IO_API_VERSION_V1, TRUNK_IO_API_VERSION_V2)
+ default_version = TRUNK_IO_API_VERSION_V2
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TRUNKIO
@@ -79,7 +88,7 @@ class TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):
api_version: str | None = None,
) -> list[SourceSchema]:
return build_endpoint_schemas(
- ENDPOINTS,
+ endpoints_for_version(self.resolve_api_version(api_version)),
INCREMENTAL_FIELDS,
names,
descriptions=DESCRIPTIONS,
@@ -93,6 +102,8 @@ class TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
+ # Every version keeps the repository-scoped v1 tables, and v2 accepts the same token, so
+ # the v1 probe holds for both pins.
repo = TrunkRepo(host=config.repo_host, owner=config.repo_owner, name=config.repo_name)
return validate_trunk_io_credentials(config.api_token, config.org_url_slug, repo)
@@ -107,6 +118,8 @@ class TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):
) -> SourceResponse:
repo = TrunkRepo(host=config.repo_host, owner=config.repo_owner, name=config.repo_name)
endpoint = inputs.schema_name
+ if endpoint not in endpoints_for_version(self.resolve_api_version(inputs.api_version)):
+ raise ValueError(f"Unknown Trunk.io endpoint: {endpoint}")
if endpoint == "UnhealthyTests":
items = unhealthy_tests(config.api_token, repo, config.org_url_slug, resumable_source_manager)
@@ -137,6 +150,10 @@ class TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):
if inputs.should_use_incremental_field
else None,
)
+ elif endpoint == TEST_COLLECTIONS:
+ items = list_test_collections(config.api_token, resumable_source_manager)
+ elif endpoint == TESTS:
+ items = list_tests(config.api_token, resumable_source_manager)
else:
raise ValueError(f"Unknown Trunk.io endpoint: {endpoint}")
@@ -159,6 +176,8 @@ Supported tables:
- `QuarantinedTests`
- `FailingTests`
- `MergeQueuePullRequests` (needs a merge queue target branch below)
+- `TestCollections`
+- `Tests` (tests in your test collections)
Create an API token in the Trunk app under Settings > Organization > General > API.
""",
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.py
index 4154463174c2..bd8c030a38c9 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
@@ -20,6 +20,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.t
TrunkPageQueryPaginator,
TrunkRepo,
failing_tests,
+ list_test_collections,
+ list_tests,
merge_queue_pull_requests,
quarantined_tests,
unhealthy_tests,
@@ -540,6 +542,75 @@ class TestMergeQueuePullRequests:
assert saved == [TrunkIoResumeConfig(cursor="cursor-1", synced_through="2024-06-15T00:00:00Z")]
+class TestV2Lists:
+ @staticmethod
+ def _drive(responses: list[Response]) -> tuple[Any, list[dict[str, Any]]]:
+ sent: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **kwargs: Any) -> Response:
+ assert kwargs.get("allow_redirects") is False
+ assert kwargs.get("timeout") == (10.0, 60.0)
+ sent.append(
+ {
+ "method": request.method,
+ "url": request.url,
+ "params": dict(request.params),
+ "headers": request.auth(Request(headers={})).headers,
+ }
+ )
+ return next(response_iter)
+
+ patcher = patch(MAKE_SESSION_TARGET)
+ mock_session = patcher.start().return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+ return patcher, sent
+
+ @parameterized.expand(
+ [
+ ("test_collections", list_test_collections, "https://api.trunk.io/v2/test-collections"),
+ ("tests", list_tests, "https://api.trunk.io/v2/tests"),
+ ]
+ )
+ def test_paginates_v2_cursor_with_bearer_auth(self, _label: str, fn: Any, expected_url: str) -> None:
+ patcher, sent = self._drive(
+ [
+ _make_http_response({"data": [{"id": "a"}], "nextCursor": "cursor-1", "hasMore": True}),
+ _make_http_response({"data": [{"id": "b"}], "nextCursor": None, "hasMore": False}),
+ ]
+ )
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ pages = list(fn("token", manager))
+ finally:
+ patcher.stop()
+
+ assert [row["id"] for page in pages for row in page] == ["a", "b"]
+ assert [(r["method"].upper(), r["url"]) for r in sent] == [("GET", expected_url)] * 2
+ assert sent[0]["params"] == {"limit": 100}
+ assert sent[1]["params"] == {"limit": 100, "cursor": "cursor-1"}
+ assert sent[0]["headers"] == {"Authorization": "Bearer token"}
+ manager.save_state.assert_called_once_with(TrunkIoResumeConfig(cursor="cursor-1"))
+ manager.clear_state.assert_called_once()
+
+ def test_resume_seeds_saved_cursor(self) -> None:
+ patcher, sent = self._drive([_make_http_response({"data": [], "nextCursor": None, "hasMore": False})])
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = TrunkIoResumeConfig(cursor="cursor-resumed")
+
+ list(list_tests("token", manager))
+ finally:
+ patcher.stop()
+
+ assert sent[0]["params"]["cursor"] == "cursor-resumed"
+
+
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 header
diff --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.py
index cc0860a52a85..5b3406d00072 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
@@ -62,16 +62,63 @@ class TestTrunkIoSource:
assert repo.owner == "my-org"
assert repo.name == "my-repo"
+ def test_new_sources_default_to_v2(self):
+ assert self.source.supported_versions == ("v1", "v2")
+ assert self.source.default_version == "v2"
+
@parameterized.expand(
[
- ("UnhealthyTests", "unhealthy_tests"),
- ("QuarantinedTests", "quarantined_tests"),
- ("FailingTests", "failing_tests"),
- ("MergeQueuePullRequests", "merge_queue_pull_requests"),
+ ("v1", "v1", ["UnhealthyTests", "QuarantinedTests", "FailingTests", "MergeQueuePullRequests"]),
+ (
+ "v2",
+ "v2",
+ [
+ "UnhealthyTests",
+ "QuarantinedTests",
+ "FailingTests",
+ "MergeQueuePullRequests",
+ "TestCollections",
+ "Tests",
+ ],
+ ),
+ (
+ "unpinned",
+ None,
+ [
+ "UnhealthyTests",
+ "QuarantinedTests",
+ "FailingTests",
+ "MergeQueuePullRequests",
+ "TestCollections",
+ "Tests",
+ ],
+ ),
]
)
- def test_source_for_pipeline_dispatches_to_expected_transport(self, schema_name: str, transport_fn: str):
- inputs = _make_inputs(schema_name)
+ def test_get_schemas_lists_tables_for_pinned_version(
+ self, _label: str, api_version: str | None, expected: list[str]
+ ):
+ schemas = self.source.get_schemas(self.config, self.team_id, api_version=api_version)
+ assert [s.name for s in schemas] == expected
+
+ @parameterized.expand(
+ [
+ ("UnhealthyTests", "unhealthy_tests", "v1"),
+ ("QuarantinedTests", "quarantined_tests", "v1"),
+ ("FailingTests", "failing_tests", "v1"),
+ ("MergeQueuePullRequests", "merge_queue_pull_requests", "v1"),
+ ("UnhealthyTests", "unhealthy_tests", "v2"),
+ ("QuarantinedTests", "quarantined_tests", "v2"),
+ ("FailingTests", "failing_tests", "v2"),
+ ("MergeQueuePullRequests", "merge_queue_pull_requests", "v2"),
+ ("TestCollections", "list_test_collections", "v2"),
+ ("Tests", "list_tests", "v2"),
+ ]
+ )
+ def test_source_for_pipeline_dispatches_to_expected_transport(
+ self, schema_name: str, transport_fn: str, api_version: str
+ ):
+ inputs = _make_inputs(schema_name, api_version=api_version)
manager = MagicMock(spec=ResumableSourceManager)
with patch(
@@ -83,17 +130,21 @@ class TestTrunkIoSource:
mock_transport.assert_called_once()
assert response.name == schema_name
- def test_source_for_pipeline_unknown_endpoint_raises(self):
- inputs = _make_inputs("NotARealEndpoint")
+ @parameterized.expand(
+ [
+ ("unknown", "NotARealEndpoint", "v2"),
+ ("v2_table_on_v1_pin", "TestCollections", "v1"),
+ ("v2_tests_on_v1_pin", "Tests", "v1"),
+ ]
+ )
+ def test_source_for_pipeline_rejects_tables_the_pin_does_not_serve(
+ self, _label: str, schema_name: str, api_version: str
+ ):
+ inputs = _make_inputs(schema_name, api_version=api_version)
manager = MagicMock(spec=ResumableSourceManager)
- try:
+ with pytest.raises(ValueError):
self.source.source_for_pipeline(self.config, manager, inputs)
- raised = False
- except ValueError:
- raised = True
-
- assert raised
@parameterized.expand(
[
@@ -101,6 +152,8 @@ class TestTrunkIoSource:
("QuarantinedTests", ["name", "parent", "file", "classname", "variant"]),
("FailingTests", ["id"]),
("MergeQueuePullRequests", ["id"]),
+ ("TestCollections", ["id"]),
+ ("Tests", ["id"]),
]
)
def test_source_for_pipeline_primary_keys(self, schema_name: str, expected_keys: list[str]):
@@ -111,6 +164,8 @@ class TestTrunkIoSource:
"QuarantinedTests": "quarantined_tests",
"FailingTests": "failing_tests",
"MergeQueuePullRequests": "merge_queue_pull_requests",
+ "TestCollections": "list_test_collections",
+ "Tests": "list_tests",
}[schema_name]
with patch(
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.py
index ceebee16d9a9..1bfa6cba9ad5 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
@@ -7,8 +7,14 @@ from dateutil import parser as date_parser
from requests import Request, RequestException, Response
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
+ APIKeyAuth,
+ BearerTokenAuth,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ JSONResponseCursorPaginator,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.settings import (
@@ -18,6 +24,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.s
MERGE_QUEUE_PAGE_SIZE,
PAGE_SIZE,
UNHEALTHY_STATUSES,
+ V2_BASE_URL,
+ V2_PAGE_SIZE,
)
@@ -157,6 +165,18 @@ def _client(api_token: str) -> RESTClient:
)
+def _v2_client(api_token: str) -> RESTClient:
+ # v2 takes the same token as an `Authorization: Bearer` organization API key. Redirects stay
+ # off for the same reason as `_client`.
+ return RESTClient(
+ base_url=V2_BASE_URL,
+ auth=BearerTokenAuth(token=api_token),
+ allowed_hosts=[],
+ allow_redirects=False,
+ request_timeout=(10.0, 60.0),
+ )
+
+
def _coerce_datetime(value: Any) -> datetime:
if isinstance(value, datetime):
return value if value.tzinfo else value.replace(tzinfo=UTC)
@@ -345,6 +365,48 @@ def merge_queue_pull_requests(
resumable_source_manager.clear_state()
+def _v2_list(
+ api_token: str,
+ path: str,
+ resumable_source_manager: ResumableSourceManager[TrunkIoResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ client = _v2_client(api_token)
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ def checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(TrunkIoResumeConfig(cursor=str(state["cursor"])))
+
+ for page in client.paginate(
+ path=path,
+ method="get",
+ params={"limit": V2_PAGE_SIZE},
+ paginator=JSONResponseCursorPaginator(cursor_path="nextCursor", cursor_param="cursor"),
+ data_selector="data",
+ resume_hook=checkpoint,
+ initial_paginator_state={"cursor": resume.cursor} if resume and resume.cursor else None,
+ ):
+ if page:
+ yield page
+
+ resumable_source_manager.clear_state()
+
+
+def list_test_collections(
+ api_token: str,
+ resumable_source_manager: ResumableSourceManager[TrunkIoResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ return _v2_list(api_token, "/v2/test-collections", resumable_source_manager)
+
+
+def list_tests(
+ api_token: str,
+ resumable_source_manager: ResumableSourceManager[TrunkIoResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ # No `testCollectionId` filter, so this lists tests across every collection in the org.
+ return _v2_list(api_token, "/v2/tests", resumable_source_manager)
+
+
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: