: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(engineering-analytics): add state filter and paging to the pull-requests tool (#109370)
posthog[bot]f6775e9338db
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex 8c0011c565a6..6777d5c7de9a 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -436,13 +436,23 @@ def list_pull_requests(*,team: Team,date_from: str | None = None,+ date_to: str | None = None,author: str | None = None,+ state: str | None = None,+ limit: int | None = None,+ offset: int | None = None,source_id: str | None = None,repo: str | None = None,user_access_control: "UserAccessControl | None" = None,) -> PullRequestList:return logic.build_pull_request_list(- curated=_authorized_source(team, source_id, user_access_control, repo=repo), date_from=date_from, author=author+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),+ date_from=date_from,+ date_to=date_to,+ author=author,+ state=state,+ limit=limit,+ offset=offset,)diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex e4701056b4cb..61b781501837 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -956,7 +956,7 @@ class PullRequestListItem:class PullRequestList:"""A page of the PR list plus an explicit truncation signal. ``items`` is cappedat ``limit`` (newest first); ``truncated`` is True when more pull requests match- than the cap. Surfaced so a consumer never mistakes a capped page for the whole+ after this page. Surfaced so a consumer never mistakes a capped page for the wholeset — the aggregate counts in ``CICardSummary`` can legitimately exceed``len(items)`` when ``truncated`` is True."""diff --git a/products/engineering_analytics/backend/logic/pull_requests.py b/products/engineering_analytics/backend/logic/pull_requests.pyindex eea0cf2c7e9e..7a8c272bab63 100644--- a/products/engineering_analytics/backend/logic/pull_requests.py+++ b/products/engineering_analytics/backend/logic/pull_requests.py@@ -13,6 +13,7 @@ from products.engineering_analytics.backend.facade.contracts import (MergedPullRequest,PRCostSummary,PRLifecycle,+ PRState,PullRequestList,WorkflowCost,WorkflowRunDetail,@@ -105,10 +106,32 @@ def build_ci_cards(*, curated: CuratedGitHubSource) -> CICardSummary:def build_pull_request_list(- *, curated: CuratedGitHubSource, date_from: str | None = None, author: str | None = None+ *,+ curated: CuratedGitHubSource,+ date_from: str | None = None,+ date_to: str | None = None,+ author: str | None = None,+ state: str | None = None,+ limit: int | None = None,+ offset: int | None = None,) -> PullRequestList:parsed_from = _parse_date(curated.team, date_from or _DEFAULT_WINDOW)- return query_pull_request_list(curated=curated, date_from=parsed_from, author=author)+ parsed_to = _parse_date(curated.team, date_to) if date_to else None+ if parsed_to is not None and parsed_to < parsed_from:+ raise ValueError("date_to must be on or after date_from")+ try:+ parsed_state = PRState(state) if state else None+ except ValueError:+ raise ValueError(f"state must be one of: {', '.join(s.value for s in PRState)}") from None+ return query_pull_request_list(+ curated=curated,+ date_from=parsed_from,+ date_to=parsed_to,+ author=author,+ state=parsed_state,+ limit=limit,+ offset=offset or 0,+ )def build_attention_pull_requests(*, curated: CuratedGitHubSource) -> AttentionPullRequestList:diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_list.py b/products/engineering_analytics/backend/logic/queries/pull_request_list.pyindex 54c9935e0296..30543ea8aa00 100644--- a/products/engineering_analytics/backend/logic/queries/pull_request_list.py+++ b/products/engineering_analytics/backend/logic/queries/pull_request_list.py@@ -5,6 +5,11 @@ finished work; open PRs are always included regardless of age). Ordered newestfirst, capped at ``_LIMIT``. The query fetches ``_LIMIT + 1`` rows so an overflow isdetectable, and the result reports ``truncated`` rather than silently dropping thetail (the aggregate counts in ``ci_cards`` can then legitimately exceed the list).++A ``state`` narrows the list to one state and orders it by that state's own timestamp+(``merged_at`` for merged, ``closed_at`` for closed), so the cap covers only those rows.+Every ordering ends on the PR key, so ``limit`` / ``offset`` pages never skip or repeat+a row when two PRs share a timestamp."""from datetime import datetime@@ -39,19 +44,36 @@ _ATTENTION_LIMIT = 15_PUSH_HISTORY_LIMIT = 20-def _visible_prs_where(prefix: str, author: str | None) -> str:+def _visible_prs_where(prefix: str, author: str | None, state: PRState | None, has_date_to: bool) -> str:"""The list's row predicate, buildable against the ``pr`` alias (outer WHERE) orunqualified curated PR columns (the runs-rollup scope) — one definition so therollup scope can never drift narrower than the rows it must serve."""++ def in_window(column: str) -> str:+ upper = f" AND {prefix}{column} < {{date_to}}" if has_date_to else ""+ return f"({prefix}{column} >= {{date_from}}{upper})"+author_clause = f"AND {prefix}author_handle = {{author}}" if author else ""- return f"""(- {prefix}state = 'open'- OR {prefix}merged_at >= {{date_from}}- OR {prefix}closed_at >= {{date_from}}- ) {author_clause}"""+ if state == PRState.OPEN:+ state_clause = f"{prefix}state = 'open'"+ elif state == PRState.MERGED:+ state_clause = f"{prefix}state = 'merged' AND {in_window('merged_at')}"+ elif state == PRState.CLOSED:+ state_clause = f"{prefix}state = 'closed' AND {in_window('closed_at')}"+ else:+ state_clause = f"{prefix}state = 'open' OR {in_window('merged_at')} OR {in_window('closed_at')}"+ return f"({state_clause}) {author_clause}"+++_ORDER_COLUMN_BY_STATE = {PRState.MERGED: "merged_at", PRState.CLOSED: "closed_at"}-_SELECT = f"""+def _order_by(state: PRState | None) -> str:+ timestamp = _ORDER_COLUMN_BY_STATE.get(state, "created_at") if state else "created_at"+ return f"pr.{timestamp} DESC, pr.number DESC, pr.repo_owner, pr.repo_name"+++_SELECT = """SELECTpr.number, pr.title, pr.repo_owner, pr.repo_name,pr.author_handle, pr.author_avatar_url, pr.is_bot,@@ -71,7 +93,7 @@ _SELECT = f"""__READY_JOIN__WHERE __ROWS__ORDER BY __ORDER_BY__- LIMIT __LIMIT__+ LIMIT __LIMIT__ OFFSET __OFFSET__"""@@ -189,6 +211,7 @@ def _query_rows(rows_where: str,order_by: str,limit: int,+ offset: int = 0,query_type: str,placeholders: dict[str, ast.Expr],ready: ReadyToMergeSql,@@ -203,6 +226,7 @@ def _query_rows(.replace("__ROWS__", rows_where).replace("__ORDER_BY__", order_by).replace("__LIMIT__", str(limit))+ .replace("__OFFSET__", str(offset)))response = curated.run(curated.pr_rollup_query(select, pr_scope_where=scope_where, ready=ready),@@ -224,23 +248,39 @@ def _enrich(*, curated: CuratedGitHubSource, rows: list[tuple]) -> list[PullRequdef query_pull_request_list(- *, curated: CuratedGitHubSource, date_from: datetime, author: str | None = None+ *,+ curated: CuratedGitHubSource,+ date_from: datetime,+ date_to: datetime | None = None,+ author: str | None = None,+ state: PRState | None = None,+ limit: int | None = None,+ offset: int = 0,) -> PullRequestList:+ page_size = _LIMIT if limit is None else limit+ if not 1 <= page_size <= _LIMIT:+ raise ValueError(f"limit must be between 1 and {_LIMIT}")+ if offset < 0:+ raise ValueError("offset must be zero or greater")+placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}+ if date_to is not None:+ placeholders["date_to"] = ast.Constant(value=date_to)if author:placeholders["author"] = ast.Constant(value=author)rows = _query_rows(curated=curated,- scope_where=_visible_prs_where("", author),- rows_where=_visible_prs_where("pr.", author),- order_by="pr.created_at DESC",- limit=_LIMIT + 1,+ scope_where=_visible_prs_where("", author, state, date_to is not None),+ rows_where=_visible_prs_where("pr.", author, state, date_to is not None),+ order_by=_order_by(state),+ limit=page_size + 1,+ offset=offset,query_type="engineering_analytics.pull_request_list",placeholders=placeholders,ready=curated.ready_to_merge_sql(),)return PullRequestList(- items=_enrich(curated=curated, rows=rows[:_LIMIT]), truncated=len(rows) > _LIMIT, limit=_LIMIT+ items=_enrich(curated=curated, rows=rows[:page_size]), truncated=len(rows) > page_size, limit=page_size)diff --git a/products/engineering_analytics/backend/presentation/serializers/pull_requests.py b/products/engineering_analytics/backend/presentation/serializers/pull_requests.pyindex fece39fac0c0..f0f1d9738074 100644--- a/products/engineering_analytics/backend/presentation/serializers/pull_requests.py+++ b/products/engineering_analytics/backend/presentation/serializers/pull_requests.py@@ -291,14 +291,16 @@ class PullRequestListItemSerializer(DataclassSerializer):class PullRequestListSerializer(DataclassSerializer):- items = PullRequestListItemSerializer(many=True, help_text="Pull requests, newest first, capped at `limit`.")+ items = PullRequestListItemSerializer(+ many=True, help_text="This page of pull requests, newest first, capped at `limit`."+ )class Meta:dataclass = PullRequestListextra_kwargs = {"truncated": {- "help_text": "True when more pull requests match than the cap; `items` is the newest `limit` rows "- "and the aggregate counts in ci_cards can exceed it.",+ "help_text": "True when more pull requests match after this page; call again with `offset` "+ "increased by `limit` to read them. The aggregate counts in ci_cards can exceed `items`.",},"limit": {"help_text": "Maximum number of pull requests returned in `items`."},}diff --git a/products/engineering_analytics/backend/presentation/views/pull_requests.py b/products/engineering_analytics/backend/presentation/views/pull_requests.pyindex 53f8cb17339b..7b08c9aa2d9f 100644--- a/products/engineering_analytics/backend/presentation/views/pull_requests.py+++ b/products/engineering_analytics/backend/presentation/views/pull_requests.py@@ -8,6 +8,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom products.engineering_analytics.backend.facade import api+from products.engineering_analytics.backend.facade.contracts import PRStatefrom products.engineering_analytics.backend.presentation.serializers.pull_requests import (AttentionPullRequestListSerializer,BranchPRMatchSerializer,@@ -27,6 +28,7 @@ from products.engineering_analytics.backend.presentation.views._base import (EngineeringAnalyticsViewSetBase,_bad_request,_optional_datetime_param,+ _optional_int_param,_require_int_param,)@@ -81,19 +83,57 @@ class PullRequestActionsMixin(EngineeringAnalyticsViewSetBase):required=False,description="Optional GitHub login to scope the list to one author's pull requests.",),+ OpenApiParameter(+ name="state",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ enum=[state.value for state in PRState],+ description=(+ "Optional state filter. 'merged' lists PRs merged in the window, newest merged_at first. "+ "'closed' lists PRs closed without a merge in the window, newest closed_at first. 'open' lists "+ "all open PRs whatever their age, newest first. Omit it to get open PRs plus any merged or "+ "closed in the window."+ ),+ ),+ OpenApiParameter(+ name="date_to",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description=(+ "Optional exclusive upper bound for merged_at / closed_at: relative or ISO8601. Defaults to "+ "now. Set a fixed value when you page, so new merges do not move rows between pages."+ ),+ ),+ OpenApiParameter(+ name="limit",+ type=OpenApiTypes.INT,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Page size, 1 to 1000. Defaults to 1000.",+ ),+ OpenApiParameter(+ name="offset",+ type=OpenApiTypes.INT,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Number of rows to skip. Defaults to 0. While `truncated` is true, add `limit` to "+ "offset to read the next page.",+ ),_SOURCE_ID,_REPO,],responses={200: PullRequestListSerializer,- 400: OpenApiResponse(description="Invalid date_from or source_id."),+ 400: OpenApiResponse(description="Invalid date_from, date_to, state, limit, offset, or source_id."),},description=("Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with "- "its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards "- "counts can exceed it. open_to_merge_seconds is coarse: it fuses draft and ready-for-review time; "- "CI counts can lag until late completions settle. Cost and billable minutes can lag new CI by up to "- "5 minutes."+ "its head-SHA CI rollup. Pass state to list one state only. The list is paged by limit and offset; "+ "when more match, `truncated` is true and the ci_cards counts can exceed it. open_to_merge_seconds is "+ "coarse: it fuses draft and ready-for-review time; CI counts can lag until late completions settle. "+ "Cost and billable minutes can lag new CI by up to 5 minutes."),)@action(detail=False, methods=["get"], pagination_class=None)@@ -102,13 +142,17 @@ class PullRequestActionsMixin(EngineeringAnalyticsViewSetBase):result = api.list_pull_requests(team=self.team,date_from=request.query_params.get("date_from") or None,+ date_to=request.query_params.get("date_to") or None,author=request.query_params.get("author") or None,+ state=request.query_params.get("state") or None,+ limit=_optional_int_param(request, "limit"),+ offset=_optional_int_param(request, "offset"),source_id=request.query_params.get("source_id") or None,repo=request.query_params.get("repo") or None,user_access_control=self.user_access_control,)except ValueError as exc:- return _bad_request(exc, fallback="Invalid date_from or source_id")+ return _bad_request(exc, fallback="Invalid date_from, date_to, state, limit, offset, or source_id")return Response(PullRequestListSerializer(instance=result).data)@extend_schema(diff --git a/products/engineering_analytics/backend/tests/test_logic_pull_requests.py b/products/engineering_analytics/backend/tests/test_logic_pull_requests.pyindex 02381a14d785..4750f40eed06 100644--- a/products/engineering_analytics/backend/tests/test_logic_pull_requests.py+++ b/products/engineering_analytics/backend/tests/test_logic_pull_requests.py@@ -260,6 +260,20 @@ class TestPullRequestEndpointMapping(BaseTest):assert result.limit == 2assert len(result.items) == 2+ @parameterized.expand(+ [+ ("limit_zero", {"limit": 0}),+ ("limit_over_cap", {"limit": 1001}),+ ("negative_offset", {"offset": -1}),+ ("unknown_state", {"state": "draft"}),+ ("date_to_before_date_from", {"date_from": "-7d", "date_to": "-14d"}),+ ]+ )+ def test_pull_request_list_rejects_invalid_paging(self, _name: str, kwargs: dict[str, Any]) -> None:+ with mock.patch(_RUN_QUERY) as run, self.assertRaises(ValueError):+ api.list_pull_requests(team=self.team, **kwargs)+ run.assert_not_called()+class TestResolveBranchMapping(BaseTest):"""Row mapping for resolve_branch (query method mocked, no warehouse). A GitHub source is@@ -503,6 +517,42 @@ class TestPullRequestEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):assert {i.number for i in api.list_pull_requests(team=self.team, author="alice").items} == {81}assert {i.number for i in api.list_pull_requests(team=self.team, author="bob").items} == {82}+ def test_pull_request_list_pages_merged_prs_by_merged_at(self) -> None:+ # PR 21 was opened long ago but merged recently: it must lead the merged page, not sink below+ # the open backlog. 22 and 23 merge in the same second, so only the number tie-breaker keeps+ # them from swapping across pages.+ tied_merge = _ago(3)+ self._create_table(+ "github_pull_requests",+ PULL_REQUESTS_COLUMNS,+ [+ _pr_row(20, "alice", "open", 0, _ago(1), head_sha="sha20"),+ _pr_row(21, "alice", "closed", 0, _ago(40), merged_at=_ago(2), head_sha="sha21"),+ _pr_row(22, "bob", "closed", 0, _ago(5), merged_at=tied_merge, head_sha="sha22"),+ _pr_row(23, "bob", "closed", 0, _ago(4), merged_at=tied_merge, head_sha="sha23"),+ _pr_row(24, "carol", "closed", 0, _ago(5), closed_at=_ago(2), head_sha="sha24"),+ _pr_row(25, "carol", "closed", 0, _ago(30), merged_at=_ago(20), head_sha="sha25"),+ _pr_row(26, "carol", "closed", 0, _ago(1), merged_at=_ago(0), head_sha="sha26"),+ ],+ )+ self._create_table(+ "github_workflow_runs",+ WORKFLOW_RUNS_COLUMNS,+ [_run_row(2100, "CI", "sha21", "completed", "success", _ago(2), _ago(2), pr_number=21)],+ )+ first = api.list_pull_requests(+ team=self.team, state="merged", date_from="-14d", date_to=_ago(1), limit=2, offset=0+ )+ second = api.list_pull_requests(+ team=self.team, state="merged", date_from="-14d", date_to=_ago(1), limit=2, offset=2+ )++ assert ([i.number for i in first.items], first.truncated) == ([21, 23], True)+ assert ([i.number for i in second.items], second.truncated) == ([22], False)+ assert first.items[0].ci.passing == 1+ closed = api.list_pull_requests(team=self.team, state="closed", date_from="-14d")+ assert [i.number for i in closed.items] == [24]+def test_resolve_branch_orders_open_first(self) -> None:# The branch path matches the PR head ref (head.ref); open PRs come before merged/closed ones,# and PRs on other branches are excluded.diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex 54989aad40fb..f1f3ee25ac7b 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -1435,9 +1435,9 @@ export interface PullRequestTimelinesApi {}export interface PullRequestListApi {- /** Pull requests, newest first, capped at `limit`. */+ /** This page of pull requests, newest first, capped at `limit`. */items: PullRequestListItemApi[]- /** True when more pull requests match than the cap; `items` is the newest `limit` rows and the aggregate counts in ci_cards can exceed it. */+ /** True when more pull requests match after this page; call again with `offset` increased by `limit` to read them. The aggregate counts in ci_cards can exceed `items`. */truncated: boolean/** Maximum number of pull requests returned in `items`. */limit: number@@ -2761,6 +2761,18 @@ export type EngineeringAnalyticsPullRequestsParams = {* Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.*/date_from?: string+ /**+ * Optional exclusive upper bound for merged_at / closed_at: relative or ISO8601. Defaults to now. Set a fixed value when you page, so new merges do not move rows between pages.+ */+ date_to?: string+ /**+ * Page size, 1 to 1000. Defaults to 1000.+ */+ limit?: number+ /**+ * Number of rows to skip. Defaults to 0. While `truncated` is true, add `limit` to offset to read the next page.+ */+ offset?: number/*** 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.*/@@ -2769,8 +2781,21 @@ export type EngineeringAnalyticsPullRequestsParams = {* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/source_id?: string+ /**+ * Optional state filter. 'merged' lists PRs merged in the window, newest merged_at first. 'closed' lists PRs closed without a merge in the window, newest closed_at first. 'open' lists all open PRs whatever their age, newest first. Omit it to get open PRs plus any merged or closed in the window.+ */+ state?: EngineeringAnalyticsPullRequestsState}+export type EngineeringAnalyticsPullRequestsState =+ (typeof EngineeringAnalyticsPullRequestsState)[keyof typeof EngineeringAnalyticsPullRequestsState]++export const EngineeringAnalyticsPullRequestsState = {+ Closed: 'closed',+ Merged: 'merged',+ Open: 'open',+} as const+export type EngineeringAnalyticsQuarantineParams = {/*** Optional 'owner/name' repository to read the quarantine file from. Defaults to the connected GitHub source's most active repo over the last 30 days.diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex fdd3a2c91d91..2ea60c25a5b6 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -764,7 +764,7 @@ export const getEngineeringAnalyticsPullRequestsUrl = (}/**- * Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards counts can exceed it. open_to_merge_seconds is coarse: it fuses draft and ready-for-review time; CI counts can lag until late completions settle. Cost and billable minutes can lag new CI by up to 5 minutes.+ * Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with its head-SHA CI rollup. Pass state to list one state only. The list is paged by limit and offset; when more match, `truncated` is true and the ci_cards counts can exceed it. open_to_merge_seconds is coarse: it fuses draft and ready-for-review time; CI counts can lag until late completions settle. Cost and billable minutes can lag new CI by up to 5 minutes.*/export const engineeringAnalyticsPullRequests = async (projectId: string,diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yamlindex 935dbf5a83e9..0b89b29bb363 100644--- a/products/engineering_analytics/mcp/tools.yaml+++ b/products/engineering_analytics/mcp/tools.yaml@@ -369,7 +369,10 @@ tools:verifiably never drafted. Null means "not observed" (the issue-events window is bounded), never zero. CIcounts come from the latest run per workflow on the head SHA and can lag until the workflow_run webhooksettles a late completion. Cost and billable minutes can lag new CI by up to 5 minutes. Bots and drafts are- present; exclude them (author.is_bot, is_draft) for throughput questions.+ present; exclude them (author.is_bot, is_draft) for throughput questions. To list every PR merged in a+ window, pass state=merged: open PRs then do not count against the page, and rows come newest merged_at first+ with number as the tie-breaker. Pages hold up to 1000 rows; while truncated is true, call again with offset+ increased by limit, and keep date_to fixed across pages so new merges do not move rows between pages.param_overrides:date_from:description: >diff --git a/products/signals/skills/signals-scout-pr-follow-up/references/sources.md b/products/signals/skills/signals-scout-pr-follow-up/references/sources.mdindex efaf01ac48ec..42742f3fb7ff 100644--- a/products/signals/skills/signals-scout-pr-follow-up/references/sources.md+++ b/products/signals/skills/signals-scout-pr-follow-up/references/sources.md@@ -21,8 +21,13 @@ List the PRs with `gh` exactly as rung 3 describes.`engineering-analytics-sources` lists each configured `owner/repo` with its `source_id`, table prefix, and a `synced` flag.`synced: true` means both the pull-request and workflow-run tables exist; this scout needs only the first, so a `synced: false` entry can still carry a readable `<prefix>github_pull_requests` table (a source that never synced workflow runs): prefer a synced entry when one repository appears under several sources, and otherwise confirm the pull-request table itself in `system.information_schema.tables` before you give the source up.-`pull-requests` (`date_from` set to the window start, `-14d` at its narrowest, pass `source_id` and `repo`) returns open PRs plus those merged in the window with their CI rollup, newest first, capped at 1,000 rows; open PRs count against the cap, so on a busy repository the page holds a few days of merges, not 14, and carries `truncated: true`.-Treat that flag as the signal to list from the raw table instead:+For a `synced: true` entry, `pull-requests` with `state: "merged"`, `date_from` set to the window start (`-14d` at its narrowest), `date_to` set to a fixed ISO8601 time at the start of the run, `source_id`, and `repo` lists only the PRs merged in the window, with their CI rollup, newest `merged_at` first.+A page holds up to 1,000 rows; while it comes back with `truncated: true`, call again with `offset` increased by `limit` and the same `date_to`.+The fixed `date_to` keeps a merge that lands during the run from moving rows between pages, and the `number` tie-breaker keeps the order total, so no PR is skipped or listed twice when two merges share a second.+Stop when a page comes back with `truncated: false`; the window is then covered.++A `synced: false` entry has no tool listing: `pull-requests` needs the workflow-run table too and answers 400 without it.+List from the confirmed pull-request table instead, bounded by the same fixed run-start time:```sqlSELECT number, toString(title) AS title,@@ -32,13 +37,15 @@ SELECT number, toString(title) AS title,FROM `<prefix>github_pull_requests`WHERE merged_at IS NOT NULL AND merged_at != ''AND parseDateTimeBestEffort(merged_at) >= toDateTime('<window start>', 'UTC')+ AND parseDateTimeBestEffort(merged_at) < toDateTime('<run start>', 'UTC')ORDER BY parseDateTimeBestEffort(merged_at) DESC, number DESC-LIMIT 500+LIMIT 500 OFFSET <page * 500>```-`title` and `body` are JSON columns (`toString(title)`, `toString(body)`), `user` is a JSON-encoded string that only `JSONExtractString(user, 'login')` and `JSONExtractString(user, 'type') = 'Bot'` can read (a dotted `user.login` fails on this table, exactly when the tool listing was truncated), timestamps are strings, and `merge_commit_sha` can be null, so the merge SHA for the containment check still comes from the detail fetch below.+Take the next page until one comes back with fewer than 500 rows; the `number` tie-breaker keeps this order total too.++When you read the raw table (this listing, or a column the tool does not return), `title` and `body` are JSON columns (`toString(title)`, `toString(body)`), `user` is a JSON-encoded string that only `JSONExtractString(user, 'login')` and `JSONExtractString(user, 'type') = 'Bot'` can read (a dotted `user.login` fails on this table), timestamps are strings, and `merge_commit_sha` can be null, so the merge SHA for the containment check still comes from the detail fetch below.Quote the table name in backticks as shown: a flattened multi-repository name keeps the repository's hyphens, and a bare `owner_my-repo__pull_requests` parses as arithmetic.-Page with `OFFSET` to the window boundary; the `number` tie-breaker keeps the order total, because two merges in the same second would otherwise swap across pages and one of them would never be listed.`pr-lifecycle` gives one PR's timeline.The prefix also names warehouse tables you can read with `execute-sql`: `<prefix>github_pull_requests`, and, when the project syncs the deployments endpoints, `<prefix>github_deployments` and `<prefix>github_deployment_statuses` (the best deploy signal you can get; see `deploy-ladder.md`).diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 1a3381be0dc3..388883bf52b2 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -9849,7 +9849,7 @@}},"pull-requests": {- "description": "Open pull requests plus any merged or closed within the window, newest first, each with its head-SHA CI rollup (runs / passing / failing / pending). Use this for \"which PRs are stuck\", \"which open PRs have failing or pending CI\", and per-author or per-repo PR triage. open_to_merge_seconds is coarse: it is merged_at minus created_at and fuses draft and ready-for-review time, so report it as \"open to merge\", never \"cycle time\". ready_to_merge_seconds is the true cycle time: merged_at minus the last observed ready-for-review transition (only the last draft/ready switch counts), or minus created_at for a merged PR verifiably never drafted. Null means \"not observed\" (the issue-events window is bounded), never zero. CI counts come from the latest run per workflow on the head SHA and can lag until the workflow_run webhook settles a late completion. Cost and billable minutes can lag new CI by up to 5 minutes. Bots and drafts are present; exclude them (author.is_bot, is_draft) for throughput questions.",+ "description": "Open pull requests plus any merged or closed within the window, newest first, each with its head-SHA CI rollup (runs / passing / failing / pending). Use this for \"which PRs are stuck\", \"which open PRs have failing or pending CI\", and per-author or per-repo PR triage. open_to_merge_seconds is coarse: it is merged_at minus created_at and fuses draft and ready-for-review time, so report it as \"open to merge\", never \"cycle time\". ready_to_merge_seconds is the true cycle time: merged_at minus the last observed ready-for-review transition (only the last draft/ready switch counts), or minus created_at for a merged PR verifiably never drafted. Null means \"not observed\" (the issue-events window is bounded), never zero. CI counts come from the latest run per workflow on the head SHA and can lag until the workflow_run webhook settles a late completion. Cost and billable minutes can lag new CI by up to 5 minutes. Bots and drafts are present; exclude them (author.is_bot, is_draft) for throughput questions. To list every PR merged in a window, pass state=merged: open PRs then do not count against the page, and rows come newest merged_at first with number as the tie-breaker. Pages hold up to 1000 rows; while truncated is true, call again with offset increased by limit, and keep date_to fixed across pages so new merges do not move rows between pages.","category": "Engineering analytics","feature": "engineering_analytics","summary": "List pull requests with CI status",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 0ba0202030d5..414aadd1a875 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -10440,7 +10440,7 @@}},"pull-requests": {- "description": "Open pull requests plus any merged or closed within the window, newest first, each with its head-SHA CI rollup (runs / passing / failing / pending). Use this for \"which PRs are stuck\", \"which open PRs have failing or pending CI\", and per-author or per-repo PR triage. open_to_merge_seconds is coarse: it is merged_at minus created_at and fuses draft and ready-for-review time, so report it as \"open to merge\", never \"cycle time\". ready_to_merge_seconds is the true cycle time: merged_at minus the last observed ready-for-review transition (only the last draft/ready switch counts), or minus created_at for a merged PR verifiably never drafted. Null means \"not observed\" (the issue-events window is bounded), never zero. CI counts come from the latest run per workflow on the head SHA and can lag until the workflow_run webhook settles a late completion. Cost and billable minutes can lag new CI by up to 5 minutes. Bots and drafts are present; exclude them (author.is_bot, is_draft) for throughput questions.",+ "description": "Open pull requests plus any merged or closed within the window, newest first, each with its head-SHA CI rollup (runs / passing / failing / pending). Use this for \"which PRs are stuck\", \"which open PRs have failing or pending CI\", and per-author or per-repo PR triage. open_to_merge_seconds is coarse: it is merged_at minus created_at and fuses draft and ready-for-review time, so report it as \"open to merge\", never \"cycle time\". ready_to_merge_seconds is the true cycle time: merged_at minus the last observed ready-for-review transition (only the last draft/ready switch counts), or minus created_at for a merged PR verifiably never drafted. Null means \"not observed\" (the issue-events window is bounded), never zero. CI counts come from the latest run per workflow on the head SHA and can lag until the workflow_run webhook settles a late completion. Cost and billable minutes can lag new CI by up to 5 minutes. Bots and drafts are present; exclude them (author.is_bot, is_draft) for throughput questions. To list every PR merged in a window, pass state=merged: open PRs then do not count against the page, and rows come newest merged_at first with number as the tie-breaker. Pages hold up to 1000 rows; while truncated is true, call again with offset increased by limit, and keep date_to fixed across pages so new merges do not move rows between pages.","category": "Engineering analytics","feature": "engineering_analytics","summary": "List pull requests with CI status",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a9bf3f8fde33..fb69ca67ce6b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -85767,9 +85767,9 @@ export namespace Schemas {}export interface PullRequestList {- /** Pull requests, newest first, capped at `limit`. */+ /** This page of pull requests, newest first, capped at `limit`. */items: PullRequestListItem[];- /** True when more pull requests match than the cap; `items` is the newest `limit` rows and the aggregate counts in ci_cards can exceed it. */+ /** True when more pull requests match after this page; call again with `offset` increased by `limit` to read them. The aggregate counts in ci_cards can exceed `items`. */truncated: boolean;/** Maximum number of pull requests returned in `items`. */limit: number;@@ -114860,6 +114860,18 @@ export namespace Schemas {* Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.*/date_from?: string;+ /**+ * Optional exclusive upper bound for merged_at / closed_at: relative or ISO8601. Defaults to now. Set a fixed value when you page, so new merges do not move rows between pages.+ */+ date_to?: string;+ /**+ * Page size, 1 to 1000. Defaults to 1000.+ */+ limit?: number;+ /**+ * Number of rows to skip. Defaults to 0. While `truncated` is true, add `limit` to offset to read the next page.+ */+ offset?: number;/*** 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.*/@@ -114868,8 +114880,21 @@ export namespace Schemas {* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.*/source_id?: string;+ /**+ * Optional state filter. 'merged' lists PRs merged in the window, newest merged_at first. 'closed' lists PRs closed without a merge in the window, newest closed_at first. 'open' lists all open PRs whatever their age, newest first. Omit it to get open PRs plus any merged or closed in the window.+ */+ state?: EngineeringAnalyticsPullRequestsState;};+ export type EngineeringAnalyticsPullRequestsState = typeof EngineeringAnalyticsPullRequestsState[keyof typeof EngineeringAnalyticsPullRequestsState];+++ export const EngineeringAnalyticsPullRequestsState = {+ Closed: 'closed',+ Merged: 'merged',+ Open: 'open',+ } as const;+export type EngineeringAnalyticsQuarantineParams = {/*** Optional 'owner/name' repository to read the quarantine file from. Defaults to the connected GitHub source's most active repo over the last 30 days.diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.tsindex c05a2ac18cc4..170c10bcab3d 100644--- a/services/mcp/src/generated/engineering_analytics/api.ts+++ b/services/mcp/src/generated/engineering_analytics/api.ts@@ -142,7 +142,7 @@ export const EngineeringAnalyticsPrLifecycleQueryParams = () => zod.object({})/**- * Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards counts can exceed it. open_to_merge_seconds is coarse: it fuses draft and ready-for-review time; CI counts can lag until late completions settle. Cost and billable minutes can lag new CI by up to 5 minutes.+ * Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with its head-SHA CI rollup. Pass state to list one state only. The list is paged by limit and offset; when more match, `truncated` is true and the ci_cards counts can exceed it. open_to_merge_seconds is coarse: it fuses draft and ready-for-review time; CI counts can lag until late completions settle. Cost and billable minutes can lag new CI by up to 5 minutes.*/export const EngineeringAnalyticsPullRequestsParams = () => zod.object({project_id: zod@@ -155,6 +155,19 @@ export const EngineeringAnalyticsPullRequestsParams = () => zod.object({export const EngineeringAnalyticsPullRequestsQueryParams = () => zod.object({author: zod.string().optional().describe("Optional GitHub login to scope the list to one author's pull requests."),date_from: zod.string().optional().describe("Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d."),+ date_to: zod+ .string()+ .optional()+ .describe(+ 'Optional exclusive upper bound for merged_at \/ closed_at: relative or ISO8601. Defaults to now. Set a fixed value when you page, so new merges do not move rows between pages.'+ ),+ limit: zod.number().optional().describe('Page size, 1 to 1000. Defaults to 1000.'),+ offset: zod+ .number()+ .optional()+ .describe(+ 'Number of rows to skip. Defaults to 0. While `truncated` is true, add `limit` to offset to read the next page.'+ ),repo: zod.string().optional()@@ -167,6 +180,12 @@ export const EngineeringAnalyticsPullRequestsQueryParams = () => zod.object({.describe('Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'),+ state: zod+ .enum(['closed', 'merged', 'open'])+ .optional()+ .describe(+ "Optional state filter. 'merged' lists PRs merged in the window, newest merged_at first. 'closed' lists PRs closed without a merge in the window, newest closed_at first. 'open' lists all open PRs whatever their age, newest first. Omit it to get open PRs plus any merged or closed in the window."+ ),})/**diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.tsindex 0353d71f9ac2..091a25a6fb1c 100644--- a/services/mcp/src/tools/generated/engineering_analytics.ts+++ b/services/mcp/src/tools/generated/engineering_analytics.ts@@ -292,8 +292,12 @@ const pullRequests = (): ToolBase<ReturnType<typeof PullRequestsSchema>, WithPosquery: {author: params.author,date_from: params.date_from,+ date_to: params.date_to,+ limit: params.limit,+ offset: params.offset,repo: params.repo,source_id: params.source_id,+ state: params.state,},})return await withPostHogUrl(context, result, '/engineering-analytics')