Skip to content

refactor(github): the github session owns transport, ledger, error classes and link pagination #983

Closed

Description

@dan-petty

Ready: implementation plan (refined 2026-10-17 at 3dd7fa6)

The plan is in this comment, because the body has no room for it. It supersedes any text below that conflicts with it.


Problem Statement

This item is Part B of #767, split out by the owner's decision (decisions Q2 and the #767 entry: "#767 keeps Part A in v0.2.26; Part B is a new item in v0.2.28 depending on #767"). #767 gives a process one GitHub identity: a session built from one gh auth token, GH_TOKEN pinned into every gh and git subprocess, a quota and cache directory per identity, GitHubClient built only from the session, and the token code, github.token, DEVOPS_CLI_GITHUB_TOKEN, the GraphQL client and GitHubGraphQLError removed. That is what #741, #752 and #753 need in v0.2.26, and it already touches 22 source files, 19 test files, README, three generated docs and seven knowledge-base pages. What remains is an independent transport rewrite whose tests and review stand on their own, and which together with Part A exceeds one reviewable pull request (CONTEXT.md: "Even a high-effort item fits in one pull request; anything bigger is split").

After #767 the session has one token but still no transport of its own, so GitHub is still reached four ways that do not share a ledger, an error vocabulary or a pagination rule (all evidence at HEAD 9c879ae, branch release/v0.2.25):

  • Two direct httpx2.Client() calls bypass the ledger. The PR diff (github/client.py:169-186, client at :178) and the SSH signing key (github/ssh.py:149-166, client at :151) send their own Authorization header and never report x-ratelimit-* to GitHubRateLimiter. The only reader of those headers is _process_header_metrics and _extract_header_ratelimit (github/rate_limiter.py:588-637), fed by _post_process_run (:1672-1689) through _parse_rate_limit_from_output (:637-643) from gh's stdout and stderr, so it sees headers only when a caller passes -i (tests/test_github_rate_limiter.py:369-387). Nothing reads x-ratelimit-resource.
  • Errors are classified by matching strings at five sites. Rate limits: is_rate_limit_error and is_secondary_rate_limit (rate_limiter.py:1164-1176, patterns CONST_GITHUB_RATE_LIMIT_PATTERNS and CONST_GITHUB_SECONDARY_RATE_LIMIT_PATTERNS at config/constants.py:340-357, which fix(security): network references come from url and ip syntax, not identifier-prefix and property-suffix lists #431 hands to this work, 431.md:95), check_github_rate_limit_error (github/projects.py:302-316, called at :327, :437, :769, :795 and by the roadmap store's _failure at roadmap/github_store.py:1016) and _handle_pr_ready_failure (commands/pr.py:958, "rate limit" in clean_err.lower()). Missing scopes: scope_error_patterns (projects.py:328-346) and "needs the" in combined and "scope" in combined (github/ssh.py:139). Unauthenticated: "not logged in" in err or "authentication required" in err (projects.py:347). Only GitHubRateLimitError (exceptions/git.py:96) and the base GitHubOperationError (:78) exist, so callers cannot tell a missing scope from a 404.
  • run_gh pages by building page=N URLs and returns partial results. _run_gh_paginated (rate_limiter.py:1627-1668) strips --paginate and --slurp (:1637), _extract_page_per_page (:1499-1506) assumes 100 items per page when the URL has no per_page, _build_paginated_url (:1509-1515) appends page=N, _execute_single_page (:1526-1562) runs each page with the caller's remaining arguments including --jq (page_args, :1539-1540), and _append_paginated_data (:1565-1577) unwraps only check_runs. Twelve call sites outside rate_limiter.py pass --paginate (roadmap/github_store.py:979, commands/pr.py:1295 and :1456, github/pr_monitor.py:326, :410 and :516, github/client.py:456, commands/gh.py:1289, github/projects.py:783, github/issues.py:138 and :393, github/check_verdict.py:263; commands/gh.py:1265 only declares the option); three also pass --slurp (pr.py:1296, pr_monitor.py:411, check_verdict.py:264). refactor(github): one github session per identity owning token, quota and transport #767 reproduced three defects offline by patching _execute_single_page:
    • pulls/{n}/reviews (_fetch_raw_reviews, pr_monitor.py:509-522) has no per_page; GitHub's default is 30, so a 30-item page 1 ended the loop and page 2 was never requested;
    • a wrapped workflow_runs list with total_count: 150 came back with page 1 only;
    • _query_timeline_copilot_state (pr_monitor.py:321-334) combines --paginate with --jq; two matching events on two pages returned [], because each page's filtered NDJSON is not one JSON document.
      run_gh_async (:1944) delegates to run_gh through asyncio.to_thread (:1966-1975), so it inherits all of this.
  • The ledger never refreshes on its own. get_quota (rate_limiter.py:1146-1162) only syncs from disk; _is_graphql_quota_exhausted (projects.py:1087-1095) treats an unknown or expired entry as exhausted, although _refresh_from_github (:903-913) could ask /rate_limit.
  • The roadmap store carries its own transport workarounds. refactor(github): roadmap store that reads and writes items, releases and board fields behind one interface #768's GitHub adapter (roadmap/github_store.py, 1030 lines, delivered on this branch in bf746de) injects a GhRunner (:91, default run_gh at :431), appends per_page=100 in _read_listing (:974-980) because of the first defect (its module docstring at :3-6 says why), pages issue events with its own page=N loop in changes_since (:531-551), and classifies failures through check_github_rate_limit_error (:1016). It has no conditional-request code, so every poll costs quota even when nothing changed.
  • devops gh api (commands/gh.py:1254-1300) passes --paginate, -q, -t and the user's extra arguments to run_gh (:1289-1297), and its help advertises gh's repos/:owner/:repo placeholders (:1257), which only gh resolves. Any pagination rewrite must keep the endpoint on gh.

GitHub's REST guidance is to follow the Link header rather than build page URLs, and documents conditional requests (a 304 does not count against the primary limit) for REST only; #752 checked with gh api graphql -i that GraphQL answers carry no ETag (752.md:102).

Proposed Solution

The session #767 creates becomes the one transport. Nothing below changes identity, the pin, or any removal #767 makes.

Adapters

  • httpx2, through the shared pool (get_shared_client, http/pool.py:61), serves three session methods: session.rest(method, path, **kwargs), session.graphql(query, variables) and session.paginate(path, **kwargs). Every request carries the session's Authorization: Bearer <token>, Accept: application/vnd.github+json and X-GitHub-Api-Version: 2022-11-28.
  • gh stays run_gh. Its 87 run_gh( call sites in 17 files keep their argv, the --paginate and --slurp ones included.

Shared by both adapters

  • One ledger. GitHubRateLimiter, already per identity after refactor(github): one github session per identity owning token, quota and transport #767. Every httpx2 response feeds it from x-ratelimit-* headers, routed by x-ratelimit-resource (core, graphql, search, ...), falling back to the path (/graphql is graphql). Every page run_gh fetches feeds it the same way (below). The header parser at rate_limiter.py:588-637 is reused, extended to read x-ratelimit-resource.
  • One retry policy. The rules run_gh already applies (_handle_retry_after_wait, rate_limiter.py:646; calculate_backoff_delay, :1178; DEFAULT_GH_MAX_RETRIES, config/defaults.py:724) pace httpx2 requests too.
  • One set of error classes, one classifier. GitHubRateLimitError (exceptions/git.py:96) stays the rate-limited class. Four new subclasses of GitHubOperationError (:78) in exceptions/git.py, exported from exceptions/__init__.py: GitHubScopeError (missing scope), GitHubNotFoundError, GitHubUnauthenticatedError and GitHubUnreadError (the answer could not be read: connection error, 5xx after retries, undecodable body). One classifier module in github/ maps HTTP responses, GraphQL error types and gh stderr to them. The ten existing except GitHubOperationError sites in src (commands/gh.py:257, commands/pr.py:570, :1479, :1577, :1739, :2125, github/client.py:77, github/pr_threads.py:301, github/issue_closure.py:379, github/branch_protection.py:442) keep working. The five string-matching sites and the unauthenticated match (rate_limiter.py:1164-1176, projects.py:302-316, :328-346, :347, commands/pr.py:958, github/ssh.py:139) call the classifier; CONST_GITHUB_RATE_LIMIT_PATTERNS and CONST_GITHUB_SECONDARY_RATE_LIMIT_PATTERNS move into it as its gh-stderr table and leave config/constants.py (and config/__init__.py).

Pagination

One Link parser and one flattening step, shared by both adapters: follow Link: rel="next" until there is none and return one flat list, for plain arrays and for wrapped lists (check_runs, workflow_runs, items, by the single list-valued key beside total_count).

  • session.paginate() pages over httpx2.
  • run_gh's --paginate path stays on the gh subprocess, so gh still resolves :owner/:repo placeholders and applies -H, -f, -X. Each page runs as gh api --include <url>, which prints the status line and headers before the body; the loop reads Link and x-ratelimit-* from them, feeds the ledger, and the retry rules pace each page. --slurp is honoured: with it, the pages are returned as one JSON array of page payloads, as gh does; without it, as one flat list. _extract_page_per_page, _build_paginated_url and _append_paginated_data go; DEFAULT_GH_MAX_PAGINATED_PAGES (defaults.py:732) stays as the page cap.
  • With --jq/-q or --template/-t, run_gh returns each page's filtered output concatenated, as gh's own --paginate does. _query_timeline_copilot_state keeps its argv; its parser already reads NDJSON (_parse_ndjson_dicts, pr_monitor.py:236).
  • The flat shape breaks no reader: _extract_page_runs (commands/pr.py:1277-1287, pr_monitor.py:394-402) and _extract_page_check_runs (check_verdict.py:220-228) already accept bare run objects, and parse_paginated_json (client.py:320) accepts one document.

Conditional requests

A REST GET on the httpx2 adapter sends If-None-Match with the ETag stored for that identity and URL. A 304 returns the stored body, marked as not modified, and leaves the ledger's remaining unchanged. The ETag store lives in the identity directory #767 creates, under the ledger's existing thread and file lock. Nothing is stored for GraphQL.

Moved onto the session

  • The roadmap store's GitHub adapter (roadmap/github_store.py): the GhRunner injection point (:91, :431) is replaced by the session; _read_listing (:974-980) and the per_page=100 workaround by session.paginate(); the changes_since page loop (:531-551) by session.paginate() with the same stop-at-cutoff rule (takewhile on created_at >= cutoff, stop at the first short or partially-old page); _failure (:1010-1018) by the classifier. Reads and writes that stay on gh (gh project item-list, item-edit and the other board commands) go through the session's gh adapter. Nothing is kept alongside. tests/test_roadmap_github_store.py's RecordedGh fake (:72, built by board_store at :116-117) becomes a MockTransport for REST and a scripted runner for board commands.
  • The PR diff (client.py:169-186): GitHubClient.get_pr_diff calls session.rest("GET", ..., headers={"Accept": "application/vnd.github.diff"}), keeping the same-host redirect rule (:180-184).
  • The signing key (ssh.py:149-166): _add_signing_key calls session.rest("POST", "/user/ssh_signing_keys", ...), keeping 422 as "already registered".
  • The quota check behind _is_graphql_quota_exhausted (projects.py:1087-1095): an unknown or expired entry is refreshed from /rate_limit (through session.rest, feeding the ledger as _extract_rate_limit_endpoint_response, rate_limiter.py:1481, does today) before the decision.

Scope

Key Questions

  • How does run_gh follow Link without changing transport? Answered. Each page runs as gh api --include, which prints the status line and headers before the body; the loop reads Link and x-ratelimit-* from them and strips them before returning. Handing --paginate to httpx2 would re-implement gh's placeholders and flags for devops gh api; handing it to gh's own --paginate would lose per-page pacing and the ledger feed.
  • What does --slurp mean on the new loop? Answered. What it means to gh: one JSON array whose elements are the page payloads. Without it, one flat list. _run_gh_paginated strips both flags today (rate_limiter.py:1637) and always returns a flat list, which the three --slurp callers tolerate only because their readers accept both shapes; honouring the flag removes that accident.
  • What happens to --jq with --paginate? Answered. run_gh concatenates each page's filtered output, as gh does. devops gh api --paginate -q keeps working, and _query_timeline_copilot_state keeps its argv.
  • Which error classes, and where? Answered. GitHubRateLimitError stays; GitHubScopeError, GitHubNotFoundError, GitHubUnauthenticatedError and GitHubUnreadError are new subclasses of GitHubOperationError in exceptions/git.py, and one classifier in github/ maps HTTP responses, GraphQL error types and gh stderr to them. The ten except GitHubOperationError sites keep working. fix(github): pr monitor reports copilot as idle or completed when its timeline or reviews read fails #806's unread state keeps taking its reason from gh stderr (806.md:21) and needs none of these.
  • Where do the rate-limit patterns go? Answered. Into the classifier's gh-stderr table, out of config/constants.py:340-357 and config/__init__.py. fix(security): network references come from url and ip syntax, not identifier-prefix and property-suffix lists #431 (v0.2.26) leaves them to this work (431.md:95) and lands first.
  • Where do conditional requests apply? Answered. To REST GETs on the httpx2 adapter only. GitHub documents them for REST, where a 304 does not count against the primary limit; GraphQL answers carry no ETag (752.md:102), and refactor(github): one github session per identity owning token, quota and transport #767 removes the GraphQL ETag cache.
  • How are httpx2 responses routed to a ledger entry? Answered. By x-ratelimit-resource, which GitHub sends on every API response, falling back to the path. run_gh keeps _detect_resource on argv.
  • Does the ledger refresh itself? Answered. Only where a decision depends on it: _is_graphql_quota_exhausted refreshes an unknown or expired entry from /rate_limit before deciding. get_quota stays a read.
  • Does the flat pagination shape break callers? Answered. No. The check-runs readers accept bare run objects (commands/pr.py:1277-1287, pr_monitor.py:394-402, check_verdict.py:220-228) and parse_paginated_json accepts one document; the existing tests of those readers must pass unchanged.
  • Does the store keep GhRunner? Answered. No. The session is the injection point: tests build a session over MockTransport and a scripted runner. tests/test_roadmap_store_contract.py (39 tests) runs against the in-memory adapter and only constructs the GitHub adapter at :61; it needs a constructor that accepts a session.
  • Does run_gh_async change? Answered. No. It delegates to run_gh through asyncio.to_thread (rate_limiter.py:1966-1975) and inherits the new loop.
  • Does MutationBudget go? Answered. No. It caps writes per project sync (projects.py:90) and is not GitHub's quota; GitHub's content-creation limits stay in the ledger's mutation pacing (_is_mutation_command, rate_limiter.py:498; DEFAULT_GH_MUTATION_MIN_INTERVAL_SECONDS, defaults.py:747).
  • Do feat(cli): service mode for devops serve with github webhooks, a polling tick and per-repo job queues #752's per-repo workers share one session? Answered. Yes: one process, one identity. The ledger's thread and file lock already serialize updates, and the ETag store uses the same lock.
  • Does devops gh api change? Answered. No. It still hands gh the endpoint unchanged, with --paginate, -q, -t and extra arguments (commands/gh.py:1289-1297); only the loop under run_gh changes.
  • Does this land before or after fix(github): pr monitor reports copilot as idle or completed when its timeline or reviews read fails #806? Answered. After. fix(github): pr monitor reports copilot as idle or completed when its timeline or reviews read fails #806 (v0.2.27) changes the failure handling of _query_timeline_copilot_state and _fetch_raw_reviews (806.md:22), the same reads whose pagination this item fixes; both keep the call-site argv, so this item rebases onto fix(github): pr monitor reports copilot as idle or completed when its timeline or reviews read fails #806 (806.md:64 asks for the same).

Acceptance Criteria

  • One ledger. An httpx2 response through session.rest() with x-ratelimit-resource: graphql and x-ratelimit-remaining: 42 sets the entry that run_gh reads (limiter.get_quota("graphql").remaining) to 42. A run_gh --paginate page whose --include headers carry x-ratelimit-remaining: 41 sets the core entry to 41. With the graphql entry unknown, _is_graphql_quota_exhausted makes one /rate_limit request over MockTransport and decides from its answer. Test: unit tests in tests/test_github_rate_limiter.py, next to test_run_gh_passively_updates_header_quota (:369).

  • Error classes. A table-driven unit test in a new tests/test_github_errors.py maps:

    • 429, and 403 with x-ratelimit-remaining: 0 or retry-after, to GitHubRateLimitError;
    • 403 where x-accepted-oauth-scopes names a scope missing from x-oauth-scopes, and GraphQL INSUFFICIENT_SCOPES, to GitHubScopeError;
    • 404 and GraphQL NOT_FOUND to GitHubNotFoundError;
    • 401, and gh stderr HTTP 401, Bad credentials, not logged in and authentication required, to GitHubUnauthenticatedError;
    • a connection error, a 5xx after the retry policy is exhausted, and an undecodable body to GitHubUnreadError;
    • every gh stderr string now matched at the five sites (rate_limiter.py:1164-1176, projects.py:302-316, :328-346, commands/pr.py:958, ssh.py:139) and at projects.py:347 to the same classes.

    Each site uses the classes: a unit test per site scripts gh stderr for a rate limit (and, at verify_project_auth_scopes and register_key_on_github, a missing scope) and asserts the class the site raises or reports, in the file that already covers the site: tests/test_github_rate_limiter.py (is_rate_limit_error), tests/test_github_projects.py (check_github_rate_limit_error, verify_project_auth_scopes), tests/test_pr_cmd.py (_handle_pr_ready_failure, untested today) and tests/test_github_ssh.py (register_key_on_github). A reviewer runs rg -n 'CONST_GITHUB_RATE_LIMIT_PATTERNS|CONST_GITHUB_SECONDARY_RATE_LIMIT_PATTERNS|check_github_rate_limit_error|scope_error_patterns|"needs the" in|"rate limit" in|"not logged in" in' src and every match is inside the classifier module.

  • Pagination over httpx2. Three MockTransport pages linked by Link: rel="next" return one flat list from session.paginate(). One link carries an after= cursor rather than page=, and one page is shorter than per_page. This holds for a plain array and for wrapped check_runs, workflow_runs and items pages. Test: a unit test.

  • Pagination over gh. The same pages, scripted as gh api --include output on a patched subprocess runner, return the same flat list through run_gh, and with --slurp one array of page payloads; the runner is called once per page with --include and without --paginate or --slurp. The three refactor(github): one github session per identity owning token, quota and transport #767 reproductions pass: a 30-item first page with no per_page fetches page 2, a 150-run workflow_runs list fetches every page, and a cursor link is followed. Test: unit tests replacing test_run_gh_paginated_edge_cases, test_build_paginated_url_and_extraction and test_run_gh_paginated_multipage_success in tests/test_github_rate_limiter.py and test_run_gh_paginated_handles_check_runs_dict in tests/test_pr_check_runs.py.

  • --jq with --paginate. Through run_gh, --paginate with --jq returns every page's filtered lines, and _query_timeline_copilot_state sees both matching events of a two-page timeline. Test: a unit test in tests/test_github_pr_monitor.py, next to test_fetch_raw_reviews_paginated (:831).

  • devops gh api is unchanged. devops gh api 'repos/:owner/:repo/issues' --paginate -q '.[].number' hands gh the endpoint unchanged and prints the concatenated filtered output. Test: a CLI test with a patched runner in tests/test_gh_cmd.py, next to test_gh_api_basic (:667) and test_gh_api_options_and_cache (:684).

  • Readers pass unchanged. uv run pytest tests/test_pr_check_runs.py tests/test_github_pr_monitor.py tests/test_pr_cmd.py -q passes with no edit to the readers' tests other than the four pagination-internals tests named above.

  • Conditional requests. The second GET of a URL through session.rest() sends If-None-Match with the stored ETag. A 304 returns the stored body marked as not modified and leaves the ledger's remaining unchanged. A's ETags are never sent as B: a second session over a different token sends no If-None-Match for the same URL. A GraphQL call stores no ETag. Test: a unit test over MockTransport with a temporary data dir.

  • Store on the session. tests/test_roadmap_github_store.py (56 tests) passes with the store's GitHub adapter running on the session, its REST reads over MockTransport and its board commands over a scripted runner; changes_since stops at the first event older than the cutoff without requesting a further page. rg -n "GhRunner|_read_listing|page=\{page\}|per_page=|check_github_rate_limit_error" src/devops_cli/roadmap/github_store.py prints nothing. tests/test_roadmap_store_contract.py (39 tests) passes. Test: those suites.

  • Diff and signing key on the session. rg -n "httpx2\.Client\(" src/devops_cli/github prints nothing. test_get_pr_diff_normal_and_redirect (tests/test_github_client.py:248) and test_add_signing_key (tests/test_github_ssh.py:189) run over the session's MockTransport, asserting Authorization: Bearer <session token> on the request and, for the diff, the same-host redirect rule. A diff response feeds the ledger's core entry. Test: those two tests, rewritten.

  • Removed helpers are gone. rg -n "_extract_page_per_page|_build_paginated_url|_append_paginated_data|CONST_GITHUB_RATE_LIMIT_PATTERNS|CONST_GITHUB_SECONDARY_RATE_LIMIT_PATTERNS" src tests prints nothing; the reviewer runs it.

  • Gate. uv run devops ci passes within its 5-minute budget. Each new test runs in under 1 s under pytest --durations=0. No new test opens a socket (prevent_external_network_calls, tests/conftest.py:99) or runs a real gh.

  • Fragment. changelog.d/<issue>.md exists and CHANGELOG.md and docs/ROADMAP.md are untouched. Command: devops pr check-readiness passes.

  • Pending a person (live GitHub, read-only), in a terminal logged in to gh:

    • uv run devops gh api 'repos/dan-petty/devops-cli/issues?state=closed' --paginate -q '.[].number' | wc -l prints more than 100 (gh api takes no -R; the endpoint has no per_page, so today's loop stops at GitHub's default page of 30).
    • uv run devops pr monitor <a PR with a Copilot review on its second timeline page> reports the Copilot state, not idle.
    • uv run devops gh rate-limit --format json before and after each of two uv run devops roadmap render --repo dan-petty/devops-cli --dry-run runs: the second run raises core used by fewer requests than the first, the difference being the listings that answered 304.

Out of Scope

Dependencies

Scope added 2026-10-02: the architecture review of 2026-10-02 measured github/rate_limiter.py (1,980 lines; 10 public and 62 private top-level definitions at 38517a8). It reported six public symbols with no production caller. Five of them are used inside the module or are the test reset hook: calculate_request_delay (defined at :412, called at :969), resolve_quota_cache_path, QuotaState, GitHubRateLimiter and reset_github_rate_limiter. One has no caller at all: run_gh_async (:1944). rg -n run_gh_async src tests finds only its definition, and no open issue other than this one names it. This item's answer to "Does run_gh_async change?" was "No", so as written it keeps dead code. The review's other points on this module are covered elsewhere. The session is the injection point that replaces GhRunner, as this item already answers. The three page extractors (_extract_page_runs twice, _extract_page_check_runs) are #998's. GhCliClient stays out of scope, as this item says; it is still used by commands/gh.py:254 and github/metrics.py:229, :298 and :325.

  • run_gh_async is deleted. rg -n "run_gh_async" src tests finds nothing.

Library-first scope: redirects through httpx2, session requests stay on the API origin (2026-10-03)

Scope added 2026-10-03, under the library rule that #1107 enforces: hand-written URL, host and address checks give way to standard-library or locked-dependency calls. Lines cited at dcafadf. httpx2 lines are from the locked httpx2 2.13.0.

Under "Moved onto the session", "The PR diff" keeps "the same-host redirect rule (:180-184)", and the "Diff and signing key on the session" criterion asserts that rule. The rule is a hand-written redirect follower. get_pr_diff (github/client.py:169-186) opens its own client with follow_redirects=False (:178) and parses the Location header with urllib.parse.urlparse (:182). It then compares parsed.scheme == "https" and parsed.netloc in ("api.github.com", "github.com") (:183) and re-sends the same headers by hand, Authorization included (:184). An offline test with httpx2.MockTransport measured what the string rule gets wrong:

  • It does not follow a relative Location: /repositories/1/pulls/42, https://API.GITHUB.COM:443/..., or a second redirect hop. In each case raise_for_status() then raises on the 3xx.
  • It copies the token by hand onto a hop to github.com.

httpx2 already does this job. With follow_redirects=True, which is the shared pool's default (http/pool.py:95), it:

  • resolves both relative and absolute Location values;
  • runs the client's request hooks before the first request and before every hop (_send_handling_redirects, httpx2/_client.py:1040-1041), and an exception a hook raises propagates out of send() unchanged;
  • drops Authorization whenever a hop changes origin (_redirect_headers, httpx2/_client.py:530-534). The only exception is an http-to-https upgrade on the same host (:71).

The same test showed Authorization kept on an api.github.com to api.github.com hop and dropped on a hop to another host. httpx2.URL.origin returns an httpx2.Origin (scheme, lower-cased host, effective port), so one equality test replaces the host tuple, the scheme test and the urlparse call.

The check belongs on the session rather than in get_pr_diff. Every request that session.rest(), session.graphql() and session.paginate() send carries the token. session.paginate() also follows Link: rel="next" URLs taken from the response, so the same hook stops a Link that names another origin from receiving the token.

This scope supersedes two phrases above:

  • In "Moved onto the session", "keeping the same-host redirect rule (:180-184)" becomes "following redirects through httpx2 under the session's origin hook".
  • In the "Diff and signing key on the session" criterion, "the same-host redirect rule" becomes the redirect cases below.

Issue #898 (v0.2.29, rewritten to route every client through one connect-time factory) checks the dialled address when a connection opens. That check decides which addresses may be dialled, not which origin may receive the GitHub token, so this hook stays with the session's client whichever of the two lands first.

  • No hand-written redirect handling. get_pr_diff makes one session.rest("GET", ..., headers={"Accept": "application/vnd.github.diff"}) call and lets httpx2 follow redirects. rg -n 'is_redirect|netloc|urlparse|urllib|Authorization' src/devops_cli/github/client.py prints nothing.
  • One origin check, done by the library. The session's pooled client has its own key in get_shared_client (http/pool.py:61), so no other pool caller shares its hook, and keeps the pool's follow_redirects=True (:95). It carries one request hook (event_hooks={"request": [...]}). The hook compares request.url.origin with httpx2.URL(CONST_URL_GITHUB_API_BASE).origin (config/constants.py:537) and refuses any other origin. The hook contains no host tuple, netloc comparison, startswith or scheme-string test.
  • Redirect cases. test_get_pr_diff_normal_and_redirect (tests/test_github_client.py:248-288) today patches httpx2.Client.get with a fake response object. It becomes a table test over the session's httpx2.MockTransport, starting at https://api.github.com/repos/octo/repo/pulls/42:
    • These hops are followed, the diff is returned, and every hop carries Authorization: Bearer <session token> and Accept: application/vnd.github.diff:

      • a 301 to https://api.github.com/repositories/1/pulls/42 (the moved-repository case);
      • a relative Location: /repositories/1/pulls/42;
      • https://API.GITHUB.COM:443/repositories/1/pulls/42;
      • a 301 followed by a 307, both on api.github.com.

      The last three fail today with an HTTPStatusError on the 3xx (measured).

    • These hops are refused before they are sent, so the transport records exactly one request:

      • https://example.com/x;
      • https://api.github.com@example.com/x, where the userinfo names GitHub;
      • https://api.github.com.example.com/x, a look-alike host that begins with GitHub's API host name. This case is a deliberate exception to the AGENTS.md rule that mock hosts are bare example.com with no subdomain, because only a subdomain can express the look-alike; a comment on the case says so;
      • http://api.github.com/repositories/1/pulls/42, a scheme downgrade;
      • https://github.com/octo/repo/pull/42.diff.
    • The hook itself raises GitHubUnreadError, with a message naming the refused origin. An origin refusal counts as unread (the answer was never fetched), and the retry policy never retries it: when the call raises, the transport has still recorded exactly one request.

  • Link pages stay on the origin. Over MockTransport, a session.paginate() page whose Link: rel="next" names https://example.com/repos/octo/repo/issues?page=2 raises the same refusal. The transport never sees a request to example.com, so the token is never sent there.
  • Construct scan. Once feat(ci): hand-rolled URL and address parsing fails devops ci, AGENTS.md makes the library the rule, and reviews stop discarding the findings #1107 has landed, its construct scan (the constructs row of refactor(ci): github ci runs the gate through devops ci from one check table #843's check table, which runs uv run ast-grep scan --error=unused-suppression --error=no-suppress-all src) reports no hit in github/client.py or the session module, and neither file carries an ast-grep-ignore marker. feat(ci): hand-rolled URL and address parsing fails devops ci, AGENTS.md makes the library the rule, and reviews stop discarding the findings #1107's rules do not match today's host tuple (no hit in github/client.py at dcafadf), so this scope does not change feat(ci): hand-rolled URL and address parsing fails devops ci, AGENTS.md makes the library the rule, and reviews stop discarding the findings #1107's marker ceiling; the rg criterion above is its guard.

Key question for this scope:

  • Does the hook still allow github.com? Proposed: no. Only the API origin (CONST_URL_GITHUB_API_BASE) receives session requests. Today's rule lets a hop to github.com through and copies the token onto it by hand. Under httpx2 that hop would go out without Authorization, because the origin differs, so it would be an unauthenticated fetch from a host the session does not otherwise use. The moved-repository redirect stays on api.github.com and remains covered. Apart from this redirect rule, no code path in src sends the GitHub token to another GitHub host, so nothing that works now breaks.

Consolidated from #1034: both new pagination loops fail closed (2026-10-03)

#1034 (v0.2.29) fixes _fetch_all_pages and _append_paginated_data, which this item (v0.2.28) deletes, and this item's new loops do not state the fail-closed rule. The rule applies to both loops that replace them: run_gh over gh api --include, and session.paginate().

Acceptance criteria (added, from #1034).

  • An empty, HTML, truncated or error-object page, on page 1 or any later page, is a failed read that raises and names the endpoint and the page. It never ends the listing early.
  • A literal [] or a short page ends the listing.
  • extract_json_payload never salvages a page.
  • A readiness test with a malformed second check-runs page reports the read failure, not a short list.

Key question (added). Does #1034 still land separately? (proposed) No. Once this amendment is posted, #1034 closes as merged into this item, because the functions it fixes are deleted here a release earlier. The alternative is to move #1034 ahead of this item and keep these criteria. Neither has an owner placement, so a person decides.

Related (added). #891 depends on this item (not on #767). #1125's request classifier is reused by this item's session adapter. #1118 removes the ratelimit package from the same module.

The quota refresh is a classifier site too (2026-10-04)

Owner decision on #767's bad-token check: #767 ships reporting GitHub's 401 as it does today, and this item turns it into the unauthenticated error.

  • The class already exists. refactor(github): one github session per identity owning token, quota and transport #767 adds GitHubUnauthenticatedError (GITHUB_UNAUTHENTICATED, exceptions/git.py), raised when gh auth token finds no token. This item reuses that class instead of adding a new one, and the classifier raises it.

  • A sixth site: GitHubRateLimiter._refresh_from_github (github/rate_limiter.py, about :903-929 after refactor(github): one github session per identity owning token, quota and transport #767). It raises GitHubRateLimitError for every failed gh api rate_limit. The refresh is the first GitHub call of a devops gh command, so with GH_TOKEN=not-a-real-token the command exits with Failed to refresh rate limits from GitHub API: HTTP 401: Bad credentials: a bad token reported as a rate-limit failure. Nothing catches that class to wait or retry, so the cost is only the wrong error. The refresh passes its gh failure to the classifier:

    • a 401 raises GitHubUnauthenticatedError;
    • a rate limit stays GitHubRateLimitError;
    • anything else raises GitHubUnreadError.

    The same applies to the broken-state error that _get_quota_locked raises when a refresh fails.

  • Acceptance, added to Error classes:

    • a unit test in tests/test_github_rate_limiter.py scripts gh api rate_limit failing with HTTP 401: Bad credentials and asserts that _refresh_from_github raises GitHubUnauthenticatedError;
    • tests/test_gh_cmd.py asserts that devops gh issues list, with that runner, prints the unauthenticated error and exits 1 without a traceback.
  • Pending a person, added to the list above: GH_TOKEN=not-a-real-token uv run devops gh issues list -R dan-petty/devops-cli exits 1 with the unauthenticated error and prints no issues. This replaces refactor(github): one github session per identity owning token, quota and transport #767's amended bad-token check.

Test design: the GitHub session fake (2026-10-07)

The owner decided on 2026-10-07, in the test design #1307, that tests double only process edges, each through one seam, and that every fake ships with a contract suite. This item's session is the seam for the GitHub edge. The session over MockTransport and a scripted gh runner that this item's tests build becomes that edge's shared fake.

PyGithub stays outside that fake until #891 moves the pull request, repository and SSH-key calls onto the session. GitHubClient still wraps Github(), which talks to GitHub over requests [code: github/client.py:39-46 at 5c45b1e], and this item's Out of Scope leaves PyGithub to #891. The package migrations whose tests reach GitHubClient (#1321, #1324, #1326, #1328, #1331 and #1332) therefore wait for #891 as well as for this item.

Acceptance criteria (added).

Strategic alignment (added).

Update 2026-10-08: owner decision on the session transport

The key question from the 2026-10-08 client-library audit is answered: gidgethub backs session.rest/graphql/paginate, over the shared egress-checked httpx2 pool. This replaces the hand-written Link parser, error classifier, ETag store and retry loop this item specified. Record it as an ADR before the code.

How the item changes:

Update 2026-10-08: refinement

Proposed design

Problem statement

After #767 establishes a single GitHub identity per process (one token, one quota directory, one session), the codebase still reaches GitHub through four separate paths that do not share a rate-limit ledger, an error vocabulary, or a pagination rule. Two direct httpx2 calls bypass the ledger; errors are classified by string-matching at five sites; pagination builds page=N URLs and has three known defects (30-item default page, wrapped lists, --jq with --paginate); and the roadmap store carries its own transport workarounds. This item makes the session the single transport: it adds rest, graphql, and paginate methods backed by gidgethub over the shared httpx2 pool, introduces a unified error classifier replacing the five string-matching sites, replaces page-URL pagination with Link-header following, adds conditional requests for REST GETs, moves the PR diff and SSH signing key onto the session, rewrites the roadmap store's GitHub adapter to use the session, and deletes the dead run_gh_async function.

Acceptance criteria

  • Criterion 1: One ledger: an httpx2 response through session.rest() with x-ratelimit-resource and x-ratelimit-remaining headers sets the same ledger entry that run_gh reads; a run_gh --paginate page whose --include headers carry x-ratelimit-remaining sets the core entry; _is_graphql_quota_exhausted refreshes an unknown entry from /rate_limit before deciding.
    Verification: Unit tests in tests/test_github_rate_limiter.py next to test_run_gh_passively_updates_header_quota pass; the test scripts a MockTransport response with x-ratelimit-resource: graphql and x-ratelimit-remaining: 42, then asserts limiter.get_quota('graphql').remaining == 42.
  • Criterion 2: Error classes: a table-driven test in tests/test_github_errors.py maps 429/403-with-remaining-0 to GitHubRateLimitError, 403-with-missing-scope and GraphQL INSUFFICIENT_SCOPES to GitHubScopeError, 404 and GraphQL NOT_FOUND to GitHubNotFoundError, 401 and gh stderr strings to GitHubUnauthenticatedError, and connection errors/5xx/undecodable bodies to GitHubUnreadError; every gh stderr string previously matched at the five string-matching sites maps to the same classes.
    Verification: rg -n 'CONST_GITHUB_RATE_LIMIT_PATTERNS|CONST_GITHUB_SECONDARY_RATE_LIMIT_PATTERNS|check_github_rate_limit_error|scope_error_patterns|"needs the" in|"rate limit" in|"not logged in" in' src prints only matches inside the classifier module; tests/test_github_errors.py passes.
  • Criterion 3: Pagination over httpx2: three MockTransport pages linked by Link: rel="next" return one flat list from session.paginate(), including a cursor-based after= link and a short final page, for plain arrays and wrapped check_runs/workflow_runs/items pages.
    Verification: A unit test in tests/test_github_rate_limiter.py scripts three linked pages over MockTransport and asserts the returned list is flat and complete.
  • Criterion 4: Pagination over gh: the same pages scripted as gh api --include output on a patched subprocess runner return the same flat list through run_gh; with --slurp, one array of page payloads; the runner is called once per page with --include and without --paginate or --slurp; the three refactor(github): one github session per identity owning token, quota and transport #767 reproductions (30-item first page, 150-run workflow_runs, cursor link) pass.
    Verification: Unit tests replacing test_run_gh_paginated_edge_cases, test_build_paginated_url_and_extraction, test_run_gh_paginated_multipage_success in tests/test_github_rate_limiter.py and test_run_gh_paginated_handles_check_runs_dict in tests/test_pr_check_runs.py pass.
  • Criterion 5: --jq with --paginate: through run_gh, --paginate with --jq returns every page's filtered lines concatenated; _query_timeline_copilot_state sees both matching events of a two-page timeline.
    Verification: A unit test in tests/test_github_pr_monitor.py next to test_fetch_raw_reviews_paginated passes, asserting both events are found.
  • Criterion 6: devops gh api is unchanged: devops gh api 'repos/:owner/:repo/issues' --paginate -q '.[].number' hands gh the endpoint unchanged and prints the concatenated filtered output.
    Verification: A CLI test with a patched runner in tests/test_gh_cmd.py next to test_gh_api_basic and test_gh_api_options_and_cache passes.
  • Criterion 7: Readers pass unchanged: the check-runs readers and PR monitor tests pass with no edit other than the four pagination-internals tests.
    Verification: uv run pytest tests/test_pr_check_runs.py tests/test_github_pr_monitor.py tests/test_pr_cmd.py -q passes.
  • Criterion 8: Conditional requests: the second GET of a URL through session.rest() sends If-None-Match with the stored ETag; a 304 returns the stored body marked as not modified and leaves the ledger's remaining unchanged; a second session over a different token sends no If-None-Match for the same URL; a GraphQL call stores no ETag.
    Verification: A unit test over MockTransport with a temporary data dir passes, asserting the If-None-Match header, the 304 response, and the unchanged remaining count.
  • Criterion 9: Store on the session: tests/test_roadmap_github_store.py (56 tests) passes with the store's GitHub adapter running on the session, its REST reads over MockTransport and its board commands over a scripted runner; changes_since stops at the first event older than the cutoff without requesting a further page; tests/test_roadmap_store_contract.py (39 tests) passes.
    Verification: rg -n "GhRunner|_read_listing|page={page}|per_page=|check_github_rate_limit_error" src/devops_cli/roadmap/github_store.py prints nothing; both test suites pass.
  • Criterion 10: Diff and signing key on the session: no httpx2.Client( calls remain in src/devops_cli/github; test_get_pr_diff_normal_and_redirect and test_add_signing_key run over the session's MockTransport, asserting Authorization: Bearer and the same-host redirect rule.
    Verification: rg -n "httpx2.Client(" src/devops_cli/github prints nothing; both tests pass.
  • Criterion 11: Removed helpers are gone: _extract_page_per_page, _build_paginated_url, _append_paginated_data, CONST_GITHUB_RATE_LIMIT_PATTERNS, and CONST_GITHUB_SECONDARY_RATE_LIMIT_PATTERNS are deleted from src and tests.
    Verification: rg -n "_extract_page_per_page|_build_paginated_url|_append_paginated_data|CONST_GITHUB_RATE_LIMIT_PATTERNS|CONST_GITHUB_SECONDARY_RATE_LIMIT_PATTERNS" src tests prints nothing.
  • Criterion 12: run_gh_async is deleted: no reference remains in src or tests.
    Verification: rg -n "run_gh_async" src tests finds nothing.
  • Criterion 13: No hand-written redirect handling: get_pr_diff makes one session.rest call and lets httpx2 follow redirects; no is_redirect, netloc, urlparse, urllib, or manual Authorization copy remains in github/client.py.
    Verification: rg -n 'is_redirect|netloc|urlparse|urllib|Authorization' src/devops_cli/github/client.py prints nothing.
  • Criterion 14: One origin check, done by the library: the session's pooled client carries one request hook comparing request.url.origin with CONST_URL_GITHUB_API_BASE origin; the hook contains no host tuple, netloc comparison, startswith, or scheme-string test; it raises GitHubUnreadError naming the refused origin.
    Verification: A table test over MockTransport starting at api.github.com follows 301/relative/uppercase/double-hop redirects with Authorization on every hop, and refuses example.com, userinfo, look-alike subdomain, http downgrade, and github.com hops before sending, recording exactly one request in the transport.
  • Criterion 15: Link pages stay on the origin: a session.paginate() page whose Link: rel="next" names a different origin raises the same refusal; the transport never sees a request to the other origin.
    Verification: A MockTransport test scripts a Link header pointing to example.com and asserts GitHubUnreadError is raised and the transport recorded no request to example.com.
  • Criterion 16: Fail-closed pagination: an empty, HTML, truncated, or error-object page on page 1 or any later page raises and names the endpoint and page; a literal [] or a short page ends the listing; extract_json_payload never salvages a page.
    Verification: A readiness test with a malformed second check-runs page reports the read failure, not a short list; the existing fail-closed tests in tests/test_roadmap_github_store.py pass.
  • Criterion 17: Ships the edge's fake under tests/support/fakes/ and its contract suite, per the ADR that tests double only process edges through seams.
    Verification: tests/support/fakes/ contains the GitHub session fake and its contract suite; the contract suite passes against both the fake and a recorded-response real side.
  • Criterion 18: Gate: CI passes within its 5-minute budget; each new test runs in under 1 s; no new test opens a socket or runs a real gh.
    Verification: uv run devops ci passes; pytest --durations=0 shows no test over 1 s; prevent_external_network_calls and isolate_gh_config guards are active.
  • Criterion 19: Fragment: changelog.d/.md exists and CHANGELOG.md and docs/ROADMAP.md are untouched.
    Verification: devops pr check-readiness passes.

Key questions

  • How does run_gh follow Link without changing transport?: Each page runs as gh api --include, which prints the status line and headers before the body; the loop reads Link and x-ratelimit-* from them and strips them before returning. Handing --paginate to httpx2 would re-implement gh's placeholders and flags; handing it to gh's own --paginate would lose per-page pacing and the ledger feed. (proposed)
  • What does --slurp mean on the new loop?: What it means to gh: one JSON array whose elements are the page payloads. Without it, one flat list. _run_gh_paginated strips both flags today and always returns a flat list; honouring the flag removes the accident that the three --slurp callers tolerate. (proposed)
  • What happens to --jq with --paginate?: run_gh concatenates each page's filtered output, as gh does. devops gh api --paginate -q keeps working, and _query_timeline_copilot_state keeps its argv. (proposed)
  • Which error classes, and where?: GitHubRateLimitError stays; GitHubScopeError, GitHubNotFoundError, GitHubUnauthenticatedError, and GitHubUnreadError are new subclasses of GitHubOperationError in exceptions/git.py. One classifier in github/ maps HTTP responses, GraphQL error types, and gh stderr to them. The ten existing except GitHubOperationError sites keep working. fix(github): pr monitor reports copilot as idle or completed when its timeline or reviews read fails #806's unread state keeps taking its reason from gh stderr. (proposed)
  • Where do the rate-limit patterns go?: Into the classifier's gh-stderr table, out of config/constants.py:340-357 and config/init.py. fix(security): network references come from url and ip syntax, not identifier-prefix and property-suffix lists #431 (v0.2.26) leaves them to this work and lands first. (proposed)
  • Where do conditional requests apply?: To REST GETs on the httpx2 adapter only. GitHub documents them for REST, where a 304 does not count against the primary limit; GraphQL answers carry no ETag, and refactor(github): one github session per identity owning token, quota and transport #767 removes the GraphQL ETag cache. (proposed) [sources: docs/adr/0003-polling-is-how-the-roadmap-sees-changes.md]
  • How are httpx2 responses routed to a ledger entry?: By x-ratelimit-resource, which GitHub sends on every API response, falling back to the path. run_gh keeps _detect_resource on argv. (proposed)
  • Does the ledger refresh itself?: Only where a decision depends on it: _is_graphql_quota_exhausted refreshes an unknown or expired entry from /rate_limit before deciding. get_quota stays a read. (proposed)
  • Does the store keep GhRunner?: No. The session is the injection point: tests build a session over MockTransport and a scripted runner. tests/test_roadmap_store_contract.py runs against the in-memory adapter and only constructs the GitHub adapter at :61; it needs a constructor that accepts a session. (proposed)
  • Does run_gh_async change?: It is deleted. rg -n run_gh_async src tests finds only its definition at rate_limiter.py:1944, and no open issue other than this one names it. The architecture review of 2026-10-02 confirmed it has no production caller. (proposed)
  • Does MutationBudget go?: No. It caps writes per project sync (projects.py:90) and is not GitHub's quota; GitHub's content-creation limits stay in the ledger's mutation pacing. (proposed)
  • Do feat(cli): service mode for devops serve with github webhooks, a polling tick and per-repo job queues #752's per-repo workers share one session?: Yes: one process, one identity. The ledger's thread and file lock already serialize updates, and the ETag store uses the same lock. (proposed)
  • Does devops gh api change?: No. It still hands gh the endpoint unchanged, with --paginate, -q, -t, and extra arguments; only the loop under run_gh changes. (proposed)
  • Does this land before or after fix(github): pr monitor reports copilot as idle or completed when its timeline or reviews read fails #806?: After. fix(github): pr monitor reports copilot as idle or completed when its timeline or reviews read fails #806 (v0.2.27) changes the failure handling of _query_timeline_copilot_state and _fetch_raw_reviews, the same reads whose pagination this item fixes; both keep the call-site argv, so this item rebases onto fix(github): pr monitor reports copilot as idle or completed when its timeline or reviews read fails #806. (proposed)
  • Does the hook still allow github.com?: No. Only the API origin (CONST_URL_GITHUB_API_BASE) receives session requests. Today's rule lets a hop to github.com through and copies the token onto it by hand; under httpx2 that hop would go out without Authorization because the origin differs. The moved-repository redirect stays on api.github.com and remains covered. (proposed)
  • Does fix(github): a paginated gh api read fails closed on a page that is not the expected json, instead of returning a short listing #1034 still land separately?: No. Once this amendment is posted, fix(github): a paginated gh api read fails closed on a page that is not the expected json, instead of returning a short listing #1034 closes as merged into this item, because the functions it fixes (_fetch_all_pages and _append_paginated_data) are deleted here a release earlier. The fail-closed criteria stay for the loops' replacement. (proposed)

Open questions

  • Does the flat pagination shape break callers? (missing verified source)

Fit

Fits in one pull request.

Suspected block

None.

Dependencies

#767, #806, #431, #974, #981, #1312

Activity

  1. added this to the v0.2.28 milestone on Oct 2, 2026
  2. added
    type/refactor
    scope/github
    priority/p1-high
    on Oct 2, 2026
  3. removed this from the v0.2.28 milestone on Oct 6, 2026
  4. dan-petty-bot commented on Oct 6, 2026

    @dan-petty-bot
    Collaborator

    Moved to the backlog: it was New, not Ready, when v0.2.28 started. (devops roadmap reprioritize)

  5. 18 remaining items

  6. added
    priority/p0-critical
    and removed
    priority/p1-high
    on Oct 18, 2026
  7. dan-petty commented on Oct 18, 2026

    @dan-petty
    OwnerAuthor

    Amendment (2026-10-18), from PR 3's review: items for later PRs

    An adversarial review of PR 3 (four lenses, skeptics on every finding) left these outside PR 3's scope:

    • PR 5 or PR 7: the session's _add_signing_key treats every 422 as already registered (src/devops_cli/github/ssh.py; a PR 1 decision). GitHub also answers 422 for "key is invalid". PR 3 fixes the gh path by confirming a 422 against the key listing. The session path should do the same through session.paginate("/user/ssh_signing_keys"), so the two paths agree. The 2026-10-08 audit comment above flagged this too.
    • PR 5: decide an unrecovered owner-lookup failure by the GraphQL quota, not by gh's phrase. gh's OwnerIDAndType (gh 2.102.0 queries.go:1240-1281) reports every failed owner lookup except not-found as "unknown owner type", dropping the cause: a 401, a 5xx, a SAML refusal or a rate limit. PR 3 keeps it a rate limit where there is no @me fallback (the store's item-add, item-create and project create with --owner <login>, and _read_failure). So a 401 or a 5xx there still reads "wait for the quota". The /rate_limit GraphQL quota, which costs no quota to read, can tell them apart. The read belongs in the callers, because error_classifier cannot import rate_limiter.
    • PR 7: prune the project-scope rows gh never writes. These rows came from the old projects.py tuples by plan decision: "scope 'project'", 'scope "project"', "requires additional permissions", "requires the 'project' scope", "need the 'project' scope", "project scope" and "authentication required". None appears in gh's or go-gh's non-test output. gh's exit-codes help says "requires authentication". PR 3's switch to classifying stderr only removes most of their exposure to user text.
  8. dan-petty commented on Oct 18, 2026

    @dan-petty
    OwnerAuthor

    Note (2026-10-18): inline "exit code N" fallbacks

    #1345 PR 1's review found the user-facing fallback f"exit code {returncode}" written in English outside the lang catalogue at five more sites: commands/pr.py:1384, commands/k8s/security_audit.py:50, and github/check_verdict.py:343, :464 and :472 (at 7607f0f). PR 1 of #1345 moves its own instance into lang/en. Where a later #983 PR routes these sites' gh failures through the classifier, the message should come from the catalogue too. Whatever is left is one small chore.

  9. dan-petty commented on Oct 20, 2026

    @dan-petty
    OwnerAuthor

    What changed

    #1716, merged into release/v0.2.37 as bf9481e.

    The last of #983's pull requests. The GitHub session's fake moves under tests/support/fakes/, and a contract suite holds it to GitHub's recorded answers. This closes #983.

    The move.

    The contract suite: tests/test_github_contract.py. Ten cases run through the real session twice:

    • over GitHubApiFake, routed as a test over the fake routes it;
    • over RecordedGitHubApi, which replays GitHub's own answers to the same requests in order through httpx2.MockTransport, offline. It fails on an unrecorded request or an unused recording.

    The cases:

    • a REST read;
    • a read answered from its ETag after a 404;
    • a 404;
    • a listing over GitHub's linked pages;
    • a reader that stops early;
    • a listing read again from its first page's ETag;
    • a refused token;
    • a 422;
    • a write answered with text;
    • a write refused with a 400.

    Each compares answers, errors, requests and the ledger against values written in the case. Every case fails under at least one mutant of the fake or the sessio…

    34 file(s) changed.

    How it was verified

    Check runs at 2838468:

    • Prune PR DevContainer Images: pass
    • Audit Defect PR Hardening: skipping
    • zizmor: pass
    • devops-cli: pass
    • bandit: pass
    • CodeQL: pass
    • Rule Pack Tests: pass
    • Fail-to-Pass Self-Check: pass
    • Changed-Test Independence: pass
    • Tests & Coverage: pass
    • Analyze (python): pass
    • Fail-to-Pass Check: pass
    • Analyze (actions): pass
    • Static Analysis: pass
    • DevContainer Image: skipping
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-983-github-session-transport.md:

    • rg -n "httpx2\.(Async)?Client\(" src/devops_cli/github and rg -n 'is_redirect|netloc|urlparse|urllib|Authorization' src/devops_cli/github/client.py print nothing.
    • Every request the session sends carries the session's token, X-GitHub-Api-Version and the constant User-Agent, and is paced and charged to the resource GitHub names: test_a_get_carries_the_token_the_api_version_and_the_user_agent, test_a_response_charges_its_quota_to_the_resource_github_names (core at 42, a response naming no resource, one naming another) and test_a_post_is_paced_as_a_mutation_a_get_as_a_read_and_the_quota_read_not_at_all in tests/test_github_session.py, over httpx2.MockTransport.
    • A session paces and charges its own identity's ledger: two sessions with different tokens leave 11 and 22 on their own ledgers and the process identity's untouched (test_two_sessions_charge_their_own_identities_ledgers).
    • A 429 with retry-after: 1 is retried once after a 1 s wait, three 502s raise GitHubUnreadError after two retries, and a write that gets a 502 is sent once (test_a_429_with_retry_after_is_retried_once_after_that_wait, test_three_502s_raise_the_unread_error_after_the_retries, test_a_write_that_gets_a_502_is_not_sent_again).
    • Pacing, charging, the retry wait and its throttle record take the ledger's lock only in anyio worker threads, never on the portal's loop (test_the_ledger_is_only_read_and_charged_off_the_event_loop).
    • The session's client has one request hook comparing request.url.origin with the origin of CONST_URL_GITHUB_API_BASE, with no host tuple, netloc comparison, startswith or scheme-string test. The 2026-10-03 redirect table passes: a 301 to the moved repository, a relative Location, an upper-case host with :443 and a 301 then a 307 are followed with the token on every hop (test_redirects_on_the_api_origin_are_followed_with_the_token_on_each_hop). A hop to example.com, to userinfo naming GitHub, to another port on GitHub's API host, to http:// and to github.com raises GitHubUnreadError naming the origin with exactly one request recorded (test_a_redirect_off_the_api_origin_is_refused_before_it_is_sent). The plan's look-alike host api.github.com.example.com gave way to api.github.com:8443: AGENTS.md allows no subdomain in a mock host, and the port case was missing.
    • tests/test_github_errors.py maps a 401, a 403 with no quota left, a 403 with retry-after, a 429, a 403 with a missing scope, a 403 with an accepted scope held, a 403 whose message says rate limit without its headers, a 404, a 422 and a 5xx after the retries to their classes, each with its int status and its path. A refused connect, an undecodable body, an unknown charset, a 520 and quota headers that are not numbers raise GitHubUnreadError without a retry. A retry wait past max_rate_limit_wait raises GitHubRateLimitError with the path and the status 429. No classification in src/devops_cli/github/error_classifier.py reads a response's message text.
    • test_get_pr_diff_normal_and_redirect (tests/test_github_client.py) and test_add_signing_key (tests/test_github_ssh.py) run over the shared fake; the signing key's 201 and 422 pass, and its missing scope and 5xx raise GitHubScopeError and GitHubUnreadError. A diff answered without a content type, or as JSON, raises GitHubUnreadError (test_an_answer_that_is_no_diff_raises_the_unread_error).
    • Egress vetting still applies through the session: the factory builds its client at EgressLevel.PUBLIC, and a request whose host comes to resolve to loopback raises SSRFBlockedError before anything reaches the fake (test_the_sessions_requests_are_vetted_at_the_public_egress_level). A test that asks for github_api and stub_web together fails instead of one fake silently winning (test_the_fake_github_api_and_stub_web_refuse_to_share_a_test). git diff origin/release/v0.2.37 -- src/devops_cli/http/ prints nothing.
    • A brace in a path is sent percent-encoded, not dropped by the template expansion (test_braces_in_a_path_are_sent_as_literal_characters).
    • A process that sent a request and never closed its session exits: a child interpreter that sends one request over the fake, resets the session and sends another through the same held session exits 0 within its 30 s bound (test_a_process_that_sent_a_request_exits_without_closing_its_session). reset_github_session() and a token change close the session's client and stop its portal thread (test_reset_closes_the_sessions_client_and_portal, test_a_token_change_closes_the_replaced_session). Closing cancels a request waiting out a 30 s retry wait, which fails as GitHubUnreadError within 5 s (test_closing_a_session_cancels_a_request_waiting_out_a_retry), and requests in flight at a close fail only with GitHubUnreadError (test_closing_a_session_mid_flight_fails_each_request_with_a_typed_error).
    • No new test opens a socket or runs a real gh: the github_api fixture seeds the core quota, fails a test whose quota would need a gh api rate_limit refresh, and records the limiter's pauses and the retry waits instead of sleeping, replacing only the rate limiter's clock and gidgethub's wait. Every quota header a test sends is built when the test runs, so its reset is still ahead however long the suite has been running. Each new test's call phase is under 0.3 s, except the exit test, whose child interpreter takes about 3 s to import devops_cli.
    • session.paginate() follows rel="next" page and cursor links and yields one flat sequence for a plain array and for check_runs, workflow_runs and items pages (test_linked_pages_yield_one_flat_sequence, three pages each). A page without a next link, or [], ends the listing (test_a_short_listing_is_one_request, test_an_empty_page_ends_the_listing). A consumer that stops after the first item sends one request (test_a_consumer_that_stops_after_the_first_item_sends_one_request).
    • paginate() stops at DEFAULT_GH_MAX_PAGINATED_PAGES, the cap the other paginated readers keep, read when the listing runs. With the cap at 2, a chain of next links raises GitHubUnreadError naming the endpoint and the cap after exactly 2 requests, and a listing of exactly 2 pages is read whole (test_a_listing_that_runs_past_the_page_cap_fails_closed, test_a_listing_of_exactly_the_page_cap_reads_every_page).
    • A Link to https://example.com/repos/octo/repo/issues?page=2 raises the origin refusal, and the transport sees no request to example.com (test_a_link_to_another_origin_is_refused_before_it_is_sent).
    • An HTML, an error-object, a wrapped error-object, a truncated and an empty second page each raise GitHubUnreadError naming the endpoint and page 2, after page 1's items (test_a_page_that_is_no_list_of_items_fails_closed). No page goes through extract_json_payload.
    • The issue and milestone reads run over the fake. tests/test_github_issues.py covers reading every page with labels and filtering, stopping at the limit after one request, and failing closed on a 5xx, a 404, an object and a body that is not JSON. tests/test_gh_issues_milestones.py covers resolving a number without a request, stopping at the matching title on page 1 or 2, an unknown title, and an unreadable page that is not reported as a missing milestone.
    • tests/test_github_errors.py maps every phrase of the gh-output table, upper-cased, to its class (test_a_gh_failure_is_classified_by_its_exit_status_and_the_gh_output_table). It does the same for gh's own outputs for HTTP 401, Bad credentials, Requires authentication (HTTP 401), not logged in, unknown owner type and exit status 4, and maps a 404, a 422, a 500 and silence to no class. A fix/...-retry-after branch gh echoes in a URL or message is no rate limit, and a 401 whose URL names it is unauthenticated (test_text_gh_echoes_from_the_request_names_no_rate_limit). The status gh names is read as an int from both of gh's formats, beside gh's exit status, and gh's output is bounded to 256 characters on one line.
    • rg -n 'CONST_GITHUB_RATE_LIMIT_PATTERNS|CONST_GITHUB_SECONDARY_RATE_LIMIT_PATTERNS|check_github_rate_limit_error|scope_error_patterns|"needs the" in|"rate limit" in|"not logged in" in' src matches only config/constants.py, config/__init__.py and github/error_classifier.py.
    • Each caller raises the classified error for a rate limit its old phrase list missed. run_gh backs off at least the secondary floor and retries (tests/test_github_rate_limiter.py). verify_project_auth_scopes raises it, and also a missing scope, a refused token, no login and exit 4, and asks for the project scope; the board lookup raises the same classes and finds no board on a 500 (tests/test_github_projects.py). So do a failed board read, the roadmap store's reads (tests/test_roadmap_github_store.py) and devops pr ready, whose message is one paragraph (tests/test_pr_cmd.py). _gh_add_key covers an added key, a missing scope, a rate limit, a refused token and another failure, and a 422 for an invalid key, a key in use elsewhere, a listed key and an unreadable listing (tests/test_github_ssh.py). devops gh views sync keeps [read:project] (tests/test_gh_cmd.py).
    • gh's stdout is never classified. A failed gh api graphql whose partial answer on stdout holds a title reading like a rate limit, a scope, a refused login or an owner lookup fails as a plain failed read, in a board read and in the store's reads, and run_gh sends it once with no backoff (test_a_failed_board_read_classifies_gh_s_stderr_never_the_titles_on_stdout, test_a_failed_read_classifies_gh_s_stderr_never_the_titles_on_stdout, test_run_gh_backs_off_on_gh_s_stderr_never_on_github_s_answer_on_stdout).
    • An owner gh project can't look up is resent as --owner @me at once, through the real run_gh, with no backoff or throttle; a rate limit is never resent as @me (test_an_owner_lookup_failure_is_asked_for_as_me_at_once_through_run_gh, test_only_an_owner_gh_project_cannot_look_up_is_asked_for_again_as_me).
    • rg -n 'HTTP_STATUS_RE' src matches only config/constants.py and github/error_classifier.py.
    • devops gh issues list with gh api rate_limit failing HTTP 401: Bad credentials prints the unauthenticated error, exits 1 without a traceback and sends no listing (test_gh_issues_list_reports_a_refused_token_as_the_unauthenticated_error, tests/test_gh_cmd.py); with the refresh timing out it prints the unread error the same way. A refresh GitHub refused, or gh exited 4 for, raises GitHubUnauthenticatedError, and a rate-limited one GitHubRateLimitError; a 502, silence, a timeout or an empty answer raises GitHubUnreadError (tests/test_github_rate_limiter.py). devops roadmap intake --plan whose refresh times out ends with that error, exit 1 and no traceback. A refused token or a rate limit at the refresh stops an intake round after one refresh, and an unread quota skips the candidate and writes the next (tests/test_roadmap_intake.py).
    • Not in refactor(github): the github session owns transport, ledger, error classes and link pagination #983: _is_branch_unprotected_error (github/branch_protection.py), create_repository_issue (github/issues.py), _report_create_failure (commands/pr.py) and extract_retry_after (github/rate_limiter.py) still match gh's text of their own. Their follow-up is the 2026-10-19 amendment on #891, refactor(github): route the remaining gh-text matchers through the gh classifier.
    • devops gh api 'repos/:owner/:repo/issues' --paginate -q '.[].number' hands gh that argv unchanged, and gh's output is printed (test_gh_api_hands_gh_its_paginate_and_jq_flags_unchanged, tests/test_gh_cmd.py).
    • A two-page timeline gives _query_timeline_copilot_state both Copilot events, and a timeline page that is no list leaves the state unread naming page 2 (tests/test_github_pr_monitor.py). The reviews are read from every page, and a failed reviews read gives none and its reason.
    • A malformed second check-runs page (HTML, check_runs not a list, an error object or a 502) makes the readiness read a failure, never a short list (test_a_malformed_second_check_runs_page_is_a_read_failure_in_readiness, tests/test_pr_check_runs.py, and test_check_readiness_fails_closed_when_second_page_check_runs_malformed through the CLI, tests/test_pr_cmd.py).
    • The pull request's files are read from every linked page, and a malformed page is the read's failure (tests/test_pr_cmd.py). The repository listings are read from every linked page and a malformed page raises (tests/test_github_projects.py). The reconcile dry run still lists the kinds of request a run sends, in order, with the listings as session GETs (test_the_dry_run_lists_the_requests_a_run_sends_in_order).
    • A GraphQL --paginate request with no document, a document on stdin the classifier doesn't see (-F query=@-, --input -) or an unreadable file is paced as a write, and a readable paginated query as a read (the paginated-graphql-* rows of _API_REQUESTS, tests/test_github_rate_limiter.py).
    • A devops gh api --paginate call runs under DEFAULT_GH_API_PAGINATE_TIMEOUT_SECONDS and any other under DEFAULT_GH_SUBPROCESS_TIMEOUT_SECONDS (test_gh_api_gives_a_paginated_walk_the_listing_timeout, tests/test_gh_cmd.py).
    • A repository-list entry that is an int, None or a string, in issues or pulls, raises GitHubUnreadError naming its type (test_a_repository_listing_entry_that_is_no_object_fails_the_read, tests/test_github_projects.py), and the error names no entry text and bounds the path (tests/test_github_errors.py).
    • The test fakes tell a session read from a one-page run_gh read. tests/test_pr_cmd.py's routed session records each read, asks its run_gh stub with a <session> GET argv and refuses to run with run_gh unstubbed (test_the_routed_session_refuses_an_unstubbed_run_gh); the reconcile fake answers no gh listing. Offline, a _fetch_pr_files regressed to one gh api page fails test_grounding_reads_the_files_the_base_and_the_closed_issue_once_each, and a _fetch_repository_list regressed to one run_gh page fails the 25 reconcile, sync and CLI tests over the reconcile fake, which refuses the gh listing.
    • rg -n "_extract_page_per_page|_build_paginated_url|_append_paginated_data|_fetch_all_pages|_run_gh_paginated|incompatible_gh_api_paginate_flag|parse_paginated_json|run_gh_async|aiolimiter" src tests pyproject.toml and rg -n '"--paginate"' src/devops_cli/github src/devops_cli/commands/pr.py src/devops_cli/roadmap print nothing. The tests of the deleted loop went with it, test_paginated_read_fails_closed_when_exceeding_page_cap, which spun through 100 pages, among them.
    • rg -n "listing_page_args|_read_listing|check_github_rate_limit_error" src prints nothing.
    • The store's listings run over the github_api fake and its board commands over RecordedGh (over_github, tests/test_roadmap_github_store.py): a failed listing raises the session's unread error and a rate-limited one the rate limit; linked pages are read on; a page that is HTML, empty or an error object, first or later, raises naming the listing and the page, for milestones, issues, events, comments and dependencies; merged pull requests read every linked page and each one's files, and a failed page or files listing raises.
    • changes_since follows the events' linked pages and stops at the first older event without asking for the next; one whose second event is older than the cutoff sends one events request (test_changes_since_whose_second_event_is_older_than_the_cutoff_sends_one_request); the pull request and Release listings stop the same way; a chain past the page cap raises.
    • tests/test_roadmap_store_contract.py builds the GitHub adapter with a session, which reads its Releases in one request (test_both_adapters_are_roadmap_stores).
    • The plan lists each listing as the session's GET and URL, and a run's calls still follow its plan (tests/test_roadmap_dry_runs.py, tests/test_roadmap_intake.py, tests/test_roadmap_close.py).
    • An owner lookup gh drops is decided by GraphQL's own budget, never REST's: points left make a plain failure that names them and still allows a secondary limit; a spent budget, a budget read refused for a secondary limit or unread keeps the rate limit; a refused token is the unauthenticated error (test_an_owner_lookup_gh_drops_is_decided_by_graphqls_own_budget). Through the real run_gh, a budget read failing with GitHub's body on stdout keeps the owner lookup's error or the unauthenticated one (test_through_run_gh_a_failed_budget_read_after_an_owner_lookup_is_classified). With the budget read refused for a secondary limit, an intake round stops at its first candidate (tests/test_roadmap_intake.py), and a board read in github/projects.py decides the same way (tests/test_github_projects.py).
    • A Release for an older tag published after the cutoff, listed below one that shipped before it, is a ship, with one Releases request (test_an_older_tag_published_after_the_cutoff_below_an_earlier_ship_is_a_ship).
    • A store the factory opens with no session reads its listings through the process's session and none through gh (test_a_store_the_factory_opens_reads_its_listings_through_the_processs_session).
    • The spend meter counts the requests the ledger paced since it started, gh commands and session requests alike, by resource (test_the_spend_meter_counts_every_request_the_ledger_paces_and_each_model_call).
    • A failed gh api rate_limit returns its exit status and parses no quota from its body (test_a_failed_rate_limit_read_returns_its_exit_status_without_reading_its_body).
    • A refusal on the session path of devops ssh is a registration error: register_key_on_github raises it, and rotate removes the new key and exits 0 (tests/test_github_ssh.py, tests/test_ssh.py).
    • devops gh milestones list names a listing GitHub fails with a 502 as the session reports it, with the status, over the github_api fake (tests/test_github_milestones.py).
    • The session's client connects within DEFAULT_GH_SESSION_CONNECT_TIMEOUT_SECONDS and keeps the factory's read timeout (test_the_sessions_client_waits_a_public_connect_timeout_and_the_factorys_read_timeout), and a ConnectTimeout still raises the unread error naming the endpoint after one request (test_a_connect_timeout_raises_the_unread_error_naming_the_endpoint_without_a_retry, tests/test_github_session.py).
    • A signing key's 422 is registered when the session lists the key or can't read the listing, and raises for an invalid key or one in use elsewhere (test_a_signing_key_422_counts_as_registered_only_when_the_session_lists_the_key, tests/test_github_ssh.py).
    • A second GET of a URL sends If-None-Match with its first answer's ETag (test_a_second_get_of_a_url_sends_the_etag_it_was_answered_with). A 304 returns the stored body, is paced, and leaves the ledger at the x-ratelimit-remaining it reported (test_a_304_answers_with_the_stored_body_paced_and_charged_with_the_quota_it_reports).
    • Two sessions never share a cache: a session over another token sends no If-None-Match for a URL the first one read (test_a_session_over_another_token_sends_no_etag_for_the_same_url). A POST stores nothing (test_a_post_stores_nothing), and the store keeps only the latest DEFAULT_GH_SESSION_ETAG_CACHE_SIZE URLs (test_the_session_keeps_the_etags_of_its_latest_reads_only).
    • A conditional GET retried after a 502 carries its If-None-Match again and answers from the store (test_a_conditional_get_retried_after_a_502_still_answers_from_its_etag). A caller that changes an answer leaves the stored one as GitHub sent it (test_a_caller_that_changes_an_answer_leaves_the_stored_one_as_github_sent_it).
    • A page answered 304 keeps its next link and the listing reads on, and the last page is read in full (test_a_page_answered_from_its_etag_keeps_its_next_link_and_the_last_page_is_read_in_full). A full last page that gains a next page is read on to it (test_a_last_page_that_gains_a_next_page_is_read_on_to_it), and a stored page that is no list still fails closed (test_a_page_answered_from_its_etag_that_is_no_list_of_items_still_fails_closed).
    • A one-page listing leaves nothing stored (test_a_one_page_listing_leaves_nothing_stored), so with room for three answers, three one-page listings read between two reads of a two-page listing leave its first page to be sent conditionally (test_one_page_listings_leave_the_store_to_pages_that_can_answer_304). A listing reads in full a last page a rest() GET stored (test_a_listing_reads_in_full_a_last_page_a_rest_get_stored).
    • devops --help, devops gh --help, devops roadmap --help and devops pr --help leave cachetools unimported (test_help_leaves_the_github_sessions_etag_store_unloaded, tests/test_cli_startup_imports.py).
    • The GitHub session's fake lives in tests/support/fakes/github.py with its github_api fixture, tests/conftest.py defines neither the fixture nor install_async_client_fake, and rg -n github_session_fakes tests src docs/TESTING.md docs/adr prints nothing.
    • The contract suite passes against the fake and the recorded real side: tests/test_github_contract.py's ten cases each pass over GitHubApiFake and over GitHub's answers recorded on 2026-10-19, with every recorded answer asked for, and each fails under a mutant of the fake or the session (Red Then Green).
    • The fake's own 304 reports the quota it last reported for the resource, and its own 404 spends one from it, as GitHub's do (test_a_read_after_a_404_is_answered_from_its_etag_with_the_quota_github_reports, test_a_read_of_nothing_raises_the_not_found_error_and_charges_the_quota_github_reported), and a text answer carries a quota (test_a_write_answers_the_text_github_rendered).
    • Under github_api, a reader that falls back to run_gh fails offline with A test over the fake GitHub API ran gh: ['gh', 'api', 'repos/octo/repo/pages'] and starts no gh (test_a_reader_that_falls_back_to_gh_fails_offline_under_the_fake_api).
    • The seven rows gh writes for no GitHub failure name no class (test_a_phrase_gh_writes_for_no_github_failure_names_no_class), and neither does a proxy's Proxy Authentication Required (test_a_gh_failure_is_classified_by_its_exit_status_and_the_gh_output_table, tests/test_github_errors.py).
    • uv run devops ci passes in 3 min 19 s, inside its 5-minute budget. The full suite passes offline under a scratch plugin that refuses to start a real gh, which no test reached: 11,041 passed, 1 skipped and 8 xfailed, the base's 11,028 tests and PR 7's 22. Each of PR 7's tests' call phase is under 0.05 s, and none opens a socket.
    • changelog.d/983.md exists, and git diff origin/release/v0.2.37 --stat -- CHANGELOG.md docs/ROADMAP.md prints nothing.
    • Pending a person (live GitHub, read-only, after PR 4): uv run devops gh api 'repos/dan-petty/devops-cli/issues?state=closed' --paginate -q '.[].number' | wc -l prints more than 100.
    • Pending a person (after PR 4): uv run devops pr monitor <a PR with a Copilot review on its second timeline page> reports the Copilot state, not idle.
    • Pending a person (after PR 3): GH_TOKEN=not-a-real-token uv run devops gh issues list -R dan-petty/devops-cli exits 1 with the unauthenticated error and prints no issues.
    • Pending a person (after PR 6): with one devops serve process polling, uv run devops gh rate-limit --format json read around two consecutive ticks shows the second tick spending fewer core requests than the first.
  10. added a commit that references this issue on Oct 20, 2026
  11. removed
    status/in-progress
    on Oct 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p0-criticalscope/githubtype/refactor

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions