: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): read trunk flaky-test tables from the v2 api (#124755)
Georges-Antoine Assi72ab5ed88cdd
diff --git a/.agents/skills/fixing-flaky-tests/SKILL.md b/.agents/skills/fixing-flaky-tests/SKILL.mdindex 40873faeda6c..f90b1b52413c 100644--- a/.agents/skills/fixing-flaky-tests/SKILL.md+++ b/.agents/skills/fixing-flaky-tests/SKILL.md@@ -81,19 +81,21 @@ hogli ci:insights search "<test name or error>" # cross-run history — corro### Corroborate with Trunk Flaky Tests-CI uploads test results to [Trunk Flaky Tests](https://app.trunk.io/posthog-inc/flaky-tests?repo=PostHog/posthog), which tracks per-test failure history across `master` and PR runs.-On a PR, the `trunk-io` bot's "Trunk Test Analytics" comment links that PR's slice (`https://app.trunk.io/posthog-inc/flaky-tests/pr/<number>?repo=PostHog/posthog`).+CI uploads test results to [Trunk Flaky Tests](https://app.trunk.io/posthog-inc/flaky-tests/collections), which tracks per-test failure history across `master` and PR runs.+It keeps one test collection per suite: backend-core `AA6dvTdI`, backend-product `C0LrorjW`, backend-temporal `smyQjxZ3`, frontend-jest `OZ6hVJ5z`, storybook `P3SjL3vy`, e2e-playwright `kF88Gx2u`, nodejs `ugvRjGsw`, rust `TewkWR1w`, mcp `Nt38b1Ej`.+A collection's page is `https://app.trunk.io/posthog-inc/flaky-tests/collections/<shortId>`, and a test's page is `…/collections/<shortId>/tests/<id>`.+A PR's page in Trunk is `https://app.trunk.io/posthog-inc/pull/<number>?repo=dcf9eb51-cf4b-4bdc-8bc1-a2040fdbe8f4`.+The Trunk browser extension also links to it from the GitHub PR view.The `trunk` MCP server in `.mcp.json` queries it (tools are marked experimental by Trunk):-- `search-test` (`repoName: "PostHog/posthog"`, `testNameSearch: "<test name, no filepath>"`) → the test case ID.+- `search-test` (`repoName: "PostHog/posthog"`, `testNameSearch: "<test name, no filepath>"`) → the test case ID. Add `testCollectionShortId` (one of the short IDs above) to search one collection, or leave it out to search all of them.- `fix-flaky-test` (`repoName`, `testCaseId`) → failure history, first-seen commit, git blame, and Trunk's root-cause investigation; `createNewInvestigation: true` triggers a fresh analysis (takes up to a minute).Authenticate once via `/mcp` → `trunk` (browser OAuth); headless environments instead add an `Authorization: Bearer` header with a `TRUNK_API_TOKEN` org token to the server entry.-Two limits worth knowing before you start here.AI investigations are not enabled for this repo, so `fix-flaky-test` returns history or nothing, never a root cause.-And lookup only goes name to ID: a bare dashboard link identifies a test you cannot name, so ask for the test name rather than guessing at the ID.+A bare collection test link still identifies the test: its last segment is the test's ID, which `GET /v2/tests/{testId}` accepts.Trunk attributes each test to a team through CODEOWNERS, which cannot express the `owners.yaml` map.`.github/scripts/trunk-codeowners.sh` projects the map into a generated CODEOWNERS before each upload (`hogli owners:codeowners` builds the same file locally), so a test's owner in Trunk should match `hogli owners:who`.diff --git a/.depot/actions/trunk-quarantine-gate/action.yml b/.depot/actions/trunk-quarantine-gate/action.ymlindex 1e76939d60b7..3c9183af8d0c 100644--- a/.depot/actions/trunk-quarantine-gate/action.yml+++ b/.depot/actions/trunk-quarantine-gate/action.yml@@ -39,9 +39,6 @@ runs:id: uploadcontinue-on-error: trueuses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2- env:- # Link to the repo view: a new collection has no history yet.- TRUNK_HIDE_TEST_COLLECTION_LINKS: 'true'with:junit-paths: ${{ inputs.junit-paths }}org-slug: posthog-inc@@ -68,8 +65,6 @@ runs:if: ${{ steps.upload.outcome == 'failure' && inputs.previous-step-outcome == 'success' }}continue-on-error: trueuses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2- env:- TRUNK_HIDE_TEST_COLLECTION_LINKS: 'true'with:junit-paths: ${{ inputs.junit-paths }}org-slug: posthog-incdiff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 792b389eb42a..de4f9935b68b 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -3886,8 +3886,6 @@ jobs:continue-on-error: trueif: ${{ !cancelled() && matrix.segment == 'Core' && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true' }}uses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2- env:- TRUNK_HIDE_TEST_COLLECTION_LINKS: 'true'with:junit-paths: junit-core.xml,junit-core-retry-failures.xmlorg-slug: posthog-inc@@ -3905,8 +3903,6 @@ jobs:continue-on-error: trueif: ${{ !cancelled() && matrix.segment == 'Temporal' && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true' }}uses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2- env:- TRUNK_HIDE_TEST_COLLECTION_LINKS: 'true'with:junit-paths: junit-temporal.xml,junit-temporal-retry-failures.xmlorg-slug: posthog-incdiff --git a/.github/actions/trunk-quarantine-gate/action.yml b/.github/actions/trunk-quarantine-gate/action.ymlindex 1e76939d60b7..3c9183af8d0c 100644--- a/.github/actions/trunk-quarantine-gate/action.yml+++ b/.github/actions/trunk-quarantine-gate/action.yml@@ -39,9 +39,6 @@ runs:id: uploadcontinue-on-error: trueuses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2- env:- # Link to the repo view: a new collection has no history yet.- TRUNK_HIDE_TEST_COLLECTION_LINKS: 'true'with:junit-paths: ${{ inputs.junit-paths }}org-slug: posthog-inc@@ -68,8 +65,6 @@ runs:if: ${{ steps.upload.outcome == 'failure' && inputs.previous-step-outcome == 'success' }}continue-on-error: trueuses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2- env:- TRUNK_HIDE_TEST_COLLECTION_LINKS: 'true'with:junit-paths: ${{ inputs.junit-paths }}org-slug: posthog-incdiff --git a/.github/workflows/ci-e2e-playwright.yml b/.github/workflows/ci-e2e-playwright.ymlindex 7130df7fac24..aecdf4631086 100644--- a/.github/workflows/ci-e2e-playwright.yml+++ b/.github/workflows/ci-e2e-playwright.yml@@ -1170,8 +1170,6 @@ jobs:continue-on-error: trueif: ${{ !cancelled() && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true' }}uses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2- env:- TRUNK_HIDE_TEST_COLLECTION_LINKS: 'true'with:junit-paths: playwright/junit-results.xmlorg-slug: posthog-incdiff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex d67d6e3eaece..8491e938bfc3 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -1314,7 +1314,7 @@2 products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/reddit_ads.py2 products/warehouse_sources/backend/temporal/data_imports/sources/servicenow/servicenow.py2 products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py-2 products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/trunk_io.py+1 products/warehouse_sources/backend/temporal/data_imports/sources/trunk_io/trunk_io.py2 products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py2 products/web_analytics/backend/path_cleaning_suggestions/service.py22 products/batch_exports/backend/service.pydiff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex 972fbc6b483d..df44b22ac835 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -882,14 +882,12 @@ class TrunkQuarantinedTest:# Repo-relative path of the test's file, empty when neither the repository nor Trunk places it.file: strowner_team: str- # Trunk's health verdict on the test, e.g. 'FLAKY' or 'BROKEN'.+ # Trunk's health verdict on the test, e.g. 'flaky' or 'broken'.status: str- # How the quarantine was applied, e.g. 'AUTO_QUARANTINE'.- quarantine_setting: strquarantined_at: datetimeage_days: intoverdue: bool- # The Trunk app's page for this test; None when the source has no org slug or the row no id.+ # The Trunk app's page for this test; None when the row has no URL and no org slug or test id.trunk_url: str | Nonediff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex a6760fe8f3f5..57c70475f1ce 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -345,13 +345,19 @@ class CuratedGitHubSource:source = self._trunk_quarantine()if source is None:return None- return f"({trunk_quarantined_tests.build_query(source.table)})"+ return f"({trunk_quarantined_tests.build_query(source.table, v2_shape=source.v2_shape)})"def trunk_org_url_slug(self) -> str | None:"""The TrunkIo source's org slug, for links into the Trunk app; None when unsynced or unset."""source = self._trunk_quarantine()return source.org_url_slug if source else None+ def trunk_quarantined_tests_v2_shape(self) -> bool:+ """Whether the synced quarantined-tests table holds the v2 API shape, which carries each+ test's Trunk URL; False when unsynced."""+ source = self._trunk_quarantine()+ return source.v2_shape if source else False+def members_source(self) -> str | None:"""Curated team-membership ``SELECT`` subquery, or None when the optional table isn't synced."""if not self._tables.team_members:diff --git a/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py b/products/engineering_analytics/backend/logic/queries/trunk_quarantine.pyindex 96de594352a2..84962b2f416c 100644--- a/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py+++ b/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py@@ -23,27 +23,38 @@ from products.engineering_analytics.backend.logic.queries._curated import Curate_LIMIT = 5000_QUARANTINED_SELECT = f"""- SELECT runner, nodeid, source_path, crate, status, quarantine_setting, test_case_id, quarantined_at+ SELECT runner, nodeid, source_path, crate, status, test_case_id, trunk_url, quarantined_atFROM __TRUNK_SOURCE__ORDER BY quarantined_at ASC, nodeid ASCLIMIT {_LIMIT + 1}"""-def _trunk_url(org_url_slug: str | None, repository: str) -> str | None:+def _trunk_url(*, v2_shape: bool, org_url_slug: str | None, repository: str) -> str | None:if not org_url_slug:return None+ # Trunk closes the repo-scoped page once an org moves to test collections.+ if v2_shape:+ return f"https://app.trunk.io/{org_url_slug}/flaky-tests/collections"return f"https://app.trunk.io/{org_url_slug}/flaky-tests?repo={repository}"def _trunk_test_url(org_url_slug: str | None, repository: str, test_case_id: str) -> str | None:- """The Trunk app's per-test page. The ``?repo`` form is what Trunk itself redirects to the- canonical repo-uuid URL (verified against the live app); the uuid is not in the synced data."""+ """The Trunk app's per-test page for a v1 row, which carries no URL. The ``?repo`` form is what+ Trunk itself redirects to the canonical repo-uuid URL (verified against the live app)."""if not org_url_slug or not test_case_id:return Nonereturn f"https://app.trunk.io/{org_url_slug}/flaky-tests/test/{test_case_id}?repo={repository}"+def _test_link(+ *, v2_shape: bool, url: str | None, org_url_slug: str | None, repository: str, test_case_id: str+) -> str | None:+ if v2_shape:+ return url+ return _trunk_test_url(org_url_slug, repository, test_case_id)++def query_trunk_quarantine_debt(*,curated: CuratedGitHubSource,@@ -66,7 +77,8 @@ def query_trunk_quarantine_debt(limit=_LIMIT,)org_url_slug = curated.trunk_org_url_slug()- trunk_url = _trunk_url(org_url_slug, curated.repository)+ v2_shape = curated.trunk_quarantined_tests_v2_shape()+ trunk_url = _trunk_url(v2_shape=v2_shape, org_url_slug=org_url_slug, repository=curated.repository)quarantined = curated.run(_QUARANTINED_SELECT.replace("__TRUNK_SOURCE__", source),@@ -90,8 +102,8 @@ def query_trunk_quarantine_debt()parsed = [- (runner, nodeid, QuarantinedTestFile(source_path=source_path, crate=crate), status, setting, case_id, at)- for runner, nodeid, source_path, crate, status, setting, case_id, at in rows+ (runner, nodeid, QuarantinedTestFile(source_path=source_path, crate=crate), status, case_id, test_url, at)+ for runner, nodeid, source_path, crate, status, case_id, test_url, at in rows]owned_by_test = resolve_test_ownership(curated.repository,@@ -100,7 +112,7 @@ def query_trunk_quarantine_debt(files=repo_files(curated.team, curated.repository, source_id=curated.source_id, priority=Priority.NORMAL),)tests: list[TrunkQuarantinedTest] = []- for (runner, nodeid, _file, status, quarantine_setting, test_case_id, quarantined_at), owned in zip(+ for (runner, nodeid, _file, status, test_case_id, test_url, quarantined_at), owned in zip(parsed, owned_by_test.tests, strict=True):if quarantined_at.tzinfo is None:@@ -113,11 +125,16 @@ def query_trunk_quarantine_debt(file=owned.path,owner_team=owned.owner_team,status=status,- quarantine_setting=quarantine_setting,quarantined_at=quarantined_at,age_days=age_days,overdue=age_days > ttl_days,- trunk_url=_trunk_test_url(org_url_slug, curated.repository, test_case_id),+ trunk_url=_test_link(+ v2_shape=v2_shape,+ url=test_url,+ org_url_slug=org_url_slug,+ repository=curated.repository,+ test_case_id=test_case_id,+ ),))tests.sort(key=lambda test: (-test.age_days, test.nodeid))diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.pyindex db3af1551a43..f3d2e8011f22 100644--- a/products/engineering_analytics/backend/logic/sources.py+++ b/products/engineering_analytics/backend/logic/sources.py@@ -36,7 +36,7 @@ from products.engineering_analytics.backend.facade.contracts import (GitHubSource,GitHubSourceNotConnectedError,)-from products.engineering_analytics.backend.logic.views import depot_ci, workflow_jobs+from products.engineering_analytics.backend.logic.views import depot_ci, trunk_quarantined_tests, workflow_jobsfrom products.engineering_analytics.backend.logic.views.source_schema import OPTIONAL_WORKFLOW_RUNS_COLUMNSfrom products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSourcefrom products.warehouse_sources.backend.facade.source_inputs import SourceInputsStore, UnreadableSourceInputsError@@ -352,6 +352,8 @@ class TrunkQuarantineSource:table: strorg_url_slug: str | None+ # False until a source moved to the v2 API resyncs, so the board keeps reading the v1 columns.+ v2_shape: booldef resolve_trunk_quarantined_tests_source(@@ -377,7 +379,11 @@ def resolve_trunk_quarantined_tests_source(inputs = SourceInputsStore.load(source)except UnreadableSourceInputsError:inputs = {}- resolved = TrunkQuarantineSource(table=table.name, org_url_slug=inputs.get("org_url_slug") or None)+ resolved = TrunkQuarantineSource(+ table=table.name,+ org_url_slug=inputs.get("org_url_slug") or None,+ v2_shape=trunk_quarantined_tests.V2_SHAPE_COLUMN in (table.columns or {}),+ )owner, name = inputs.get("repo_owner") or "", inputs.get("repo_name") or ""if f"{owner}/{name}".lower() == repository.lower():return resolveddiff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.pyindex 3ed36f4b3883..6a751a8d4938 100644--- a/products/engineering_analytics/backend/logic/views/source_schema.py+++ b/products/engineering_analytics/backend/logic/views/source_schema.py@@ -224,11 +224,10 @@ TRUNK_MERGE_QUEUE_COLUMNS: dict[str, dict[str, str]] = {"state_changed_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},}-# The Trunk quarantined-tests snapshot (TrunkIo source, QuarantinedTests endpoint): one row per-# currently quarantined test case, keyed by the (name, parent, file, classname, variant) tuple-# because Trunk documents ``test_case_id`` as unstable. Verified against a real connected source;-# every column lands Nullable(String), timestamps included.-TRUNK_QUARANTINED_TESTS_COLUMNS: dict[str, dict[str, str]] = {+# The same snapshot from a source still on the v1 API: keyed by the (name, parent, file, classname,+# variant) tuple because Trunk documents ``test_case_id`` as unstable. Verified against a real+# connected source; every column lands Nullable(String), timestamps included.+TRUNK_QUARANTINED_TESTS_V1_COLUMNS: dict[str, dict[str, str]] = {"file": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},"name": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},"labels": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},@@ -242,3 +241,23 @@ TRUNK_QUARANTINED_TESTS_COLUMNS: dict[str, dict[str, str]] = {"quarantine_setting": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},"status_last_updated_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},}++# The Trunk quarantined-tests snapshot (TrunkIo source, QuarantinedTests endpoint, read from+# `GET /v2/tests`): one row per currently quarantined test across every test collection. The+# pipeline lands the API's camelCase keys as snake_case, and every column as Nullable(String),+# timestamps included.+TRUNK_QUARANTINED_TESTS_COLUMNS: dict[str, dict[str, str]] = {+ "id": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "test_collection_id": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "file": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "name": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "labels": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "parent_name": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "class_name": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "variant": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "status": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "codeowners": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "quarantine_state": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "quarantined_since": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "url": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+}diff --git a/products/engineering_analytics/backend/logic/views/trunk_quarantined_tests.py b/products/engineering_analytics/backend/logic/views/trunk_quarantined_tests.pyindex f7dd24f52267..a0ca260217eb 100644--- a/products/engineering_analytics/backend/logic/views/trunk_quarantined_tests.py+++ b/products/engineering_analytics/backend/logic/views/trunk_quarantined_tests.py@@ -1,20 +1,46 @@"""Curated view over the Trunk quarantined-tests snapshot (``TRUNK_QUARANTINED_TESTS_COLUMNS``)."""+# A QuarantinedTests table synced on the v2 API lands this column; a v1 table lands ``parent``.+V2_SHAPE_COLUMN = "parent_name"-def build_query(table: str) -> str:++def build_query(table: str, *, v2_shape: bool) -> str:"""Curated SELECT over a synced Trunk quarantined-tests table: the reconstructed runner-native- nodeid, a runner label, where the test lives, and the parsed quarantine timestamp.+ nodeid, a runner label, where the test lives, the parsed quarantine timestamp, the test's id,+ and its Trunk page when the API returned one (always null on the v1 shape, which has no URL).++ The table holds the v1 or the v2 shape, depending on the source's API version pin and whether it+ resynced since the pin changed. Both shapes carry the same values under different names: v1+ ``parent`` / ``classname`` / ``quarantined_at`` / ``test_case_id``, v2 ``parent_name`` /+ ``class_name`` / ``quarantined_since`` / ``id`` plus ``url``.- Trunk keys a test by (file, classname, name) and overloads ``parent`` per uploader (verified- against a real connected source): 'pytest' for pytest, the test file path for jest and- Playwright, and the nextest 'suite::test' id for Rust. Trimming the module prefix recovers the- pytest class; jest and Playwright need no reassembly; Rust and Storybook rows carry no file, so- the nodeid falls back to classname::name. Rows without a name or quarantine time carry nothing- a consumer can attribute or age, so they drop here.+ Trunk keys a test by (file, classname, name) and overloads the parent per uploader (verified+ against a real connected source and the live v2 API): 'pytest' for pytest, the test file path+ for jest and Playwright, the story file for Storybook, and the nextest 'crate::module' id for+ Rust. Trimming the module prefix recovers the pytest class; jest and Playwright need no+ reassembly; Rust and Storybook rows carry no file, so the nodeid falls back to classname::name.+ Rows without a name or quarantine time carry nothing a consumer can attribute or age, so they+ drop here.- ``parent`` stays inside this view: the reading of it a consumer needs is ``source_path`` (where+ The parent stays inside this view: the reading of it a consumer needs is ``source_path`` (wherethe test file sits, as its suite reported it) and ``crate`` (Rust, which reports no file)."""+ if v2_shape:+ parent, classname, quarantined_at, test_id, url = (+ "parent_name",+ "class_name",+ "quarantined_since",+ "id",+ "url",+ )+ else:+ parent, classname, quarantined_at, test_id, url = (+ "parent",+ "classname",+ "quarantined_at",+ "test_case_id",+ "NULL",+ )return f"""SELECTrunner,@@ -27,33 +53,33 @@ def build_query(table: str) -> str:any(source_path) AS source_path,any(crate) AS crate,any(status) AS status,- any(quarantine_setting) AS quarantine_setting,any(test_case_id) AS test_case_id,+ any(url) AS trunk_url,-- Trunk keys a test per variant (e.g. one row per browser), so collapse to one row per-- test; the oldest quarantine carries the honest age.min(quarantined_at_parsed) AS quarantined_atFROM (SELECT+ ifNull({parent}, '') AS parent_value,multiIf(- parent = 'pytest', 'pytest',- parent LIKE '%::%', 'rust',- parent LIKE 'playwright/%' OR parent LIKE '%.spec.ts', 'playwright',- parent LIKE '%.stories.tsx', 'storybook',+ parent_value = 'pytest', 'pytest',+ parent_value LIKE '%::%', 'rust',+ parent_value LIKE 'playwright/%' OR parent_value LIKE '%.spec.ts', 'playwright',+ parent_value LIKE '%.stories.tsx', 'storybook','jest') AS runner,- ifNull(parent, '') AS parent,- if(runner = 'rust', '', if(ifNull(file, '') != '', ifNull(file, ''), parent)) AS source_path,- if(runner = 'rust', splitByString('::', parent)[1], '') AS crate,+ if(runner = 'rust', '', if(ifNull(file, '') != '', ifNull(file, ''), parent_value)) AS source_path,+ if(runner = 'rust', splitByString('::', parent_value)[1], '') AS crate,ifNull(file, '') AS file,ifNull(name, '') AS name,- ifNull(classname, '') AS classname,- ifNull(status, '') AS status,- ifNull(quarantine_setting, '') AS quarantine_setting,- ifNull(test_case_id, '') AS test_case_id,- parseDateTimeBestEffort(quarantined_at) AS quarantined_at_parsed,+ ifNull({classname}, '') AS classname,+ lower(ifNull(status, '')) AS status,+ ifNull({test_id}, '') AS test_case_id,+ {url} AS url,+ parseDateTimeBestEffort({quarantined_at}) AS quarantined_at_parsed,replaceAll(substring(ifNull(file, ''), 1, length(ifNull(file, '')) - 3), '/', '.') AS module,- if(parent = 'pytest' AND startsWith(ifNull(classname, ''), concat(module, '.')),- replaceAll(substring(ifNull(classname, ''), length(module) + 2, length(ifNull(classname, ''))), '.', '::'),+ if(parent_value = 'pytest' AND startsWith(classname, concat(module, '.')),+ replaceAll(substring(classname, length(module) + 2, length(classname)), '.', '::'),'') AS clsFROM {table})diff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.pyindex e7af0b0906f1..766ca6ba62d8 100644--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py@@ -1139,18 +1139,19 @@ def _trunk_quarantined_rows() -> list[dict[str, Any]]:module = file[:-3].replace("/", ".") if file.endswith(".py") else ""rows.append({+ "id": f"engseed-trunk-{index:03d}",+ "test_collection_id": "engseed","file": file,"name": name,"labels": "[]",- "parent": parent,- "status": "FLAKY",+ "parent_name": parent,+ "class_name": f"{module}.{test_class}" if test_class else "","variant": "",- "classname": f"{module}.{test_class}" if test_class else "",+ "status": "flaky","codeowners": "[]",- "test_case_id": f"engseed-trunk-{index:03d}",- "quarantined_at": quarantined_at,- "quarantine_setting": "AUTO_QUARANTINE",- "status_last_updated_at": quarantined_at,+ "quarantine_state": "quarantined",+ "quarantined_since": quarantined_at,+ "url": "",})return rowsdiff --git a/products/engineering_analytics/backend/presentation/serializers/suite_health.py b/products/engineering_analytics/backend/presentation/serializers/suite_health.pyindex 82ff0c1ec8bd..3cc555774d1d 100644--- a/products/engineering_analytics/backend/presentation/serializers/suite_health.py+++ b/products/engineering_analytics/backend/presentation/serializers/suite_health.py@@ -81,16 +81,13 @@ class TrunkQuarantinedTestSerializer(DataclassSerializer):"help_text": "Owning team slug from the repository's ownership files, or 'unowned' when the ""test's file cannot be placed or no team claims its path.",},- "status": {"help_text": "Trunk's current health verdict on the test, e.g. 'FLAKY' or 'BROKEN'."},- "quarantine_setting": {- "help_text": "How the quarantine was applied in Trunk, e.g. 'AUTO_QUARANTINE'.",- },+ "status": {"help_text": "Trunk's current health verdict on the test, e.g. 'flaky' or 'broken'."},"quarantined_at": {"help_text": "When Trunk quarantined the test."},"age_days": {"help_text": "Whole days since the quarantine started."},"overdue": {"help_text": "True once age_days exceeds ttl_days: the quarantine has outlived the TTL."},"trunk_url": {- "help_text": "The Trunk app's page for this test; null when the connected source has no "- "organization slug or the row carries no test case id.",+ "help_text": "The Trunk app's page for this test; null when Trunk returned no URL and the "+ "source has no organization slug or the row carries no test id.",},}diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.pyindex 485ebcbc36c4..f8912d8032d0 100644--- a/products/engineering_analytics/backend/tests/_github_fixtures.py+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py@@ -111,20 +111,36 @@ def create_depot_source(team: Team, *, prefix: str = "depot_", repository: str =)-def _quarantined_row(*, file: str, name: str, classname: str, parent: str) -> dict[str, Any]:+def _quarantined_row(*, file: str, name: str, classname: str, parent: str, v2_shape: bool = True) -> dict[str, Any]:+ if not v2_shape:+ return {+ "file": file,+ "name": name,+ "labels": "[]",+ "parent": parent,+ "status": "FLAKY",+ "variant": "",+ "classname": classname,+ "codeowners": "[]",+ "test_case_id": f"case-{name}",+ "quarantined_at": "2026-01-10T10:00:00.000Z",+ "quarantine_setting": "AUTO_QUARANTINE",+ "status_last_updated_at": "2026-01-10T10:00:00.000Z",+ }return {+ "id": f"case-{name}",+ "test_collection_id": "collection","file": file,"name": name,"labels": "[]",- "parent": parent,- "status": "FLAKY",+ "parent_name": parent,+ "class_name": classname,"variant": "",- "classname": classname,+ "status": "flaky","codeowners": "[]",- "test_case_id": f"case-{name}",- "quarantined_at": "2026-01-10T10:00:00.000Z",- "quarantine_setting": "AUTO_QUARANTINE",- "status_last_updated_at": "2026-01-10T10:00:00.000Z",+ "quarantine_state": "quarantined",+ "quarantined_since": "2026-01-10T10:00:00.000Z",+ "url": f"https://app.trunk.io/example/flaky-tests/collections/collection/tests/case-{name}",}diff --git a/products/engineering_analytics/backend/tests/test_quarantine.py b/products/engineering_analytics/backend/tests/test_quarantine.pyindex 59a5b7c61782..667a292a3605 100644--- a/products/engineering_analytics/backend/tests/test_quarantine.py+++ b/products/engineering_analytics/backend/tests/test_quarantine.py@@ -791,6 +791,9 @@ class _StubCurated:def trunk_org_url_slug(self) -> str | None:return None+ def trunk_quarantined_tests_v2_shape(self) -> bool:+ return True+def run(self, sql: str, **_kwargs: Any) -> SimpleNamespace:self.sql = sqlreturn SimpleNamespace(results=self._rows)@@ -805,9 +808,9 @@ class TestTrunkQuarantineDebtTruncation(TestCase):f"test_{index}",f"products/a/test_{index}.py","",- "quarantined",- "always",+ "flaky",f"case-{index}",+ f"https://app.trunk.io/example/tests/case-{index}",datetime(2026, 1, 1, tzinfo=UTC),)for index in range(count)diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.pyindex 5589f78d9ae4..6d10e180112b 100644--- a/products/engineering_analytics/backend/tests/test_views.py+++ b/products/engineering_analytics/backend/tests/test_views.py@@ -31,6 +31,7 @@ from products.engineering_analytics.backend.logic.views.source_schema import (DEPOT_JOB_ATTEMPTS_COLUMNS,PULL_REQUESTS_COLUMNS,TRUNK_QUARANTINED_TESTS_COLUMNS,+ TRUNK_QUARANTINED_TESTS_V1_COLUMNS,WORKFLOW_JOBS_COLUMNS,WORKFLOW_RUNS_COLUMNS,)@@ -860,39 +861,58 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):)assert rows[0] == ("completed", None, None, "", "", 0, None)- def test_trunk_quarantined_tests_view_labels_runners_and_reconstructs_paths(self) -> None:+ @parameterized.expand([("v1_shape", False), ("v2_shape", True)])+ def test_trunk_quarantined_tests_view_labels_runners_and_reconstructs_paths(+ self, _name: str, v2_shape: bool+ ) -> None:# Trunk overloads `parent` per uploader, and ownership is resolved from the source_path and- # crate this view reads out of it, so getting either wrong unattributes the whole board.+ # crate this view reads out of it, so getting either wrong unattributes the whole board. A+ # table keeps the v1 shape until its source moves to the v2 API and resyncs.table_name = self._create_table("trunkio_quarantinedtests",- TRUNK_QUARANTINED_TESTS_COLUMNS,+ TRUNK_QUARANTINED_TESTS_COLUMNS if v2_shape else TRUNK_QUARANTINED_TESTS_V1_COLUMNS,[_quarantined_row(file="posthog/api/test/test_person.py",name="test_merge",classname="posthog.api.test.test_person.TestPerson",parent="pytest",+ v2_shape=v2_shape,),_quarantined_row(file="",name="k3s_integration",classname="personhog-coordination",parent="personhog-coordination::k3s_integration",+ v2_shape=v2_shape,+ ),+ _quarantined_row(+ file="src/cdp/cdp.test.ts",+ name="routes",+ classname="",+ parent="src/cdp/cdp.test.ts",+ v2_shape=v2_shape,),- _quarantined_row(file="src/cdp/cdp.test.ts", name="routes", classname="", parent="src/cdp/cdp.test.ts"),],)- rows = self._select(- f"SELECT runner, nodeid, source_path, crate FROM ({trunk_quarantined_tests.build_query(table_name)}) AS q "- "ORDER BY runner"- )+ query = trunk_quarantined_tests.build_query(table_name, v2_shape=v2_shape)+ rows = self._select(f"SELECT runner, nodeid, source_path, crate, trunk_url FROM ({query}) AS q ORDER BY runner")++ def url(name: str) -> str | None:+ return (+ f"https://app.trunk.io/example/flaky-tests/collections/collection/tests/case-{name}"+ if v2_shape+ else None+ )+assert rows == [- ("jest", "src/cdp/cdp.test.ts::routes", "src/cdp/cdp.test.ts", ""),+ ("jest", "src/cdp/cdp.test.ts::routes", "src/cdp/cdp.test.ts", "", url("routes")),("pytest","posthog/api/test/test_person.py::TestPerson::test_merge","posthog/api/test/test_person.py","",+ url("test_merge"),),- ("rust", "personhog-coordination::k3s_integration", "", "personhog-coordination"),+ ("rust", "personhog-coordination::k3s_integration", "", "personhog-coordination", url("k3s_integration")),]diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex f5f2b7873918..dd2c25317afd 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -2407,10 +2407,8 @@ export interface TrunkQuarantinedTestApi {file: string/** Owning team slug from the repository's ownership files, or 'unowned' when the test's file cannot be placed or no team claims its path. */owner_team: string- /** Trunk's current health verdict on the test, e.g. 'FLAKY' or 'BROKEN'. */+ /** Trunk's current health verdict on the test, e.g. 'flaky' or 'broken'. */status: string- /** How the quarantine was applied in Trunk, e.g. 'AUTO_QUARANTINE'. */- quarantine_setting: string/** When Trunk quarantined the test. */quarantined_at: string/** Whole days since the quarantine started. */@@ -2418,7 +2416,7 @@ export interface TrunkQuarantinedTestApi {/** True once age_days exceeds ttl_days: the quarantine has outlived the TTL. */overdue: boolean/**- * The Trunk app's page for this test; null when the connected source has no organization slug or the row carries no test case id.+ * The Trunk app's page for this test; null when Trunk returned no URL and the source has no organization slug or the row carries no test id.* @nullable*/trunk_url: string | nulldiff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.stories.tsxindex 8651230af34e..da015ec8b747 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.stories.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeamScene.stories.tsx@@ -137,8 +137,7 @@ const TRUNK_QUARANTINE: TrunkQuarantineDebtApi = {nodeid: 'products/replay/test_snapshots.py::test_resume_keeps_cursor',file: 'products/replay/test_snapshots.py',owner_team: TEAM,- status: 'FLAKY',- quarantine_setting: 'AUTO_QUARANTINE',+ status: 'flaky',quarantined_at: '2026-06-12T09:00:00Z',age_days: 21,overdue: true,diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTests.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTests.stories.tsxindex 6b5354ac7de1..717088e2e8ea 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTests.stories.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTests.stories.tsx@@ -39,8 +39,7 @@ const TRUNK_QUARANTINE: TrunkQuarantineDebtApi = {nodeid: 'products/batch_exports/backend/tests/test_snowflake.py::TestSnowflakeExport::test_resume',file: 'products/batch_exports/backend/tests/test_snowflake.py',owner_team: 'batch-exports',- status: 'FLAKY',- quarantine_setting: 'AUTO_QUARANTINE',+ status: 'flaky',quarantined_at: '2026-05-19T08:00:00Z',age_days: 44,overdue: true,@@ -51,8 +50,7 @@ const TRUNK_QUARANTINE: TrunkQuarantineDebtApi = {nodeid: 'posthog/session_recordings/test/test_snapshots.py::TestSnapshots::test_batching',file: 'posthog/session_recordings/test/test_snapshots.py',owner_team: 'team-replay',- status: 'FLAKY',- quarantine_setting: 'AUTO_QUARANTINE',+ status: 'flaky',quarantined_at: '2026-05-25T08:00:00Z',age_days: 38,overdue: true,@@ -63,8 +61,7 @@ const TRUNK_QUARANTINE: TrunkQuarantineDebtApi = {nodeid: 'frontend/src/lib/components/ActivityLog/activityLogLogic.test.tsx::humanizes flag changes',file: 'frontend/src/lib/components/ActivityLog/activityLogLogic.test.tsx',owner_team: 'unowned',- status: 'FLAKY',- quarantine_setting: 'AUTO_QUARANTINE',+ status: 'flaky',quarantined_at: '2026-06-23T08:00:00Z',age_days: 9,overdue: false,diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.tsindex 58a31c933679..0301902fdaea 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts@@ -837,8 +837,7 @@ describe('engineeringAnalyticsLogic', () => {nodeid: 'a.py::TestA::test_a',file: 'a.py',owner_team: 'team-replay',- status: 'FLAKY',- quarantine_setting: 'AUTO_QUARANTINE',+ status: 'flaky',quarantined_at: '2026-05-19T08:00:00Z',age_days: 44,overdue: true,@@ -849,8 +848,7 @@ describe('engineeringAnalyticsLogic', () => {nodeid: 'b.test.tsx::renders',file: 'b.test.tsx',owner_team: 'unowned',- status: 'FLAKY',- quarantine_setting: 'AUTO_QUARANTINE',+ status: 'flaky',quarantined_at: '2026-06-23T08:00:00Z',age_days: 9,overdue: false,@@ -874,8 +872,7 @@ describe('engineeringAnalyticsLogic', () => {nodeid: 'a.py::TestA::test_a',file: 'a.py',ownerTeam: 'team-replay',- status: 'FLAKY',- quarantineSetting: 'AUTO_QUARANTINE',+ status: 'flaky',quarantinedAt: '2026-05-19T08:00:00Z',ageDays: 44,overdue: true,diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.tsindex 060838b73de6..8247fd84437c 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts@@ -362,7 +362,6 @@ export interface TrunkQuarantinedTestRow {file: stringownerTeam: stringstatus: string- quarantineSetting: stringquarantinedAt: stringageDays: numberoverdue: boolean@@ -854,7 +853,6 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyfile: it.file,ownerTeam: it.owner_team,status: it.status,- quarantineSetting: it.quarantine_setting,quarantinedAt: it.quarantined_at,ageDays: it.age_days,overdue: it.overdue,diff --git a/products/warehouse_sources/backend/migrations/0188_reset_trunkio_v2_failing_tests.py b/products/warehouse_sources/backend/migrations/0188_reset_trunkio_v2_failing_tests.pynew file mode 100644index 000000000000..d9106a564024--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0188_reset_trunkio_v2_failing_tests.py@@ -0,0 +1,47 @@+from django.db import migrations+from django.db.models import Q++# A TrunkIo source on the v2 pin used to read `FailingTests` from the v1+# `list-failing-tests` endpoint. It now reads `GET /v2/tests`, whose test ids and columns differ.+# `FailingTests` syncs incrementally and merges on `id`, so the old v1 rows would stay beside the+# new v2 rows. Stamp `reset_pipeline`, so the next sync wipes the table and rebuilds it in the v2+# shape (`handle_reset_or_full_refresh`). `UnhealthyTests` and `QuarantinedTests` are full refresh+# and replace their table on every sync, so they need no reset. A v1 pin keeps its v1 wire.+TRUNKIO_SOURCE_TYPE = "TrunkIo"+TRUNK_IO_API_VERSION_V2 = "v2"+FAILING_TESTS = "FailingTests"+++def reset_v2_failing_tests(apps, schema_editor):+ ExternalDataSchema = apps.get_model("warehouse_sources", "ExternalDataSchema")++ # The effective pin is the schema's own, else the source's, else the source's default (v2).+ on_v2 = Q(api_version=TRUNK_IO_API_VERSION_V2) | (+ (Q(api_version__isnull=True) | Q(api_version=""))+ & (+ Q(source__api_version=TRUNK_IO_API_VERSION_V2)+ | Q(source__api_version__isnull=True)+ | Q(source__api_version="")+ )+ )+ schemas = ExternalDataSchema.objects.filter(+ on_v2, source__source_type=TRUNKIO_SOURCE_TYPE, name=FAILING_TESTS, deleted=False+ ).iterator()++ for schema in schemas:+ config = schema.sync_type_config or {}+ config["reset_pipeline"] = True+ schema.sync_type_config = config+ schema.save(update_fields=["sync_type_config"])+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources", "0187_repin_teamtailor_api_version"),+ ]++ operations = [+ # Reverse is a no-op: the reset consumes itself on the next sync, and the v1 rows it wiped+ # cannot come back.+ migrations.RunPython(reset_v2_failing_tests, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex 238fb1f3f85b..e7bb068fcabc 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0187_repin_teamtailor_api_version+0188_reset_trunkio_v2_failing_testsdiff --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 83a5a976c222..c42b89b3ae18 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@@ -12552,10 +12552,10 @@ Today (6): `FailingTests`, `MergeQueuePullRequests`, `QuarantinedTests`, `TestCoDiffed 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)+- [ ] `GET /v2/tests/{id}` — column-level, not a missing table: it adds `quarantineOverride`, `activeMonitors`, `firstSeenAt` and the all-time `lastFailureAt` to a list row, at the cost of one call per test. On a `v2` pin, `UnhealthyTests`, `QuarantinedTests` and `FailingTests` read `GET /v2/tests` with `include=metrics`, which already embeds the 7-day failure rate and last failure (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)+- [x] `GET /v2/tests` — tests across every collection in the org, with status, quarantine state and labels. Cursor-paginated, full refresh. Served on API version `v2` only. On a `v2` pin the filtered `UnhealthyTests`, `QuarantinedTests` and `FailingTests` tables read the same endpoint, because Trunk retires the repository-scoped v1 list endpoints once an org moves to test collections (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/field_classification.csv b/products/warehouse_sources/backend/temporal/data_imports/sources/field_classification.csvindex 2c2b531c91a6..917ddde79b56 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/field_classification.csv+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/field_classification.csv@@ -1277,7 +1277,7 @@ Tremendous,environment api_key,,,,,tremendousTriggerDev,api_key base_url,,,,,trigger-devTrino,host port catalog auth_type use_ssl verify_ssl,,,schema,,trinoTripleWhale,api_key shop,,,start_date,,triple-whale-TrunkIo,api_token org_url_slug repo_host,,,repo_owner repo_name merge_queue_target_branch,,trunk-io+TrunkIo,api_token org_url_slug repo_host,,,repo_owner repo_name merge_queue_target_branch trunk_repository_id,,trunk-ioTrustPilot,api_key api_secret business_unit,,,,,trust-pilotTrustradius,api_key,,,,,trustradiusTurso,organization_slug api_token,,,,,tursodiff --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 4c630209dd2c..4f47caab10a2 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@@ -12,3 +12,4 @@ class TrunkIoSourceConfig(config.Config):repo_owner: strrepo_name: strmerge_queue_target_branch: str | None = None+ trunk_repository_id: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txtindex ff372cf0fccd..45d5d308b3e9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt@@ -151,7 +151,6 @@ TemporalIO not-checkable:driver:temporalio.clientTerraformCloud fail:safe-pointTikTokAds not-checkable:databaseTrino not-checkable:schemas-TrunkIo fail:safe-pointTwitterAds not-checkable:databaseUbidots fail:safe-pointUnleash fail:safe-pointdiff --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 0eb7561cba5b..d4ed1fc8a7a4 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@@ -7,68 +7,52 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.sTESTS,)-_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"+_TEST_COLUMNS: dict[str, str] = {+ "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.",+ "quarantinedSince": "When the test's current quarantine began. Empty when the test is not quarantined.",+ "labels": "The labels on the test, with what applied each one.",+ "url": "The test's page in the Trunk app.",+ "ticket": "The ticket linked to this test, if any.",+}++_TEST_METRICS_COLUMNS: dict[str, str] = {+ **_TEST_COLUMNS,+ "metrics": "The test's failure rate, pull requests impacted, run and failure counts, p95 duration, last run and last failure over the last 7 days. Empty when the test had no runs.",+}+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.",- },+ "description": "Tests Trunk currently considers flaky or broken, across every test collection, with their metrics over the last 7 days.",+ "docs_url": _V2_DOCS_URL,+ "columns": _TEST_METRICS_COLUMNS,},"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.",- },+ "description": "Tests currently quarantined (failures suppressed so CI still passes), across every test collection, with their metrics over the last 7 days.",+ "docs_url": _V2_DOCS_URL,+ "columns": _TEST_METRICS_COLUMNS,},"FailingTests": {- "description": "Distinct tests that failed at least once within a given time window.",- "docs_url": _FLAKY_TESTS_DOCS_URL,+ "description": "Tests that failed at least once in the last 7 days, across every test collection, most recent failure first.",+ "docs_url": _V2_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.",+ **_TEST_METRICS_COLUMNS,+ "synced_through": "PostHog-added: the start of the sync run this row was fetched in, used to track incremental progress.",},},MERGE_QUEUE_PULL_REQUESTS: {@@ -106,24 +90,8 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {},},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.",+ "description": "Tests across every test collection in the organization, with their current status and quarantine state.","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.",- },+ "columns": _TEST_COLUMNS,},}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 fc069d1c8656..0ebf9478007f 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@@ -31,9 +31,9 @@ MERGE_QUEUE_PAGE_SIZE = 100MERGE_QUEUE_PULL_REQUESTS = "MergeQueuePullRequests"# 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.+# v1 endpoints: test ids differ between the two, and Trunk retires the v1 list endpoints once an+# org moves to collections. A v1 pin keeps the flaky-test tables on their v1 wire; a v2 pin reads+# them from `GET /v2/tests` across every collection and adds the collection tables on top.TEST_COLLECTIONS = "TestCollections"TESTS = "Tests"@@ -41,6 +41,8 @@ TESTS = "Tests"# params and return `{data, nextCursor, hasMore}`.V2_PAGE_SIZE = 100+TEST_METRICS_PARAMS: dict[str, str] = {"include": "metrics", "period": "7d"}+V1_ENDPOINTS = ("UnhealthyTests","QuarantinedTests",@@ -63,9 +65,9 @@ def endpoints_for_version(api_version: str) -> tuple[str, ...]: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.",+ "UnhealthyTests": "Tests Trunk currently considers flaky or broken.",+ "QuarantinedTests": "Tests currently quarantined (failures suppressed).",+ "FailingTests": "Tests that failed at least once in a recent 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.",@@ -82,12 +84,17 @@ PRIMARY_KEYS: dict[str, list[str]] = {TESTS: ["id"],}+# A v2 row carries a stable `id`, unlike a v1 quarantined test case.+V2_PRIMARY_KEYS: dict[str, list[str]] = {**PRIMARY_KEYS, "QuarantinedTests": ["id"]}+# `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.+# - `FailingTests` on v1 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. On v2+# there is only a fixed 7-day metrics window, so every row in a run is stamped with the run's+# start time and the merge on `id` keeps the latest metrics.# - `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 isdiff --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 e2ff313a7b50..50fe32ef0211 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@@ -8,7 +8,11 @@ from products.warehouse_sources.backend.facade.source_config import (SourceFieldInputConfig,SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ FieldType,+ ResumableSource,+ VersionDeprecation,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)@@ -32,18 +36,23 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.sTESTS,TRUNK_IO_API_VERSION_V1,TRUNK_IO_API_VERSION_V2,+ V2_PRIMARY_KEYS,endpoints_for_version,)from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.trunk_io import (TrunkIoResumeConfig,TrunkRepo,failing_tests,+ list_failing_tests,+ list_quarantined_tests,list_test_collections,list_tests,+ list_unhealthy_tests,merge_queue_pull_requests,quarantined_tests,unhealthy_tests,validate_credentials as validate_trunk_io_credentials,+ validate_v2_credentials,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -58,10 +67,13 @@ class TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):codebase_detection = detect(env=("^TRUNK_API_TOKEN$", "^TRUNK_ORG_URL_SLUG$"), npm=("@trunkio/launcher",))lists_tables_without_credentials = True # static endpoint catalog — safe for public docs- api_docs_url = "https://docs.trunk.io/flaky-tests/api"+ api_docs_url = "https://docs.trunk.io/flaky-tests/reference/api-reference"supported_versions = (TRUNK_IO_API_VERSION_V1, TRUNK_IO_API_VERSION_V2)default_version = TRUNK_IO_API_VERSION_V2+ # Trunk retires the repository-scoped v1 list endpoints per organization, when it moves to test+ # collections, so there is no single sunset date.+ deprecated_versions = (VersionDeprecation(version=TRUNK_IO_API_VERSION_V1),)@propertydef source_type(self) -> ExternalDataSourceType:@@ -105,8 +117,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.+ if self.resolve_api_version(api_version) == TRUNK_IO_API_VERSION_V2:+ return validate_v2_credentials(config.api_token)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)@@ -121,10 +133,19 @@ 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)):+ api_version = self.resolve_api_version(inputs.api_version)+ if endpoint not in endpoints_for_version(api_version):raise ValueError(f"Unknown Trunk.io endpoint: {endpoint}")+ on_v2 = api_version == TRUNK_IO_API_VERSION_V2+ repository_id = (config.trunk_repository_id or "").strip() or None- if endpoint == "UnhealthyTests":+ if endpoint == "UnhealthyTests" and on_v2:+ items = list_unhealthy_tests(config.api_token, resumable_source_manager, repository_id)+ elif endpoint == "QuarantinedTests" and on_v2:+ items = list_quarantined_tests(config.api_token, resumable_source_manager, repository_id)+ elif endpoint == "FailingTests" and on_v2:+ items = list_failing_tests(config.api_token, resumable_source_manager, repository_id)+ elif 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)@@ -163,7 +184,7 @@ class TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):return SourceResponse(name=endpoint,items=lambda: items,- primary_keys=PRIMARY_KEYS[endpoint],+ primary_keys=(V2_PRIMARY_KEYS if on_v2 else PRIMARY_KEYS)[endpoint],)@property@@ -172,7 +193,7 @@ class TrunkIoSource(ResumableSource[TrunkIoSourceConfig, TrunkIoResumeConfig]):name=ExternalDataSourceType.TRUNKIO,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Trunk.io (Trunk Technologies, Inc.)",- caption="""Enter a Trunk.io API token to sync flaky test and merge queue data for a single repository.+ caption="""Enter a Trunk.io API token to sync flaky test and merge queue data. On API version v2 the flaky test tables cover every test collection in your organization.Supported tables:- `UnhealthyTests`@@ -180,9 +201,9 @@ Supported tables:- `FailingTests`- `MergeQueuePullRequests` (needs a merge queue target branch below)- `TestCollections`-- `Tests` (tests in your test collections)+- `Tests` (every test in your test collections)-Create an API token in the Trunk app under Settings > Organization > General > API.+Create an API key in the Trunk app under Settings > Developer > API Keys.""",docsUrl="https://posthog.com/docs/cdp/sources/trunk-io",iconPath="/static/services/trunk_io.png",@@ -242,6 +263,16 @@ Create an API token in the Trunk app under Settings > Organization > General > Asecret=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.",),+ SourceFieldInputConfig(+ name="trunk_repository_id",+ sync_setting=True,+ label="Trunk repository ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="7a2b3c4d-5e6f-4a1b-8c9d-0e1f2a3b4c5d",+ secret=False,+ caption="Optional, API version v2 only. Limits `UnhealthyTests`, `QuarantinedTests` and `FailingTests` to tests from this repository. Copy the `repositoryId` of any of its tests from the Trunk API. Tests uploaded without a repository are left out. Leave this empty to sync tests from every repository in your Trunk organization.",+ ),],),releaseStatus=ReleaseStatus.BETA,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 56aac20026a8..a26fe4cfe87b 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@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.tTrunkPageQueryPaginator,TrunkRepo,validate_credentials,+ validate_v2_credentials,)REPO = TrunkRepo(host="github.com", owner="my-org", name="my-repo")@@ -48,7 +49,14 @@ def _page(next_page_token: str = "") -> dict[str, Any]:}-def _run(endpoint: str, script: Script, resume_state: TrunkIoResumeConfig | None = None, **kwargs: Any) -> DriveResult:+def _run(+ endpoint: str,+ script: Script,+ resume_state: TrunkIoResumeConfig | None = None,+ api_version: str = "v1",+ trunk_repository_id: str | None = None,+ **kwargs: Any,+) -> DriveResult:config = TrunkIoSourceConfig(api_token="token",org_url_slug="my-org",@@ -56,8 +64,11 @@ def _run(endpoint: str, script: Script, resume_state: TrunkIoResumeConfig | Nonerepo_owner=REPO.owner,repo_name=REPO.name,merge_queue_target_branch="main",+ trunk_repository_id=trunk_repository_id,+ )+ return SourceDriver(TrunkIoSource(), config).run(+ endpoint, script, resume_state=resume_state, api_version=api_version, **kwargs)- return SourceDriver(TrunkIoSource(), config).run(endpoint, script, resume_state=resume_state, **kwargs)class TestTrunkPageQueryPaginator:@@ -260,39 +271,92 @@ class TestMergeQueuePullRequests:class TestV2Lists:@parameterized.expand([- ("test_collections", "TestCollections", "/v2/test-collections"),- ("tests", "Tests", "/v2/tests"),+ ("test_collections", "TestCollections", "/v2/test-collections", {}),+ ("tests", "Tests", "/v2/tests", {}),+ (+ "unhealthy_tests",+ "UnhealthyTests",+ "/v2/tests",+ {"status": ("flaky,broken",), "include": ("metrics",), "period": ("7d",)},+ ),+ (+ "quarantined_tests",+ "QuarantinedTests",+ "/v2/tests",+ {"quarantineState": ("quarantined",), "include": ("metrics",), "period": ("7d",)},+ ),+ (+ "failing_tests",+ "FailingTests",+ "/v2/tests",+ {"sort": ("lastFailureAt",), "include": ("metrics",), "period": ("7d",)},+ ),])- def test_paginates_v2_cursor_with_bearer_auth(self, _label: str, schema_name: str, expected_path: str) -> None:+ def test_paginates_v2_cursor_with_bearer_auth(+ self, _label: str, schema_name: str, expected_path: str, expected_filters: dict[str, tuple[str, ...]]+ ) -> None:result = _run(schema_name,[_ok({"data": [{"id": "a"}], "nextCursor": "cursor-1", "hasMore": True}),_ok({"data": [{"id": "b"}], "nextCursor": None, "hasMore": False}),],+ api_version="v2",)assert [row["id"] for row in result.rows] == ["a", "b"]assert [(r.method.upper(), r.origin, r.path) for r in result.requests] == [("GET", "https://api.trunk.io", expected_path)] * 2- assert dict(result.requests[0].query) == {"limit": ("100",)}- assert dict(result.requests[1].query) == {"limit": ("100",), "cursor": ("cursor-1",)}+ assert dict(result.requests[0].query) == {"limit": ("100",), **expected_filters}+ assert dict(result.requests[1].query) == {"limit": ("100",), **expected_filters, "cursor": ("cursor-1",)}assert result.requests[0].headers["authorization"] == "Bearer token"assert all(request.read_timeout == 60.0 for request in result.requests)- assert result.saved_states == [TrunkIoResumeConfig(cursor="cursor-1")]+ assert [state.cursor for state in result.saved_states] == ["cursor-1"]assert result.final_state is None+ @time_machine.travel("2024-06-15T00:00:00Z", tick=False)+ def test_failing_tests_stamp_one_synced_through_per_run(self) -> None:+ result = _run(+ "FailingTests",+ [+ _ok({"data": [{"id": "a"}], "nextCursor": "cursor-1", "hasMore": True}),+ _ok({"data": [{"id": "b"}], "nextCursor": None, "hasMore": False}),+ ],+ api_version="v2",+ )++ assert {row["synced_through"] for row in result.rows} == {"2024-06-15T00:00:00Z"}+ assert result.saved_states == [TrunkIoResumeConfig(cursor="cursor-1", synced_through="2024-06-15T00:00:00Z")]+def test_resume_seeds_saved_cursor(self) -> None:result = _run("Tests",[_ok({"data": [], "nextCursor": None, "hasMore": False})],resume_state=TrunkIoResumeConfig(cursor="cursor-resumed"),+ api_version="v2",)assert result.requests[0].param("cursor") == "cursor-resumed"+ def test_repository_id_keeps_only_that_repositorys_tests_across_pages(self) -> None:+ result = _run(+ "QuarantinedTests",+ [+ _ok({"data": [{"id": "other", "repositoryId": "repo-b"}], "nextCursor": "cursor-1", "hasMore": True}),+ _ok({"data": [{"id": "other-2", "repositoryId": "repo-b"}], "nextCursor": "cursor-2", "hasMore": True}),+ _ok({"data": [{"id": "ours", "repositoryId": "repo-a"}], "nextCursor": None, "hasMore": False}),+ ],+ api_version="v2",+ trunk_repository_id=" repo-a ",+ )++ assert [row["id"] for row in result.rows] == ["ours"]+ assert len(result.requests) == 3+ # Pages filtered down to nothing yield no item, so only a safe point commits their cursors.+ assert [state.cursor for state in result.committed_states] == ["cursor-1", "cursor-2"]+class TestClientRedirectHandling:def test_redirect_is_refused_without_replaying_token(self) -> None:@@ -311,10 +375,16 @@ class TestClientRedirectHandling:class TestValidateCredentials:- def test_credential_check_disables_redirects(self) -> None:+ @parameterized.expand(+ [+ ("v1", lambda: validate_credentials("token", "my-org", REPO)),+ ("v2", lambda: validate_v2_credentials("token")),+ ]+ )+ def test_credential_check_disables_redirects(self, _label: str, validate: Any) -> None:# Redirects off keeps the token from leaking to a redirect target during validation.with scripted_network([_ok({})]) as network:- validate_credentials("token", "my-org", REPO)+ validate()assert network.session_optionsassert all(options["allow_redirects"] is False for options in network.session_options)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.pyindex 38f347e8151d..171f87c2dc62 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@@ -31,7 +31,7 @@ class TestTrunkIoSource:"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)+ result = self.source.validate_credentials(self.config, self.team_id, api_version="v1")assert result == (True, None)(api_token, org_url_slug, repo), _ = mock_validate.call_args.args, mock_validate.call_args.kwargs@@ -86,9 +86,9 @@ class TestTrunkIoSource:("QuarantinedTests", "/v1/flaky-tests/list-quarantined-tests", "v1"),("FailingTests", "/v1/flaky-tests/list-failing-tests", "v1"),("MergeQueuePullRequests", "/v1/listPullRequests", "v1"),- ("UnhealthyTests", "/v1/flaky-tests/list-unhealthy-tests", "v2"),- ("QuarantinedTests", "/v1/flaky-tests/list-quarantined-tests", "v2"),- ("FailingTests", "/v1/flaky-tests/list-failing-tests", "v2"),+ ("UnhealthyTests", "/v2/tests", "v2"),+ ("QuarantinedTests", "/v2/tests", "v2"),+ ("FailingTests", "/v2/tests", "v2"),("MergeQueuePullRequests", "/v1/listPullRequests", "v2"),("TestCollections", "/v2/test-collections", "v2"),("Tests", "/v2/tests", "v2"),@@ -120,16 +120,12 @@ class TestTrunkIoSource:@parameterized.expand([- ("UnhealthyTests", ["id"]),- ("QuarantinedTests", ["name", "parent", "file", "classname", "variant"]),- ("FailingTests", ["id"]),- ("MergeQueuePullRequests", ["id"]),- ("TestCollections", ["id"]),- ("Tests", ["id"]),+ ("v1", ["name", "parent", "file", "classname", "variant"]),+ ("v2", ["id"]),])- def test_source_for_pipeline_primary_keys(self, schema_name: str, expected_keys: list[str]):- result = SourceDriver(self.source, self.config).run(schema_name, [])+ def test_quarantined_tests_primary_key_follows_the_pin(self, api_version: str, expected_keys: list[str]):+ result = SourceDriver(self.source, self.config).run("QuarantinedTests", [], api_version=api_version)assert result.response is not Noneassert result.response.primary_keys == expected_keysdiff --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 1bfa6cba9ad5..5426b20c1635 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@@ -23,13 +23,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.trunk_io.sFAILING_TESTS_WINDOW_DAYS,MERGE_QUEUE_PAGE_SIZE,PAGE_SIZE,+ TEST_METRICS_PARAMS,UNHEALTHY_STATUSES,V2_BASE_URL,V2_PAGE_SIZE,)[email protected](frozen=True)class TrunkIoResumeConfig:"""Unified resume shape for every Trunk endpoint. Each `source_for_pipeline` call gets itsown resumable-source-manager key (namespaced by job id), so only the fields relevant to the@@ -369,24 +370,38 @@ def _v2_list(api_token: str,path: str,resumable_source_manager: ResumableSourceManager[TrunkIoResumeConfig],+ params: Optional[dict[str, Any]] = None,+ synced_through: Optional[str] = None,+ repository_id: Optional[str] = None,) -> Iterator[list[dict[str, Any]]]:client = _v2_client(api_token)resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Nonedef checkpoint(state: Optional[dict[str, Any]]) -> None:if state and state.get("cursor"):- resumable_source_manager.save_state(TrunkIoResumeConfig(cursor=str(state["cursor"])))+ resumable_source_manager.save_state(+ TrunkIoResumeConfig(cursor=str(state["cursor"]), synced_through=synced_through)+ )+ # The hook runs once the page is consumed. A run of pages filtered down to nothing yields no+ # item, so the pipeline sees a shutdown or commits the cursor only here.+ resumable_source_manager.safe_point()for page in client.paginate(path=path,method="get",- params={"limit": V2_PAGE_SIZE},+ params={"limit": V2_PAGE_SIZE, **(params or {})},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,):+ # `GET /v2/tests` has no repository filter, so rows from the org's other repositories drop here.+ if repository_id:+ page = [row for row in page if row.get("repositoryId") == repository_id]if page:+ if synced_through:+ for row in page:+ row["synced_through"] = synced_throughyield pageresumable_source_manager.clear_state()@@ -407,6 +422,53 @@ def list_tests(return _v2_list(api_token, "/v2/tests", resumable_source_manager)+def list_unhealthy_tests(+ api_token: str,+ resumable_source_manager: ResumableSourceManager[TrunkIoResumeConfig],+ repository_id: Optional[str] = None,+) -> Iterator[list[dict[str, Any]]]:+ return _v2_list(+ api_token,+ "/v2/tests",+ resumable_source_manager,+ params={"status": "flaky,broken", **TEST_METRICS_PARAMS},+ repository_id=repository_id,+ )+++def list_quarantined_tests(+ api_token: str,+ resumable_source_manager: ResumableSourceManager[TrunkIoResumeConfig],+ repository_id: Optional[str] = None,+) -> Iterator[list[dict[str, Any]]]:+ return _v2_list(+ api_token,+ "/v2/tests",+ resumable_source_manager,+ params={"quarantineState": "quarantined", **TEST_METRICS_PARAMS},+ repository_id=repository_id,+ )+++def list_failing_tests(+ api_token: str,+ resumable_source_manager: ResumableSourceManager[TrunkIoResumeConfig],+ repository_id: Optional[str] = None,+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ synced_through = (resume.synced_through if resume else None) or _format_rfc3339(datetime.now(UTC))+ # A `lastFailureAt` sort drops tests with no failure in `period`, which is what makes this+ # the failing set rather than every test.+ return _v2_list(+ api_token,+ "/v2/tests",+ resumable_source_manager,+ params={"sort": "lastFailureAt", **TEST_METRICS_PARAMS},+ synced_through=synced_through,+ repository_id=repository_id,+ )++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:@@ -431,3 +493,22 @@ def validate_credentials(api_token: str, org_url_slug: str, repo: TrunkRepo) ->"Trunk.io authentication failed. Check your API token, organization slug, and repository details.",)return False, f"Trunk.io API returned HTTP {response.status_code}."+++def validate_v2_credentials(api_token: str) -> tuple[bool, str | None]:+ session = make_tracked_session(redact_values=(api_token,), allow_redirects=False)+ try:+ response = session.get(+ f"{V2_BASE_URL}/v2/tests",+ headers={"Authorization": f"Bearer {api_token}"},+ params={"limit": 1},+ 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."+ return False, f"Trunk.io API returned HTTP {response.status_code}."diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a147892d6fbc..120df379fd02 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -121369,10 +121369,8 @@ export namespace Schemas {file: string;/** Owning team slug from the repository's ownership files, or 'unowned' when the test's file cannot be placed or no team claims its path. */owner_team: string;- /** Trunk's current health verdict on the test, e.g. 'FLAKY' or 'BROKEN'. */+ /** Trunk's current health verdict on the test, e.g. 'flaky' or 'broken'. */status: string;- /** How the quarantine was applied in Trunk, e.g. 'AUTO_QUARANTINE'. */- quarantine_setting: string;/** When Trunk quarantined the test. */quarantined_at: string;/** Whole days since the quarantine started. */@@ -121380,7 +121378,7 @@ export namespace Schemas {/** True once age_days exceeds ttl_days: the quarantine has outlived the TTL. */overdue: boolean;/**- * The Trunk app's page for this test; null when the connected source has no organization slug or the row carries no test case id.+ * The Trunk app's page for this test; null when Trunk returned no URL and the source has no organization slug or the row carries no test id.* @nullable*/trunk_url: string | null;