github-statistics 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. github_statistics/__init__.py +14 -0
  2. github_statistics/__main__.py +10 -0
  3. github_statistics/_version.py +24 -0
  4. github_statistics/cli/__init__.py +9 -0
  5. github_statistics/cli/app.py +104 -0
  6. github_statistics/cli/cache.py +159 -0
  7. github_statistics/cli/collect.py +219 -0
  8. github_statistics/cli/common.py +128 -0
  9. github_statistics/cli/config.py +80 -0
  10. github_statistics/cli/doctor.py +214 -0
  11. github_statistics/cli/export.py +111 -0
  12. github_statistics/cli/options.py +175 -0
  13. github_statistics/cli/render.py +126 -0
  14. github_statistics/cli/run.py +137 -0
  15. github_statistics/cli/scope.py +96 -0
  16. github_statistics/cli/site.py +150 -0
  17. github_statistics/client/__init__.py +40 -0
  18. github_statistics/client/accounting.py +99 -0
  19. github_statistics/client/budget.py +125 -0
  20. github_statistics/client/cooldown.py +113 -0
  21. github_statistics/client/errors.py +60 -0
  22. github_statistics/client/graphql.py +281 -0
  23. github_statistics/client/paging.py +92 -0
  24. github_statistics/client/policy.py +243 -0
  25. github_statistics/client/transport.py +437 -0
  26. github_statistics/collect/__init__.py +44 -0
  27. github_statistics/collect/common.py +69 -0
  28. github_statistics/collect/enrich_items.py +423 -0
  29. github_statistics/collect/items.py +238 -0
  30. github_statistics/collect/jobs.py +194 -0
  31. github_statistics/collect/listed.py +42 -0
  32. github_statistics/collect/members.py +70 -0
  33. github_statistics/collect/reader.py +124 -0
  34. github_statistics/collect/run.py +354 -0
  35. github_statistics/collect/runs.py +436 -0
  36. github_statistics/collect/slices.py +55 -0
  37. github_statistics/collect/steps.py +154 -0
  38. github_statistics/collect/sweep.py +70 -0
  39. github_statistics/config/__init__.py +37 -0
  40. github_statistics/config/loader.py +430 -0
  41. github_statistics/config/models.py +156 -0
  42. github_statistics/config/schema.py +245 -0
  43. github_statistics/export/__init__.py +11 -0
  44. github_statistics/export/csv.py +93 -0
  45. github_statistics/export/documents.py +189 -0
  46. github_statistics/export/json.py +33 -0
  47. github_statistics/py.typed +2 -0
  48. github_statistics/render/__init__.py +44 -0
  49. github_statistics/render/bars3d.py +420 -0
  50. github_statistics/render/charts.py +214 -0
  51. github_statistics/render/demo.py +133 -0
  52. github_statistics/render/images.py +31 -0
  53. github_statistics/render/layout.py +341 -0
  54. github_statistics/render/model.py +260 -0
  55. github_statistics/render/palette.py +41 -0
  56. github_statistics/scope/__init__.py +17 -0
  57. github_statistics/scope/apply.py +95 -0
  58. github_statistics/scope/resolver.py +228 -0
  59. github_statistics/series/__init__.py +22 -0
  60. github_statistics/series/actors.py +128 -0
  61. github_statistics/series/coverage.py +86 -0
  62. github_statistics/series/daily.py +229 -0
  63. github_statistics/series/leaderboard.py +221 -0
  64. github_statistics/series/repositories.py +154 -0
  65. github_statistics/site/__init__.py +9 -0
  66. github_statistics/site/assets/site.css +281 -0
  67. github_statistics/site/build.py +392 -0
  68. github_statistics/site/templates/base.html.j2 +25 -0
  69. github_statistics/site/templates/index.html.j2 +30 -0
  70. github_statistics/site/templates/macros.html.j2 +5 -0
  71. github_statistics/site/templates/site.js.j2 +66 -0
  72. github_statistics/site/templates/target.html.j2 +95 -0
  73. github_statistics/store/__init__.py +40 -0
  74. github_statistics/store/activity.py +311 -0
  75. github_statistics/store/aggregates.py +294 -0
  76. github_statistics/store/base.py +163 -0
  77. github_statistics/store/codec.py +263 -0
  78. github_statistics/store/models.py +136 -0
  79. github_statistics/store/paths.py +36 -0
  80. github_statistics/store/schema.py +169 -0
  81. github_statistics/store/sqlite.py +299 -0
  82. github_statistics-0.1.0.dist-info/METADATA +308 -0
  83. github_statistics-0.1.0.dist-info/RECORD +86 -0
  84. github_statistics-0.1.0.dist-info/WHEEL +4 -0
  85. github_statistics-0.1.0.dist-info/entry_points.txt +2 -0
  86. github_statistics-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,44 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Collectors: read GitHub listings into the store (design §6)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from .enrich_items import EnrichResult, enrich_items
