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(data-warehouse): add Trunk.io source (#73206)

Tom Owers23b733810517
diff --git a/frontend/public/services/trunk_io.png b/frontend/public/services/trunk_io.png
index 5759012ed509..4def0587989d 100644
Binary files a/frontend/public/services/trunk_io.png and b/frontend/public/services/trunk_io.png differ
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 042b062fd81e..eaa6f29f1642 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -580,6 +580,7 @@ the row lists both.
| trello | HTTP | requests | ✅ |
| tremendous | HTTP | requests | ✅ |
| trigger_dev | HTTP | requests | ✅ |
+| trunk_io | HTTP | requests + `rest_source.RESTClient` | ✅ |
| tvmaze | HTTP | requests + `rest_source.RESTClient` | ✅ |
| twelve_data | HTTP | requests | ✅ |
| twelve_labs | HTTP | requests | ✅ |
@@ -1335,7 +1336,6 @@ doesn't conflict with concurrent PRs.
- track_pms
- transistor
- tremendous
-- trunk_io
- trustpilot
- trustradius
- turso
diff --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.py
index 4af4fefa75b5..bd405c9a7ba0 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
@@ -6,4 +6,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class TrunkIoSourceConfig(config.Config):
- pass
+ api_token: str
+ org_url_slug: str
+ repo_host: str
+ repo_owner: str
+ repo_name: str
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
new file mode 100644
index 000000000000..7b2d31409484
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/canonical_descriptions.py
@@ -0,0 +1,67 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_FLAKY_TESTS_DOCS_URL = "https://docs.trunk.io/flaky-tests/api"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "UnhealthyTests": {
+ "description": "Tests Trunk currently considers flaky or broken, combining the `FLAKY` and `BROKEN` status filters.",
+ "docs_url": _FLAKY_TESTS_DOCS_URL,
+ "columns": {
+ "id": "A stable unique identifier for the test.",
+ "repository": "The repository the test belongs to.",
+ "html_url": "The URL of the test details page in the Trunk app.",
+ "name": "The name of the test.",
+ "variant": "The name of the test variant.",
+ "status": "The test's current status: value (healthy/flaky/broken), reason, and the timestamp of the last status change.",
+ "file_path": "The file path of the test.",
+ "parent": "The parent of the test, including the test suite depending on the test runner.",
+ "classname": "The class name of the test.",
+ "codeowners": "Code owners for the test.",
+ "pull_requests_impacted_last_7d": "The number of pull requests impacted by this test in the last 7 days.",
+ "quarantined": "Whether the test is currently quarantined.",
+ "ticket": "The ticket linked to this test case, if any.",
+ },
+ },
+ "QuarantinedTests": {
+ "description": "Tests currently quarantined (failures suppressed so CI still passes) in this repository.",
+ "docs_url": _FLAKY_TESTS_DOCS_URL,
+ "columns": {
+ "name": "The name of the test case.",
+ "parent": "The parent of the test case.",
+ "file": "The file of the test case.",
+ "classname": "The class name of the test case.",
+ "status": "The status of the test case (HEALTHY/FLAKY/BROKEN).",
+ "codeowners": "The latest code owners of the test case.",
+ "quarantine_setting": "Why the test is quarantined (ALWAYS_QUARANTINE or AUTO_QUARANTINE).",
+ "quarantined_at": "The time the test case was quarantined.",
+ "status_last_updated_at": "The last time the test case's status was updated.",
+ "test_case_id": "An identifier for the test case. Not guaranteed to be stable over time.",
+ "variant": "The variant of the test case.",
+ },
+ },
+ "FailingTests": {
+ "description": "Distinct tests that failed at least once within a given time window.",
+ "docs_url": _FLAKY_TESTS_DOCS_URL,
+ "columns": {
+ "id": "A stable unique identifier for the test.",
+ "repository": "The repository the test belongs to.",
+ "html_url": "The URL of the test details page in the Trunk app.",
+ "name": "The name of the test.",
+ "variant": "The name of the test variant.",
+ "status": "The test's current status: value (healthy/flaky/broken), reason, and the timestamp of the last status change.",
+ "most_common_failures": "The most common failure summaries for this test, with occurrence counts.",
+ "failure_rate_last_7d": "The failure rate over the last 7 days.",
+ "failure_rate_last_24h": "The failure rate over the last 24 hours.",
+ "file_path": "The file path of the test.",
+ "parent": "The parent of the test, including the test suite depending on the test runner.",
+ "classname": "The class name of the test.",
+ "codeowners": "Code owners for the test.",
+ "pull_requests_impacted_last_7d": "The number of pull requests impacted by this test in the last 7 days.",
+ "quarantined": "Whether the test is currently quarantined.",
+ "ticket": "The ticket linked to this test case, if any.",
+ "synced_through": "PostHog-added: the end of the time window this row was synced 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.py
new file mode 100644
index 000000000000..a534532c9b24
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/settings.py
@@ -0,0 +1,47 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+BASE_URL = "https://api.trunk.io/v1"
+
+# 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.
+PAGE_SIZE = 100
+
+# `list-unhealthy-tests` requires a single `status` filter per call, so the "unhealthy tests"
+# table is built by walking both statuses and merging the results.
+UNHEALTHY_STATUSES = ("FLAKY", "BROKEN")
+
+# `list-failing-tests` enforces a <=7 day start_time/end_time window per call, so a full sync
+# walks forward in fixed windows. There is no per-row "modified since" field, so this default
+# lookback bounds the first sync's backfill depth; later syncs continue from the last
+# completed window (see `synced_through` below) instead of re-walking from this point again.
+FAILING_TESTS_WINDOW_DAYS = 7
+FAILING_TESTS_DEFAULT_LOOKBACK_DAYS = 30
+
+ENDPOINTS = (
+ "UnhealthyTests",
+ "QuarantinedTests",
+ "FailingTests",
+)
+
+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.",
+}
+
+PRIMARY_KEYS: dict[str, list[str]] = {
+ "UnhealthyTests": ["id"],
+ # Quarantined tests carry no stable id (`test_case_id` is explicitly documented as
+ # unstable), so the natural key is the tuple that identifies the test case itself.
+ "QuarantinedTests": ["name", "parent", "file", "classname", "variant"],
+ "FailingTests": ["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.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "FailingTests": [incremental_field("synced_through", IncrementalFieldType.DateTime)],
+}
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 dba867bd37b5..aadef935ab2c 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
@@ -1,32 +1,189 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.trunkio import (
TrunkIoSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.settings import (
+ DESCRIPTIONS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PRIMARY_KEYS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.trunk_io import (
+ TrunkIoResumeConfig,
+ TrunkRepo,
+ failing_tests,
+ quarantined_tests,
+ unhealthy_tests,
+ validate_credentials as validate_trunk_io_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TrunkIoSource(SimpleSource[TrunkIoSourceConfig]):
+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"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TRUNKIO
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ 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.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: TrunkIoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, descriptions=DESCRIPTIONS)
+
+ def validate_credentials(
+ self,
+ config: TrunkIoSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ 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)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TrunkIoResumeConfig]:
+ return ResumableSourceManager[TrunkIoResumeConfig](inputs, TrunkIoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TrunkIoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[TrunkIoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ repo = TrunkRepo(host=config.repo_host, owner=config.repo_owner, name=config.repo_name)
+ endpoint = inputs.schema_name
+
+ if endpoint == "UnhealthyTests":
+ items = unhealthy_tests(config.api_token, repo, config.org_url_slug, resumable_source_manager)
+ elif endpoint == "QuarantinedTests":
+ items = quarantined_tests(config.api_token, repo, config.org_url_slug, resumable_source_manager)
+ elif endpoint == "FailingTests":
+ items = failing_tests(
+ config.api_token,
+ repo,
+ config.org_url_slug,
+ 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}")
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: items,
+ primary_keys=PRIMARY_KEYS[endpoint],
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
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.
+
+Supported tables:
+- `UnhealthyTests`
+- `QuarantinedTests`
+- `FailingTests`
+
+Create an API token in the Trunk app under Settings > Organization > General > API.
+""",
+ docsUrl="https://posthog.com/docs/cdp/sources/trunk-io",
iconPath="/static/services/trunk_io.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="org_url_slug",
+ label="Organization slug",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my-trunk-org-slug",
+ secret=False,
+ caption='Find this at https://app.trunk.io/trunk/settings under "Organization Name" > "Slug".',
+ ),
+ SourceFieldInputConfig(
+ name="repo_host",
+ label="Repository host",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="github.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="repo_owner",
+ label="Repository owner",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my-github-org",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="repo_name",
+ label="Repository name",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my-repo",
+ secret=False,
+ ),
+ ],
+ ),
+ 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.py
new file mode 100644
index 000000000000..822ac8fe2c0d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io.py
@@ -0,0 +1,470 @@
+import json
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from requests import Request, RequestException, Response
+
+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 (
+ FAILING_TESTS_DEFAULT_LOOKBACK_DAYS,
+ FAILING_TESTS_WINDOW_DAYS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.trunk_io import (
+ TrunkIoResumeConfig,
+ TrunkPageQueryPaginator,
+ TrunkRepo,
+ failing_tests,
+ quarantined_tests,
+ unhealthy_tests,
+ validate_credentials,
+)
+
+REPO = TrunkRepo(host="github.com", owner="my-org", name="my-repo")
+MAKE_SESSION_TARGET = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+
+
+def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _make_redirect_response(location: str, status_code: int = 302) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp.headers["Location"] = location
+ resp._content = b""
+ return resp
+
+
+def _page(next_page_token: str = "") -> dict[str, Any]:
+ return {
+ "total_rows": 1,
+ "total_pages": 1,
+ "next_page_token": next_page_token,
+ "prev_page_token": "",
+ "last_page_token": "",
+ "page_index": 0,
+ }
+
+
+class TestTrunkPageQueryPaginator:
+ def test_init_request_seeds_page_query(self) -> None:
+ paginator = TrunkPageQueryPaginator(page_size=50, page_token="")
+ request = Request(method="POST", url="https://api.trunk.io/v1/flaky-tests/list-quarantined-tests")
+ paginator.init_request(request)
+ assert request.json["page_query"] == {"page_size": 50, "page_token": ""}
+
+ @parameterized.expand(
+ [
+ ("has_next", "next-token", True),
+ ("empty_string_token", "", False),
+ ("missing_page", None, False),
+ ]
+ )
+ def test_update_state(self, _label: str, next_token: Optional[str], expected_has_next: bool) -> None:
+ paginator = TrunkPageQueryPaginator()
+ response = MagicMock()
+ response.json.return_value = {"page": _page(next_token)} if next_token is not None else {}
+ paginator.update_state(response)
+
+ assert paginator.has_next_page is expected_has_next
+ if expected_has_next:
+ assert paginator.page_token == next_token
+
+ def test_get_resume_state_round_trip(self) -> None:
+ paginator = TrunkPageQueryPaginator()
+ response = MagicMock()
+ response.json.return_value = {"page": _page("cursor-1")}
+ paginator.update_state(response)
+
+ state = paginator.get_resume_state()
+ assert state == {"page_token": "cursor-1"}
+
+ resumed = TrunkPageQueryPaginator()
+ resumed.set_resume_state(state)
+ assert resumed.page_token == "cursor-1"
+ assert resumed.has_next_page is True
+
+ def test_get_resume_state_none_on_terminal_page(self) -> None:
+ paginator = TrunkPageQueryPaginator()
+ response = MagicMock()
+ response.json.return_value = {"page": _page("")}
+ paginator.update_state(response)
+
+ assert paginator.get_resume_state() is None
+
+ def test_set_resume_state_ignores_missing_token(self) -> None:
+ paginator = TrunkPageQueryPaginator()
+ paginator.set_resume_state({})
+ assert paginator.page_token == ""
+
+
+def _drive_session(responses: list[Response]) -> tuple[Any, list[dict[str, Any]]]:
+ """Patch the tracked session so `RESTClient.paginate` runs against canned responses.
+
+ Returns the mock session and the list of JSON bodies sent (captured at send-time, since
+ the paginator mutates the same Request object in place between pages).
+ """
+ sent_bodies: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_bodies.append(json.loads(json.dumps(request.json)))
+ return next(response_iter)
+
+ patcher = patch(MAKE_SESSION_TARGET)
+ mock_make_session = patcher.start()
+ mock_session = mock_make_session.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+ return patcher, sent_bodies
+
+
+class TestUnhealthyTests:
+ def test_fresh_run_walks_both_statuses(self) -> None:
+ patcher, sent_bodies = _drive_session(
+ [
+ _make_http_response({"tests": [{"id": "flaky-1"}], "page": _page("")}),
+ _make_http_response({"tests": [{"id": "broken-1"}], "page": _page("")}),
+ ]
+ )
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ pages = list(unhealthy_tests("token", REPO, "my-org", manager))
+ finally:
+ patcher.stop()
+
+ assert pages == [[{"id": "flaky-1"}], [{"id": "broken-1"}]]
+ assert [body["status"] for body in sent_bodies] == ["FLAKY", "BROKEN"]
+ manager.clear_state.assert_called_once()
+
+ def test_resume_skips_completed_status(self) -> None:
+ patcher, sent_bodies = _drive_session(
+ [
+ _make_http_response({"tests": [{"id": "broken-resumed"}], "page": _page("")}),
+ ]
+ )
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = TrunkIoResumeConfig(status="BROKEN", page_token="")
+
+ pages = list(unhealthy_tests("token", REPO, "my-org", manager))
+ finally:
+ patcher.stop()
+
+ assert pages == [[{"id": "broken-resumed"}]]
+ assert [body["status"] for body in sent_bodies] == ["BROKEN"]
+
+ def test_resume_seeds_page_token_mid_status(self) -> None:
+ patcher, sent_bodies = _drive_session(
+ [
+ _make_http_response({"tests": [{"id": "flaky-2"}], "page": _page("")}),
+ _make_http_response({"tests": [{"id": "broken-1"}], "page": _page("")}),
+ ]
+ )
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = TrunkIoResumeConfig(status="FLAKY", page_token="cursor-mid")
+
+ list(unhealthy_tests("token", REPO, "my-org", manager))
+ finally:
+ patcher.stop()
+
+ assert sent_bodies[0]["page_query"]["page_token"] == "cursor-mid"
+ # Second status always starts fresh regardless of the seeded token.
+ assert sent_bodies[1]["page_query"]["page_token"] == ""
+
+ def test_saves_state_after_each_non_terminal_page(self) -> None:
+ patcher, _ = _drive_session(
+ [
+ _make_http_response({"tests": [{"id": "flaky-1"}], "page": _page("cursor-1")}),
+ _make_http_response({"tests": [{"id": "flaky-2"}], "page": _page("")}),
+ _make_http_response({"tests": [{"id": "broken-1"}], "page": _page("")}),
+ ]
+ )
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ list(unhealthy_tests("token", REPO, "my-org", manager))
+ finally:
+ patcher.stop()
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [TrunkIoResumeConfig(status="FLAKY", page_token="cursor-1")]
+
+
+class TestQuarantinedTests:
+ def test_fresh_run_sends_no_seeded_token(self) -> None:
+ patcher, sent_bodies = _drive_session(
+ [_make_http_response({"quarantined_tests": [{"name": "test_a"}], "page": _page("")})]
+ )
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ pages = list(quarantined_tests("token", REPO, "my-org", manager))
+ finally:
+ patcher.stop()
+
+ assert pages == [[{"name": "test_a"}]]
+ assert sent_bodies[0]["page_query"]["page_token"] == ""
+ assert "status" not in sent_bodies[0]
+ manager.clear_state.assert_called_once()
+
+ def test_resume_seeds_saved_page_token(self) -> None:
+ patcher, sent_bodies = _drive_session(
+ [_make_http_response({"quarantined_tests": [{"name": "test_b"}], "page": _page("")})]
+ )
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = TrunkIoResumeConfig(page_token="cursor-resumed")
+
+ list(quarantined_tests("token", REPO, "my-org", manager))
+ finally:
+ patcher.stop()
+
+ assert sent_bodies[0]["page_query"]["page_token"] == "cursor-resumed"
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ patcher, _ = _drive_session([_make_http_response({"quarantined_tests": [], "page": _page("")})])
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ list(quarantined_tests("token", REPO, "my-org", manager))
+ finally:
+ patcher.stop()
+
+ manager.load_state.assert_not_called()
+
+
+class TestFailingTests:
+ @freeze_time("2024-06-15T00:00:00Z")
+ def test_fresh_run_defaults_to_lookback_window(self) -> None:
+ # The 30-day default lookback is walked in 7-day windows, so a fresh run issues
+ # several requests before reaching "now" — only the first row matters here.
+ responses = [_make_http_response({"tests": [{"id": "f-1"}], "page": _page("")})] + [
+ _make_http_response({"tests": [], "page": _page("")}) for _ in range(9)
+ ]
+ patcher, sent_bodies = _drive_session(responses)
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ pages = list(
+ failing_tests(
+ "token",
+ REPO,
+ "my-org",
+ manager,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ )
+ finally:
+ patcher.stop()
+
+ now = datetime(2024, 6, 15, tzinfo=UTC)
+ expected_start = now - timedelta(days=FAILING_TESTS_DEFAULT_LOOKBACK_DAYS)
+ assert sent_bodies[0]["start_time"] == expected_start.strftime("%Y-%m-%dT%H:%M:%SZ")
+ # Row gets a `synced_through` cursor stamped on it for incremental watermarking.
+ assert pages[0][0]["synced_through"] == sent_bodies[0]["end_time"]
+
+ @freeze_time("2024-06-15T00:00:00Z")
+ def test_incremental_run_starts_from_last_value(self) -> None:
+ # 2024-06-01 -> 2024-06-15 is 14 days, walked in two 7-day windows.
+ last_value = "2024-06-01T00:00:00Z"
+ responses = [_make_http_response({"tests": [], "page": _page("")}) for _ in range(2)]
+ patcher, sent_bodies = _drive_session(responses)
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ list(
+ failing_tests(
+ "token",
+ REPO,
+ "my-org",
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=last_value,
+ )
+ )
+ finally:
+ patcher.stop()
+
+ assert sent_bodies[0]["start_time"] == last_value
+
+ @freeze_time("2024-06-15T00:00:00Z")
+ def test_window_capped_at_seven_days(self) -> None:
+ last_value = "2024-01-01T00:00:00Z"
+ patcher, sent_bodies = _drive_session(
+ [_make_http_response({"tests": [], "page": _page("")}) for _ in range(30)]
+ )
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ list(
+ failing_tests(
+ "token",
+ REPO,
+ "my-org",
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=last_value,
+ )
+ )
+ finally:
+ patcher.stop()
+
+ first_start = datetime.strptime(sent_bodies[0]["start_time"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)
+ first_end = datetime.strptime(sent_bodies[0]["end_time"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)
+ assert (first_end - first_start).days == FAILING_TESTS_WINDOW_DAYS
+
+ @freeze_time("2024-06-15T00:00:00Z")
+ def test_resume_seeds_window_and_page_token(self) -> None:
+ patcher, sent_bodies = _drive_session([_make_http_response({"tests": [{"id": "f-2"}], "page": _page("")})])
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = TrunkIoResumeConfig(
+ window_start="2024-06-10T00:00:00+00:00", page_token="cursor-mid"
+ )
+
+ list(
+ failing_tests(
+ "token",
+ REPO,
+ "my-org",
+ manager,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ )
+ finally:
+ patcher.stop()
+
+ assert sent_bodies[0]["start_time"] == "2024-06-10T00:00:00Z"
+ assert sent_bodies[0]["page_query"]["page_token"] == "cursor-mid"
+
+ @freeze_time("2024-06-15T00:00:00Z")
+ def test_terminates_once_window_reaches_now(self) -> None:
+ # Seed exactly at "now" so the walk loop must not fire a single request.
+ patcher, sent_bodies = _drive_session([])
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = TrunkIoResumeConfig(window_start="2024-06-15T00:00:00+00:00")
+
+ pages = list(
+ failing_tests(
+ "token",
+ REPO,
+ "my-org",
+ manager,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ )
+ finally:
+ patcher.stop()
+
+ assert pages == []
+ assert sent_bodies == []
+ manager.clear_state.assert_called_once()
+
+
+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
+ # `requests` wouldn't strip off-origin, so following the redirect would replay the token.
+ sent_bodies: list[dict[str, Any]] = []
+
+ def fake_send(request: Any, *_args: Any, **kwargs: Any) -> Response:
+ sent_bodies.append(json.loads(json.dumps(request.json)))
+ # The client must not ask the transport to follow redirects itself.
+ assert kwargs.get("allow_redirects") is False
+ return _make_redirect_response("https://evil.example.com/steal")
+
+ patcher = patch(MAKE_SESSION_TARGET)
+ mock_make_session = patcher.start()
+ mock_session = mock_make_session.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+ try:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ with pytest.raises(ValueError, match="[Rr]edirect"):
+ list(quarantined_tests("token", REPO, "my-org", manager))
+ finally:
+ patcher.stop()
+
+ # Exactly one request went out (to the API host); the redirect target was never called.
+ assert len(sent_bodies) == 1
+
+
+class TestValidateCredentials:
+ def test_credential_check_disables_redirects(self) -> None:
+ # Redirects off keeps the token from leaking to a redirect target during validation.
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.trunk_io.make_tracked_session"
+ ) as mock_make_session:
+ mock_session = mock_make_session.return_value
+ mock_session.post.return_value = _make_http_response({}, status_code=200)
+
+ validate_credentials("token", "my-org", REPO)
+
+ assert mock_make_session.call_args.kwargs["allow_redirects"] is False
+
+ @parameterized.expand(
+ [
+ (200, True, None),
+ (
+ 401,
+ False,
+ "Trunk.io authentication failed. Check your API token, organization slug, and repository details.",
+ ),
+ (500, False, "Trunk.io API returned HTTP 500."),
+ ]
+ )
+ def test_status_code_mapping(self, status_code: int, expected_ok: bool, expected_error: Optional[str]) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.trunk_io.make_tracked_session"
+ ) as mock_make_session:
+ mock_session = mock_make_session.return_value
+ mock_session.post.return_value = _make_http_response({}, status_code=status_code)
+
+ ok, error = validate_credentials("token", "my-org", REPO)
+
+ assert ok is expected_ok
+ assert error == expected_error
+
+ def test_network_error_is_reported(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.trunk_io.make_tracked_session"
+ ) as mock_make_session:
+ mock_session = mock_make_session.return_value
+ mock_session.post.side_effect = RequestException("boom")
+
+ ok, error = validate_credentials("token", "my-org", REPO)
+
+ assert ok is False
+ assert error is not None and "boom" in error
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
new file mode 100644
index 000000000000..1f987442272d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/tests/test_trunk_io_source.py
@@ -0,0 +1,171 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.trunkio import (
+ TrunkIoSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.source import TrunkIoSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.trunk_io import TrunkIoResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(schema_name: str, **overrides) -> SourceInputs:
+ defaults: dict = {
+ "schema_name": schema_name,
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestTrunkIoSource:
+ def setup_method(self):
+ self.source = TrunkIoSource()
+ self.team_id = 123
+ self.config = TrunkIoSourceConfig(
+ api_token="test-token",
+ org_url_slug="my-org",
+ repo_host="github.com",
+ repo_owner="my-org",
+ repo_name="my-repo",
+ )
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.TRUNKIO
+
+ def test_lists_tables_without_credentials(self):
+ # get_schemas is a static endpoint catalog with no I/O, so it must be safe for public docs.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_source_config_is_released(self):
+ config = self.source.get_source_config
+ assert getattr(config, "unreleasedSource", None) is not True
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ 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"]
+
+ 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")
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.secret is True
+
+ 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"}
+
+ def test_get_schemas_filters_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["QuarantinedTests"])
+ assert [s.name for s in schemas] == ["QuarantinedTests"]
+
+ @parameterized.expand(
+ [
+ ("UnhealthyTests", False),
+ ("QuarantinedTests", False),
+ ("FailingTests", True),
+ ]
+ )
+ def test_get_schemas_incremental_support(self, endpoint: str, supports_incremental: bool):
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ assert schema.supports_incremental is supports_incremental
+
+ def test_validate_credentials_delegates_with_repo(self):
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.source.validate_trunk_io_credentials"
+ ) as mock_validate:
+ mock_validate.return_value = (True, None)
+ result = self.source.validate_credentials(self.config, self.team_id)
+
+ assert result == (True, None)
+ (api_token, org_url_slug, repo), _ = mock_validate.call_args.args, mock_validate.call_args.kwargs
+ assert api_token == "test-token"
+ assert org_url_slug == "my-org"
+ assert repo.host == "github.com"
+ assert repo.owner == "my-org"
+ assert repo.name == "my-repo"
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = _make_inputs("UnhealthyTests")
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is TrunkIoResumeConfig
+
+ @parameterized.expand(
+ [
+ ("UnhealthyTests", "unhealthy_tests"),
+ ("QuarantinedTests", "quarantined_tests"),
+ ("FailingTests", "failing_tests"),
+ ]
+ )
+ def test_source_for_pipeline_dispatches_to_expected_transport(self, schema_name: str, transport_fn: str):
+ inputs = _make_inputs(schema_name)
+ manager = MagicMock(spec=ResumableSourceManager)
+
+ with patch(
+ f"products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.source.{transport_fn}"
+ ) as mock_transport:
+ mock_transport.return_value = iter([])
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_transport.assert_called_once()
+ assert response.name == schema_name
+
+ def test_source_for_pipeline_unknown_endpoint_raises(self):
+ inputs = _make_inputs("NotARealEndpoint")
+ manager = MagicMock(spec=ResumableSourceManager)
+
+ try:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+ raised = False
+ except ValueError:
+ raised = True
+
+ assert raised
+
+ @parameterized.expand(
+ [
+ ("UnhealthyTests", ["id"]),
+ ("QuarantinedTests", ["name", "parent", "file", "classname", "variant"]),
+ ("FailingTests", ["id"]),
+ ]
+ )
+ def test_source_for_pipeline_primary_keys(self, schema_name: str, expected_keys: list[str]):
+ inputs = _make_inputs(schema_name)
+ manager = MagicMock(spec=ResumableSourceManager)
+ transport_fn = {
+ "UnhealthyTests": "unhealthy_tests",
+ "QuarantinedTests": "quarantined_tests",
+ "FailingTests": "failing_tests",
+ }[schema_name]
+
+ with patch(
+ f"products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.source.{transport_fn}"
+ ) as mock_transport:
+ mock_transport.return_value = iter([])
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ assert response.primary_keys == expected_keys
+
+ 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"}
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
new file mode 100644
index 000000000000..a4511a4551df
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/trunk_io.py
@@ -0,0 +1,273 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional
+
+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.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 (
+ BASE_URL,
+ FAILING_TESTS_DEFAULT_LOOKBACK_DAYS,
+ FAILING_TESTS_WINDOW_DAYS,
+ PAGE_SIZE,
+ UNHEALTHY_STATUSES,
+)
+
+
+class TrunkIoResumeConfig:
+ """Unified resume shape for every Trunk endpoint. Each `source_for_pipeline` call gets its
+ own resumable-source-manager key (namespaced by job id), so only the fields relevant to the
+ endpoint being synced are ever populated."""
+
+ page_token: str = ""
+ status: Optional[str] = None
+ window_start: Optional[str] = None
+
+
+class TrunkRepo:
+ host: str
+ owner: str
+ name: str
+
+ def as_dict(self) -> dict[str, str]:
+ return {"host": self.host, "owner": self.owner, "name": self.name}
+
+
+class TrunkPageQueryPaginator(BasePaginator):
+ """Trunk paginates via a nested `page_query: {page_size, page_token}` object in the POST
+ body rather than a top-level query/json param, so the shared param-injection paginators
+ (`JSONResponseCursorPaginator` et al.) don't apply directly."""
+
+ def __init__(self, page_size: int = PAGE_SIZE, page_token: str = "") -> None:
+ super().__init__()
+ self.page_size = page_size
+ self.page_token = page_token
+ if page_token:
+ 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["page_query"] = {"page_size": self.page_size, "page_token": self.page_token}
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ try:
+ page = response.json().get("page") or {}
+ except Exception:
+ page = {}
+ next_token = page.get("next_page_token") or ""
+ if next_token:
+ self.page_token = next_token
+ self._has_next_page = True
+ else:
+ self._has_next_page = False
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"page_token": self.page_token} if self._has_next_page else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ token = state.get("page_token")
+ if token:
+ self.page_token = token
+ self._has_next_page = True
+
+ def __str__(self) -> str:
+ return f"TrunkPageQueryPaginator(page_token={self.page_token!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
+ # from the API host would otherwise replay the credential to the redirect target.
+ return RESTClient(
+ base_url=BASE_URL,
+ auth=APIKeyAuth(api_key=api_token, name="x-api-token", location="header"),
+ allowed_hosts=[],
+ allow_redirects=False,
+ )
+
+
+def _coerce_datetime(value: Any) -> datetime:
+ if isinstance(value, datetime):
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+ return date_parser.parse(str(value)).astimezone(UTC)
+
+
+def _format_rfc3339(value: datetime) -> str:
+ return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def unhealthy_tests(
+ api_token: str,
+ repo: TrunkRepo,
+ org_url_slug: str,
+ resumable_source_manager: ResumableSourceManager[TrunkIoResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ client = _client(api_token)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_index = 0
+ seed_token = ""
+ if resume and resume.status in UNHEALTHY_STATUSES:
+ start_index = UNHEALTHY_STATUSES.index(resume.status)
+ seed_token = resume.page_token or ""
+
+ for index, status in enumerate(UNHEALTHY_STATUSES[start_index:], start=start_index):
+ page_token = seed_token if index == start_index else ""
+ paginator = TrunkPageQueryPaginator(page_token=page_token)
+ body = {"repo": repo.as_dict(), "org_url_slug": org_url_slug, "status": status}
+
+ def checkpoint(state: Optional[dict[str, Any]], _status: str = status) -> None:
+ # `RESTClient.paginate` deep-copies the paginator it's given, so this hook (fed the
+ # deep-copied paginator's own resume state) is the only reliable way to observe
+ # pagination progress — reading back the outer `paginator` variable would see a
+ # stale, never-mutated copy.
+ if state and state.get("page_token"):
+ resumable_source_manager.save_state(
+ TrunkIoResumeConfig(status=_status, page_token=str(state["page_token"]))
+ )
+
+ for page in client.paginate(
+ path="/flaky-tests/list-unhealthy-tests",
+ method="post",
+ json=body,
+ paginator=paginator,
+ data_selector="tests",
+ resume_hook=checkpoint,
+ ):
+ if page:
+ yield page
+
+ resumable_source_manager.clear_state()
+
+
+def quarantined_tests(
+ api_token: str,
+ repo: TrunkRepo,
+ org_url_slug: str,
+ resumable_source_manager: ResumableSourceManager[TrunkIoResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ client = _client(api_token)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page_token = resume.page_token if resume else ""
+ paginator = TrunkPageQueryPaginator(page_token=page_token)
+ body = {"repo": repo.as_dict(), "org_url_slug": org_url_slug}
+
+ def checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("page_token"):
+ resumable_source_manager.save_state(TrunkIoResumeConfig(page_token=str(state["page_token"])))
+
+ for page in client.paginate(
+ path="/flaky-tests/list-quarantined-tests",
+ method="post",
+ json=body,
+ paginator=paginator,
+ data_selector="quarantined_tests",
+ resume_hook=checkpoint,
+ ):
+ if page:
+ yield page
+
+ resumable_source_manager.clear_state()
+
+
+def failing_tests(
+ api_token: str,
+ repo: TrunkRepo,
+ org_url_slug: 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)
+ now = datetime.now(UTC)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume and resume.window_start:
+ window_start = _coerce_datetime(resume.window_start)
+ page_token = resume.page_token or ""
+ else:
+ if should_use_incremental_field and db_incremental_field_last_value:
+ window_start = _coerce_datetime(db_incremental_field_last_value)
+ else:
+ window_start = now - timedelta(days=FAILING_TESTS_DEFAULT_LOOKBACK_DAYS)
+ page_token = ""
+
+ while window_start < now:
+ window_end = min(window_start + timedelta(days=FAILING_TESTS_WINDOW_DAYS), now)
+ synced_through = _format_rfc3339(window_end)
+ paginator = TrunkPageQueryPaginator(page_token=page_token)
+ body = {
+ "repo": repo.as_dict(),
+ "org_url_slug": org_url_slug,
+ "start_time": _format_rfc3339(window_start),
+ "end_time": synced_through,
+ }
+
+ def checkpoint(state: Optional[dict[str, Any]], _window_start: datetime = window_start) -> None:
+ if state and state.get("page_token"):
+ resumable_source_manager.save_state(
+ TrunkIoResumeConfig(window_start=_window_start.isoformat(), page_token=str(state["page_token"]))
+ )
+
+ for page in client.paginate(
+ path="/flaky-tests/list-failing-tests",
+ method="post",
+ json=body,
+ paginator=paginator,
+ data_selector="tests",
+ resume_hook=checkpoint,
+ ):
+ if page:
+ # Stamp the window boundary onto each row: there is no per-row "modified since"
+ # field, so this is what lets the pipeline's incremental watermark advance.
+ for row in page:
+ row["synced_through"] = synced_through
+ yield page
+
+ window_start = window_end
+ page_token = ""
+ resumable_source_manager.save_state(TrunkIoResumeConfig(window_start=window_start.isoformat(), page_token=""))
+
+ 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:
+ response = session.post(
+ f"{BASE_URL}/flaky-tests/list-quarantined-tests",
+ headers={"x-api-token": api_token},
+ json={
+ "repo": repo.as_dict(),
+ "org_url_slug": org_url_slug,
+ "page_query": {"page_size": 1, "page_token": ""},
+ },
+ timeout=15,
+ )
+ except RequestException as e:
+ return False, f"Could not reach the Trunk.io API: {e}"
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return (
+ False,
+ "Trunk.io authentication failed. Check your API token, organization slug, and repository details.",
+ )
+ return False, f"Trunk.io API returned HTTP {response.status_code}."