8
+ from .items import (
9
+ ISSUES_METRIC,
10
+ ITEMS_METRIC,
11
+ PULL_REQUESTS_METRIC,
12
+ ItemSyncResult,
13
+ sync_all_items,
14
+ sync_items,
15
+ )
16
+ from .jobs import JobsResult, enrich_jobs
17
+ from .members import sync_members
18
+ from .run import CollectResult, MetricCoverage, collect
19
+ from .runs import RUNS_METRIC, RunSyncResult, runs_horizon, sync_all_runs, sync_runs
20
+ from .sweep import SweepResult, sweep_runs
21
+
22
+ __all__ = [
23
+ "ISSUES_METRIC",
24
+ "ITEMS_METRIC",
25
+ "PULL_REQUESTS_METRIC",
26
+ "RUNS_METRIC",
27
+ "CollectResult",
28
+ "EnrichResult",
29
+ "ItemSyncResult",
30
+ "JobsResult",
31
+ "MetricCoverage",
32
+ "RunSyncResult",
33
+ "SweepResult",
34
+ "collect",
35
+ "enrich_items",
36
+ "enrich_jobs",
37
+ "runs_horizon",
38
+ "sweep_runs",
39
+ "sync_all_items",
40
+ "sync_all_runs",
41
+ "sync_items",
42
+ "sync_members",
43
+ "sync_runs",
44
+ ]
@@ -0,0 +1,69 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """What every collector shares: repository keys, concurrency, status handling."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ from collections.abc import Coroutine, Iterable
9
+ from datetime import UTC, datetime
10
+ from typing import Any, TypeVar
11
+
12
+ import httpx
13
+
14
+ from github_statistics.client import AuthError
15
+ from github_statistics.client.policy import rate_limited
16
+ from github_statistics.scope import ResolvedScope
17
+ from github_statistics.store import Store
18
+
19
+ UNREADABLE_STATUSES = frozenset({403, 404, 410})
20
+ SERVER_ERROR = 500
21
+
22
+ T = TypeVar("T")
23
+
24
+
25
+ def scope_keys(store: Store, scope: ResolvedScope, now: datetime) -> list[str]:
26
+ """The ``owner/name`` key of each repository in ``scope``.
27
+
28
+ A repository keeps the spelling the store's scope holds for it, as
29
+ names compare without case, so a rename in case alone keeps its
30
+ sync state, records and coverage under one key.
31
+ """
32
+ spellings = {key.lower(): key for key in store.in_scope(now.astimezone(UTC).date())}
33
+ return [
34
+ spellings.get(key.lower(), key)
35
+ for key in (
36
+ f"{scope.owner}/{repository.name}" for repository in scope.repositories
37
+ )
38
+ ]
39
+
40
+
41
+ async def run_concurrently(syncs: Iterable[Coroutine[Any, Any, T]]) -> list[T]:
42
+ """Await ``syncs`` concurrently; their results in order.
43
+
44
+ An error that stops one, ``AuthError`` first, propagates as itself,
45
+ not wrapped in an ``ExceptionGroup``, and cancels the others.
46
+ """
47
+ tasks = []
48
+ try:
49
+ async with asyncio.TaskGroup() as group:
50
+ tasks = [group.create_task(sync) for sync in syncs]
51
+ except ExceptionGroup as failures:
52
+ raise (failures.subgroup(AuthError) or failures).exceptions[0] from None
53
+ return [task.result() for task in tasks]
54
+
55
+
56
+ def unreadable_status(exc: httpx.HTTPStatusError) -> int | None:
57
+ """The status that makes a repository unreadable for this run, if any.
58
+
59
+ ``None`` for a rate limit an unbudgeted transport returned after its
60
+ retries, which stops the sync short like a spent budget. A ``403``
61
+ that is not a rate limit, a ``404``, a ``410`` or a ``5xx`` is
62
+ returned; any other status re-raises ``exc``.
63
+ """
64
+ status = exc.response.status_code
65
+ if rate_limited(exc.response):
66
+ return None
67
+ if status in UNREADABLE_STATUSES or status >= SERVER_ERROR:
68
+ return status
69
+ raise exc
@@ -0,0 +1,423 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: 2026 The Linux Foundation
3
+ """Enrich stored items with reviews, mergers and closers (design §6.3).
4
+
5
+ One GraphQL ``nodes(ids:)`` query reads fifty items, pull requests and
6
+ issues together. The items of a batch needing no further review page
7
+ are stored in one transaction, with the reviews of every pull request
8
+ among them and the merger, closer and read time of every item. A pull
9
+ request with more reviews is put aside until every batch is read, then
10
+ paged and stored on its own, the fewest reviews first.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ from collections.abc import Callable, Iterable
17
+ from dataclasses import dataclass
18
+ from datetime import datetime
19
+ from typing import Any
20
+
21
+ from github_statistics.client import (
22
+ BudgetExhaustedError,
23
+ GraphQLError,
24
+ Transport,
25
+ TransportError,
26
+ batched,
27
+ graphql,
28
+ )
29
+ from github_statistics.client.graphql import TIMEOUT_STATUSES
30
+ from github_statistics.store import Enrichment, Item, Review, Store
31
+
32
+ log = logging.getLogger(__name__)
33
+
34
+ BATCH_SIZE = 50
35
+ # A bound on a batch's cost: GitHub charged one point for this query.
36
+ BATCH_COST = 2
37
+ # GitHub's minimum, what a query reading one item or one page costs.
38
+ PAGE_COST = 1
39
+ # More items than one repository holds, so a run sees them all.
40
+ PER_REPOSITORY = 1_000_000
41
+ GHOST = "ghost"
42
+ GHOST_TYPE = "User"
43
+ # A read node: its id, the rows it marks, the row owning it and its reviews.
44
+ _Read = tuple[str, list[Enrichment], Item | None, list[Any] | None]
45
+ # A pull request put aside to page: its id, marks, owner and first page.
46
+ _Aside = tuple[str, list[Enrichment], Item, dict[str, Any]]
47
+
48
+ _ACTOR = "login __typename"
49
+ _REVIEW = f"id fullDatabaseId author {{ {_ACTOR} }} state submittedAt"
50
+ _PLACE = "number repository { nameWithOwner }"
51
+ _CLOSER = (
52
+ "timelineItems(itemTypes: [CLOSED_EVENT], last: 1) {"
53
+ f" nodes {{ ... on ClosedEvent {{ actor {{ {_ACTOR} }} }} }} }}"
54
+ )
55
+
56
+ ENRICH_QUERY = f"""
57
+ query($ids: [ID!]!) {{
58
+ rateLimit {{ cost remaining }}
59
+ nodes(ids: $ids) {{
60
+ __typename
61
+ ... on PullRequest {{
62
+ id
63
+ {_PLACE}
64
+ mergedBy {{ {_ACTOR} }}
65
+ reviews(first: 50) {{
66
+ totalCount
67
+ pageInfo {{ hasNextPage endCursor }}
68
+ nodes {{ {_REVIEW} }}
69
+ }}
70
+ {_CLOSER}
71
+ }}
72
+ ... on Issue {{
73
+ id
74
+ {_PLACE}
75
+ {_CLOSER}
76
+ }}
77
+ }}
78
+ }}
79
+ """
80
+
81
+ REVIEWS_QUERY = f"""
82
+ query($id: ID!, $cursor: String) {{
83
+ rateLimit {{ cost remaining }}
84
+ node(id: $id) {{
85
+ ... on PullRequest {{
86
+ reviews(first: 100, after: $cursor) {{
87
+ pageInfo {{ hasNextPage endCursor }}
88
+ nodes {{ {_REVIEW} }}
89
+ }}
90
+ }}
91
+ }}
92
+ }}
93
+ """
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class EnrichResult:
98
+ """What one enrichment run did.
99
+
100
+ ``items`` counts the items marked enriched, ``reviews`` the reviews
101
+ stored for them. ``failed`` holds the node ids that failed alone and
102
+ ``remaining`` those not reached when the budget ran out; both are
103
+ read again on the next run.
104
+ """
105
+
106
+ items: int
107
+ reviews: int
108
+ failed: tuple[str, ...] = ()
109
+ remaining: tuple[str, ...] = ()
110
+
111
+
112
+ def _actor(data: Any) -> tuple[str, str | None]:
113
+ """The login and ``__typename`` of an actor; ``ghost`` for a deleted one."""
114
+ if not isinstance(data, dict):
115
+ return GHOST, GHOST_TYPE
116
+ return data["login"], data.get("__typename")
117
+
118
+
119
+ def _closer(node: dict[str, Any]) -> tuple[str | None, str | None]:
120
+ """The actor of a node's last ``CLOSED_EVENT``; ``None`` when GitHub has none."""
121
+ events = (node.get("timelineItems") or {}).get("nodes") or []
122
+ if not events or not isinstance(events[-1], dict):
123
+ return None, None
124
+ return _actor(events[-1].get("actor"))
125
+
126
+
127
+ def _review(item: Item, data: dict[str, Any]) -> Review | None:
128
+ """The stored record of one review, or ``None`` for a pending one."""
129
+ if data.get("state") == "PENDING":
130
+ return None
131
+ reviewer, reviewer_type = _actor(data.get("author"))
132
+ submitted = data.get("submittedAt")
133
+ return Review(
134
+ id=int(data["fullDatabaseId"]),
135
+ node_id=data["id"],
136
+ repo=item.repo,
137
+ number=item.number,
138
+ reviewer=reviewer,
139
+ reviewer_type=reviewer_type,
140
+ state=data["state"],
141
+ submitted_at=None if submitted is None else datetime.fromisoformat(submitted),
142
+ )
143
+
144
+
145
+ def _owner(rows: list[Item], node: dict[str, Any] | None) -> Item | None:
146
+ """The row stored where GitHub places ``node``, or ``None`` when none is."""
147
+ if node is None:
148
+ return None
149
+ repo = (node.get("repository") or {}).get("nameWithOwner")
150
+ if not isinstance(repo, str):
151
+ return None
152
+ for row in rows:
153
+ if row.number == node.get("number") and row.repo.lower() == repo.lower():
154
+ return row
155
+ return None
156
+
157
+
158
+ def _enrichment(item: Item, node: dict[str, Any] | None) -> Enrichment:
159
+ """What ``node`` adds to ``item``; a missing node keeps what is stored."""
160
+ merged_by = merged_type = closed_by = closed_type = None
161
+ if node is None:
162
+ merged_by, merged_type = item.merged_by, item.merged_by_type
163
+ closed_by, closed_type = item.closed_by, item.closed_by_type
164
+ elif item.merged_at is not None:
165
+ merged_by, merged_type = _actor(node.get("mergedBy"))
166
+ closed_by, closed_type = merged_by, merged_type
167
+ elif item.closed_at is not None:
168
+ closed_by, closed_type = _closer(node)
169
+ return Enrichment(
170
+ repo=item.repo,
171
+ number=item.number,
172
+ merged_by=merged_by,
173
+ merged_by_type=merged_type,
174
+ closed_by=closed_by,
175
+ closed_by_type=closed_type,
176
+ read_at=item.updated_at,
177
+ )
178
+
179
+
180
+ async def _all_reviews(
181
+ transport: Transport, node_id: str, reviews: dict[str, Any]
182
+ ) -> list[dict[str, Any]]:
183
+ """Every review of one pull request, paging past the batch's first fifty."""
184
+ nodes = list(reviews.get("nodes") or [])
185
+ page = reviews.get("pageInfo") or {}
186
+ while page.get("hasNextPage"):
187
+ data = await graphql(
188
+ transport,
189
+ REVIEWS_QUERY,
190
+ {"id": node_id, "cursor": page.get("endCursor")},
191
+ cost_estimate=PAGE_COST,
192
+ )
193
+ more = (data.get("node") or {}).get("reviews")
194
+ if not isinstance(more, dict):
195
+ gone = {"type": "NOT_FOUND", "message": f"no review page for {node_id}"}
196
+ raise GraphQLError(gone["message"], errors=[gone])
197
+ nodes.extend(more.get("nodes") or [])
198
+ page = more.get("pageInfo") or {}
199
+ return nodes
200
+
201
+
202
+ async def _page(
203
+ transport: Transport,
204
+ aside: Iterable[_Aside],
205
+ save: Callable[[list[_Read]], None],
206
+ failed: list[str],
207
+ ) -> None:
208
+ """Page and store the pull requests put aside, fewest reviews first.
209
+
210
+ A pull request GitHub no longer finds goes in ``failed``. A spent
211
+ budget, or any other failure of a page, such as a ``502``/``504``,
212
+ a timeout or a transport error, logs the pull request it stopped at
213
+ and ends the paging: GitHub is failing, not the item.
214
+ """
215
+ for node_id, marks, owner, reviews in sorted(
216
+ aside, key=lambda a: a[3].get("totalCount") or 0
217
+ ):
218
+ try:
219
+ raw = await _all_reviews(transport, node_id, reviews)
220
+ except BudgetExhaustedError:
221
+ log.warning(
222
+ "GraphQL budget ran out paging the reviews of %s#%d;"
223
+ " it is read again next run",
224
+ owner.repo,
225
+ owner.number,
226
+ )
227
+ return
228
+ except GraphQLError as exc:
229
+ # A request-wide error stops the run, as it does batched().
230
+ if exc.request_wide or exc.status not in (None, *TIMEOUT_STATUSES):
231
+ raise
232
+ if not _not_found(exc, None):
233
+ _stop(owner, exc)
234
+ return
235
+ log.warning("could not page the reviews of %s: %s", node_id, exc)
236
+ failed.append(node_id)
237
+ continue
238
+ except TransportError as exc:
239
+ _stop(owner, exc)
240
+ return
241
+ save([(node_id, marks, owner, raw)])
242
+
243
+
244
+ def _stop(owner: Item, exc: Exception) -> None:
245
+ """Log the failure that ends the paging of the pull requests put aside."""
246
+ log.warning(
247
+ "stopped paging reviews at %s#%d: %s; it and those after it"
248
+ " are read again next run",
249
+ owner.repo,
250
+ owner.number,
251
+ exc,
252
+ )
253
+
254
+
255
+ def _not_found(exc: GraphQLError, path: list[Any] | None) -> bool:
256
+ """Whether every error in ``exc`` says the node queried does not exist.
257
+
258
+ With ``path``, every error must also name that path.
259
+ """
260
+ return bool(exc.errors) and all(
261
+ isinstance(error, dict)
262
+ and error.get("type") == "NOT_FOUND"
263
+ and (path is None or error.get("path") == path)
264
+ for error in exc.errors
265
+ )
266
+
267
+
268
+ async def _read(transport: Transport, ids: list[str]) -> list[Any]:
269
+ """The nodes of ``ids``, in order; ``[None]`` for one id GitHub cannot find.
270
+
271
+ GitHub answers an id it cannot find with a ``null`` node and a
272
+ ``NOT_FOUND`` error, which fails the whole batch; once halving has
273
+ left that id alone, it reads as a missing node.
274
+ """
275
+ estimate = BATCH_COST if len(ids) > 1 else PAGE_COST
276
+ try:
277
+ data = await graphql(
278
+ transport, ENRICH_QUERY, {"ids": ids}, cost_estimate=estimate
279
+ )
280
+ except GraphQLError as exc:
281
+ if len(ids) == 1 and _not_found(exc, ["nodes", 0]):
282
+ return [None]
283
+ raise
284
+ return list(data.get("nodes") or [None] * len(ids))
285
+
286
+
287
+ async def enrich_items(
288
+ transport: Transport, store: Store, repos: Iterable[str]
289
+ ) -> EnrichResult:
290
+ """Read reviews, mergers and closers of the items of ``repos`` needing them.
291
+
292
+ ``repos`` are the store's ``owner/name`` keys. Items never read, or
293
+ updated since ``reviews_read_at``, go fifty to a query, the most
294
+ recently updated first, so recent days complete first. A pull
295
+ request's reviews replace those stored, pending ones skipped. One
296
+ with more than fifty is put aside until every batch is read, then
297
+ paged and stored on its own, the fewest reviews first; one whose
298
+ review page does not come back fails and keeps its stored reviews.
299
+ Any other failure of a page, such as a ``502``/``504``, a timeout or
300
+ a transport error, ends the paging, leaving that pull request and
301
+ every one not yet paged in ``remaining``.
302
+ So a pull request with a long review history can delay only itself
303
+ and longer ones; it never holds back an item that fits in one page.
304
+ A merged pull request's closer is its merger; a closed item GitHub
305
+ names no closer for keeps ``closed_by`` null. A deleted account
306
+ reads as ``ghost``. ``reviews_read_at`` becomes the ``updated_at``
307
+ the item had when read.
308
+
309
+ Rows sharing one node id are read once. Only the row stored at the
310
+ repository and number GitHub reports for the node takes it and its
311
+ reviews; any other row, and the row of a node GitHub no longer
312
+ returns, is marked read with its stored fields kept, so it is not
313
+ retried every run and never takes another row's reviews.
314
+
315
+ Run it after the listing sync of ``repos``, never alongside it
316
+ (design §6.5): a listing page stored while a read is in flight can
317
+ lose its same-second invalidation of that item (design §6.3).
318
+
319
+ There is no ``budget`` argument: the budget is the one on
320
+ ``transport`` (design §6.5), charged the cost each query reports.
321
+ When fewer points are left than a batch may cost, one item is read
322
+ alone, at GitHub's minimum of one point. When the budget runs out,
323
+ enrichment stops cleanly with the ids it did not reach in
324
+ ``remaining``. A pull request whose review paging the budget cuts
325
+ off keeps its stored reviews, is logged and stays in ``remaining``
326
+ with every pull request put aside after it: one whose pages exceed
327
+ a whole run's budget is never completed. A budget smaller than the
328
+ first pages queued can complete no item, an accepted limit that a
329
+ warning naming ``budget.graphql_points`` reports. An id that fails
330
+ alone is logged and left in ``failed`` for the next run.
331
+ """
332
+ items = [
333
+ item
334
+ for repo in repos
335
+ for item in store.items_needing_enrichment(repo, PER_REPOSITORY)
336
+ ]
337
+ items.sort(key=lambda item: item.updated_at, reverse=True)
338
+ # A node can be stored under two keys: an issue transferred between
339
+ # repositories keeps its node id.
340
+ rows: dict[str, list[Item]] = {}
341
+ for item in items:
342
+ rows.setdefault(item.node_id, []).append(item)
343
+ done: set[str] = set()
344
+ aside: dict[str, _Aside] = {}
345
+ stored_items = stored_reviews = 0
346
+
347
+ def save(read: list[_Read]) -> None:
348
+ """Store items with their reviews in one transaction and count them."""
349
+ nonlocal stored_items, stored_reviews
350
+ enrichments = [e for _, marks, _, _ in read for e in marks]
351
+ reviews = {
352
+ (owner.repo, owner.number): [
353
+ review for data in raw if (review := _review(owner, data))
354
+ ]
355
+ for _, _, owner, raw in read
356
+ if owner is not None and raw is not None
357
+ }
358
+ store.store_enrichments(enrichments, reviews)
359
+ done.update(node_id for node_id, _, _, _ in read)
360
+ stored_items += len(enrichments)
361
+ stored_reviews += sum(len(r) for r in reviews.values())
362
+
363
+ async def fetch(ids: list[str]) -> None:
364
+ """Read one batch, store its items and put aside those to page."""
365
+ # A last point cannot cover a batch but reads one item; the rest
366
+ # of the chunk is then left for the next run.
367
+ budget = transport.budget
368
+ last = len(ids) > 1 and budget is not None and budget.graphql_left < BATCH_COST
369
+ if last:
370
+ ids = ids[:1]
371
+ nodes = await _read(transport, ids)
372
+ ready: list[_Read] = []
373
+ for node_id, node in zip(ids, nodes, strict=True):
374
+ if not isinstance(node, dict) or not node.get("__typename"):
375
+ node = None
376
+ owner = _owner(rows[node_id], node)
377
+ marks = [
378
+ _enrichment(row, None) for row in rows[node_id] if row is not owner
379
+ ]
380
+ if owner is None or node is None:
381
+ ready.append((node_id, marks, None, None))
382
+ continue
383
+ marks.insert(0, _enrichment(owner, node))
384
+ if node["__typename"] != "PullRequest":
385
+ ready.append((node_id, marks, owner, None))
386
+ continue
387
+ reviews = node.get("reviews") or {}
388
+ if (reviews.get("pageInfo") or {}).get("hasNextPage"):
389
+ aside[node_id] = (node_id, marks, owner, reviews)
390
+ else:
391
+ ready.append((node_id, marks, owner, list(reviews.get("nodes") or [])))
392
+ save(ready)
393
+ if last:
394
+ raise BudgetExhaustedError("one GraphQL point left; read one item")
395
+
396
+ def describe(ids: list[str]) -> str:
397
+ """Name a batch in the log."""
398
+ return f"{len(ids)} items from {ids[0]}"
399
+
400
+ out = await batched(list(rows), BATCH_SIZE, fetch, describe)
401
+ failed = list(out.failed)
402
+ await _page(transport, aside.values(), save, failed)
403
+ for node_id in failed:
404
+ item = rows[node_id][0]
405
+ log.warning("could not enrich %s#%d (%s)", item.repo, item.number, node_id)
406
+ remaining = tuple(
407
+ node_id
408
+ for node_id in dict.fromkeys([*aside, *out.remaining])
409
+ if node_id not in done and node_id not in failed
410
+ )
411
+ budget = transport.budget
412
+ if remaining and not stored_items and budget and budget.graphql_exhausted:
413
+ log.warning(
414
+ "the GraphQL budget was too small to complete any item;"
415
+ " %d wait for the next run: raise budget.graphql_points",
416
+ len(remaining),
417
+ )
418
+ return EnrichResult(
419
+ items=stored_items,
420
+ reviews=stored_reviews,
421
+ failed=tuple(failed),
422
+ remaining=remaining,
423
+ )