Skip to content

Back off exponentially on transient GitHub API failures, in praktika - #112974

Open
groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:fix-get-gh-api-5xx-retry-v2
Open

groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:fix-get-gh-api-5xx-retry-v2

Conversation

@groeneai

@groeneai groeneai commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Retry GitHub API reads with a capped exponential backoff instead of a fixed delay, so the Upgrade check rides out a longer transient 5xx or 429 from api.github.com during setup instead of failing on a routine blip. The policy now lives in praktika as GH.api_get.

Description

Related: #112205

Upgrade check (*) fails in setup (Download script failed) on a transient 5xx from the
GitHub releases API. get_previous_release_tag.py resolves it through get_gh_api,
which retried 5 times with a fixed 3 s sleep, so retries bounded the attempt count
but not the time window: a 12 s budget, which a routine blip outlasts. On PR #112205 a read
timeout at 10:06:15 was followed by four 504 retries 3 s apart, exhausted at 10:06:27.

Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112205&sha=66f93bffd6aa9d3b6f038bf7a6b59ac02a5b3f10&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29

The delay now grows as sleep * 2 ** (attempt - 1), capped at 60 s, for the classes
transient by definition: every 5xx, 429, and transport errors, giving a 45 s default
window. Terminal statuses keep the flat sleep, and the growth base is the caller's own
sleep, so the pr_info.py sites passing RETRY_SLEEP = 0 still get none. An outage that
outlasts the whole budget still raises.

Per review the policy lives in ci/praktika/gh.py as GH.api_get, reusable by any praktika
job, with get_gh_api a thin shim over it. The failover has to stay in ci/tools because
get_robot_token imports boto3 and PyGithub at module level, so the shim keeps its
signature, its APIException and the failover, driving the latter through an
on_http_error callback that restarts the budget exactly once. All eight call sites are
unaffected.

The Upgrade check digest now also lists build_download_helper.py and gh.py, which its
entry scripts import: without them the job filter read this very change as unaffected.

Validated locally, since changes to the CI code ship without tests of it: 31 scripted-response
cases across both layers, each checked against a deliberate mutation of its subject, plus a
live get_previous_release_tag run.


Workflow [PR]
Sync PR [sync-upstream/pr/112974]

groeneai and others added 7 commits August 1, 2026 18:11
get_gh_api retried 5 times with a fixed 3 second sleep. Its only special
branches are a 403 carrying "rate limit exceeded" and a 404, so everything
else including 5xx shared one generic tail: 4 x 3 s = a 12 second window,
which any longer GitHub blip exhausts. That reddened Upgrade check (*) in
its setup phase, before any ClickHouse binary started, so the failure said
nothing about the PR under test. 9 occurrences over 45 days across 9
distinct PRs, 0 on master.

ClickHouse#107916 gave the asset download in this file a capped exponential backoff
and introduced DOWNLOAD_RETRY_MAX_BACKOFF for that purpose, but left
get_gh_api, the metadata fetch that runs first in the same call chain,
using the fixed sleep.

Give that shared tail the same capped exponential backoff, scoped to the
statuses that are transient by definition: 5xx, 429 and transport errors
such as the read timeout that opened the reported failure. At the default
sleep the failing window grows from 12 to 45 seconds.

Every 4xx keeps its behaviour byte for byte, including both auth failover
branches. Distinguishing a transient 403 (GitHub's secondary rate limit,
or abuse detection) from a terminal one would require matching a response
body, and the existing predicate provably misses both of those messages,
so reclassifying 4xx would trade this starvation for a subtler one.

The multiplier is the caller-supplied sleep rather than a literal, so the
pr_info.py call sites that pass RETRY_SLEEP = 0 keep sleeping not at all.
The retry log is promoted to a warning naming the attempt, the retry count
and the delay, so the next occurrence is triageable from job.log alone.

Add ci/tests/test_get_gh_api_retries.py, which drives the real function
against scripted responses without sleeping: 4 of its rows fail before
this change and all 13 pass after. Each row pins one invariant, including
the 4xx budgets, the 403 and 404 failovers, the zero-sleep callers and the
backoff cap.

Co-Authored-By: Claude Fable 5 <[email protected]>
The cap test asserted only max(sleeps) == DOWNLOAD_RETRY_MAX_BACKOFF and an
upper bound on every sleep, which says nothing about the growth before
saturation. An implementation that applies the cap immediately whenever
retries exceeds DOWNLOAD_RETRIES_COUNT yields nine 60-second sleeps and
satisfies both assertions, so it survived the whole suite: every other row
uses the default retries and cannot see it. Asserting the exact sequence
kills that mutant while the retained max(...) line keeps the literal values
tied to the named constant, so retuning the constant still fails loudly
instead of drifting.

Also shorten the 4xx-exclusion comment to three lines. The argument about
which 403 bodies the rate-limit predicate misses is already in the PR
description; only the scope statement needs to sit at the call site.

No production behaviour changes: stripping comments from both revisions of
build_download_helper.py gives identical files.

Co-Authored-By: Claude Fable 5 <[email protected]>
Attempt 1 of the reported production failure was a read timeout, but the only
transport row raised requests.ConnectionError, and ReadTimeout inherits
Timeout -> RequestException rather than ConnectionError. A change that kept the
growing backoff for connection resets while dropping it for read timeouts
therefore passed the whole suite, so the test could not see a regression on the
scenario the change exists for.

Parameterize that row over both classes by threading the exception class through
the harness instead of a bool.

Patch only requests.get on the real module rather than replacing bdh.requests
with a namespace exposing get, HTTPError and ConnectionError. With the namespace
in place, any future handler naming another requests attribute raises
AttributeError inside the function under test, which reports a behavioural
regression as an unrelated crash. Measured on a handler added for
requests.Timeout: the namespace form fails with
"assert 'AttributeError' == 'APIException'", the single-symbol form with
"assert [3, 3, 3, 3] == [3, 6, 12, 24]". monkeypatch restores the attribute per
test, and ci/tests/test_download_build_with_progress.py already patches a single
symbol this way.

tests/ci/build_download_helper.py is unchanged.
Two oracles in the new suite could not observe a regression in the behaviour
they guard, so a change violating the stated contract would have stayed green.

Row 8 passed a preset token for all five of its cases. With the token already
set, the failover guard is short-circuited by `not token_is_set` alone, so the
403 body predicate was never load-bearing: widening it to every 403 kept the
attempt count and the sleep sequence identical and the whole suite passed.
The preset only changes the outcome for the 404 case, so the four cases where
it is inert now run without it and additionally assert that no auth header was
ever added; the 404 case keeps the preset in a row of its own.

Row 1 asserted the exponential sequence for 504 only, and row 3 for 503, so
narrowing the predicate from `>= 500` to `in (503, 504)` also passed. Row 1 is
now parameterized over the boundaries of the contract: 500, 502, 503, 504, 599.

Verified in both directions against the two mutants: each is fully green on the
previous suite and fails on this one, on the new assertion and on the sleeps
sequence respectively. No other mutant's failure set shrank.

Co-Authored-By: Claude Fable 5 <[email protected]>
A bare 429 is the one status that is both a 4xx and newly eligible for the
growing backoff, so it must get the backoff and must not get the 403/404 auth
failover. The row pinned only the first half: widening the failover predicate
to cover 429 grants it a robot token and an extra attempt, yet the counter
reset re-warms the backoff from the base sleep, so the four recorded sleeps are
unchanged and the row still passed. Bind the attempt count and the observed
auth headers so the second half is guarded too.

The module docstring also claimed every 4xx keeps its existing behaviour two
bullets after stating that 429 gets the new backoff. Name the exception.

Co-Authored-By: Claude Fable 5 <[email protected]>
The retry test drove ten distinct statuses, and 499 was not among them. Nothing
adjacent to the threshold was covered from the 4xx side, so lowering the
predicate to `status_code >= 499` produced a byte-identical sleep sequence for
every status the suite exercised and survived the whole run, while quietly
giving HTTP 499 the exponential window [3, 6, 12, 24] in place of [3, 3, 3, 3].

The published promise is that every other 4xx keeps its current behaviour
exactly, so the whole 4xx range is contract and the range needs a guard next to
the threshold, not only above it. Row 8a gains one 499 parameter; the
assertions, the rows around it and the helper are unchanged.

No 400 case: 400 sits in the same equivalence class as the already-covered 401
and 422, so its sleep sequence is identical under both the shipped predicate and
the lowered-threshold mutant, and it kills nothing 401 does not already kill.

Co-Authored-By: Claude Fable 5 <[email protected]>
Two gaps in the guard added earlier in this branch.

The retry log line is the only trace a CI operator gets of a transient GitHub
API failure, since the job's stdout is the sole place it appears. The diff
raises it to a warning and adds the attempt number and the delay, but nothing
observed any of that: all 19 cases passed with the line reverted to the old
`logger.info("Exception '%s' while getting, retry %i", ...)`. A new case pins
the level and the two fields the message promises. Verified in both directions:
reverting the block to the old one-liner reddens exactly that case (no WARNING
records at all), and keeping the warning while dropping the attempt and delay
reddens it too. The twelve recorded policy mutants are unaffected, so no
existing case lost a killer.

`CI Tests` digested `./ci`, `./tests/clickhouse-test` and
`./tests/queries/shell_config.sh`, but not the helper the new guard loads by
relative path. So a future PR touching only `tests/ci/build_download_helper.py`
was filtered out as unaffected, and its digest was byte-identical, hence an S3
cache hit: the assertions would never execute. 9 of the last 15 master commits
to that helper touched zero files under `ci/`, including the previous change to
this very retry code. Adding the single file flips affectedness for it while
leaving `tests/ci/pr_info.py` and `docs/` unaffected, and makes the digest move
when the helper changes; including the whole directory would have added 42
files and rerun the job for 11 of the last 200 master commits.

`tests/ci/build_download_helper.py` is unchanged by this commit.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent model reviewed each revision cold against the code on disk. Every finding was
adjudicated by verification rather than by assertion: each accepted one was reproduced by
building the implementation it describes and measuring it green before the fix, red after. All
concerned the test's ability to detect a future regression, or the CI wiring around it. The
production helper has been byte-identical for the last seven revisions.

❌ Vacuous cap oracle (fixed). Asserting only max(sleeps) == DOWNLOAD_RETRY_MAX_BACKOFF
said nothing about growth before saturation: capping immediately whenever retries exceeds
DOWNLOAD_RETRIES_COUNT gives nine 60-second sleeps and passed the whole suite. The row now
pins the exact sequence, keeping the max(...) line so the literals stay tied to the constant.

❌ Read timeouts uncovered (fixed). The transport row raised only requests.ConnectionError,
though the reported failure opened with a read timeout and requests.ReadTimeout is not a
subclass. Granting the backoff only inside except requests.ConnectionError passed fully green.
Now parameterized over both; ConnectTimeout is already a ConnectionError, so that is complete.

❌ Unfaithful test double (fixed). Replacing the whole requests module with a three-attribute
namespace turned a real regression into an unrelated AttributeError raised inside the function
under test. Patching only requests.get on the real module yields the honest sleep-sequence diff.

❌ The 4xx row could not see its own predicate widen (fixed). It preset a token for every case,
short-circuiting the failover guard, so widening the rate-limit body predicate to every 403 kept
the suite green. Split into a no-preset row (plus an assertion that no failover fires) and a
preset row owning the 404-with-token budget.

❌ The >= 500 boundary was exercised only at 503 and 504 (fixed). Narrowing to in (503, 504)
satisfied every row. Now parameterized over 500, 502, 503, 504, 599, with 499 pinning it from below.

❌ The 429 row could not see the failover widen to 429 (fixed). It asserted sleeps but discarded
the attempt count and header history, and the failover's counter reset re-warms the backoff, so
adding 429 to the failover predicate left the recorded sleeps unchanged. It now asserts the attempt
count and that no attempt carried an Authorization header. 429 is the only status with this gap,
being the only one both 4xx and newly retryable.

❌ Nothing observed the promised retry diagnostic (fixed). Reverting the new logger.warning to
the old info one-liner, or dropping the attempt or delay from it, left all 19 cases green. A row
now asserts the WARNING record and both fields; each mutation reddens exactly that row.

❌ The new guard would not have run when its subject changed (fixed). CI Tests digested
./ci but not the helper, so is_affected_by(['tests/ci/build_download_helper.py']) was False
and a helper-only change could hit a cached result. That path is now an explicit include and flips
to True, while tests/ci/pr_info.py and tests/ci/lambda/requirements.txt stay False.

⚠️ Comment bloat and two overclaims (fixed). One block exceeded the 3-line ceiling; census over
the whole diff is now 19 blocks, none longer than three lines, comments not outnumbering added code,
and behaviour neutrality proved by stripping all comments from both revisions and diffing. The
description said every 4xx keeps its behaviour one sentence after excepting 429. The test docstring
called get_gh_api the single chokepoint for every GitHub API call in tests/ci, which is a shade
too strong: GH.get_commit_status_by_name, get_failed_statuses, check_wf_completed
(ci_utils.py) and GH.cancel_wf (github_helper.py) bypass it. Those serve the auto-release
path, not any check setup, so the fix is still general over every path producing this failure.

💡 Noted, not blocking. Three other ci/tests/ guards (test_download_release_packages.py,
test_pr_version_info.py, test_cherry_pick_branches.py) put all of tests/ci on sys.path and
still have the digest gap this PR closes for the helper. Closing theirs means including
./tests/ci wholesale, which widens the CI Tests digest considerably, so it is a separate change.

Twelve policy mutants plus two for the diagnostic; no mutant's kill set shrank as rows were added.

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A probe drives the real get_gh_api against scripted responses with time.sleep recorded rather than executed. On master a persistent 504 gives attempts=5 sleeps=[3,3,3,3] total=12s, matching the job.log window (10:06:15 to 10:06:27) to the second; with the fix, [3,6,12,24] total=45s. No build or server needed.
b Root cause explained? Yes. One generic retry tail with a fixed sleep gives 5 attempts x 4 gaps x 3 s = a 12 second window; a longer outage exhausts it, APIException escapes, and upgrade_runner.sh prints Download script failed. The 12 s was measured against the real function, not inferred.
c Fix matches root cause? Yes. The defect is this function's retry policy, so the sleep now grows (capped) for the statuses transient by definition. No widened bound, no skip, no defensive guard. DOWNLOAD_RETRY_MAX_BACKOFF and the in-file precedent already existed for this purpose.
d Test intent preserved / new tests added? Yes. No existing test modified or weakened (the 12 sibling cases in the three neighbouring download tests still pass). New ci/tests/test_get_gh_api_retries.py: 20 cases, each pinning one invariant carrier, with a 12-mutation proof that every row pinning new behaviour is load-bearing rather than vacuous. One deliberate exception: the success-path row asserts no sleep pattern, so it guards "a blip that clears still succeeds" independently of the backoff formula.
e Both directions demonstrated? Yes. The same test file byte-for-byte: 10 cases fail against a pristine master copy of the module, 20/20 pass here. Plus the probe pair, 12 s to 45 s for 5xx while every 4xx status keeping its old policy stays at 12 s.
f Fix is general across code paths? Yes. Fixed at the shared entry point of the 8 call sites that use it (get_previous_release_tag.py:65,92, pr_info.py:97,181,194,230,427, report.py:83), not at the one caller that failed; every call site on the upgrade check's setup path goes through it. Siblings audited and out of scope: download_build_with_progress and download_release_packages.py were hardened by #107916; get_with_retries is unchanged because its only production caller passes retries=1 and the outer loop owns the backoff, so changing it would double-apply; GH.get_commit_status_by_name / get_failed_statuses / check_wf_completed (ci_utils.py) and GH.cancel_wf (github_helper.py) issue bare requests calls that bypass this helper, but they serve the auto-release path rather than any check setup.
g Fix generalizes across inputs? Yes, and the matrix is in the test file. Statuses 500/502/503/504/599, 429, 401, 422, 499, 403 with three distinct bodies (primary rate limit, secondary rate limit, abuse detection), 404 with and without a preset token, 200-after-5xx, and two transport-error classes. Parameters sleep=3 and sleep=0, retries=5 and retries=10. Boundaries: the first sleep (multiplier 1), cap saturation, the 5xx threshold from both sides, and the degenerate sleep=0.
h Backward compatible? Yes, nothing at risk. No user-visible behaviour, no settings, no SettingsChangesHistory.cpp, no serialization format, no release-branch coupling. Same exception type, same attempt counts, same branch conditions; only the delay between attempts of a failing 5xx/429/transport call changes, and callers asking for no sleep still get none.
i Invariants and contracts preserved? Yes. APIException remains the contract: report.py catches it specifically and with safe=True falls back to GITHUB_RUN_URL, and this change adds no raise site, so the single existing raise stays the only exit with its __cause__ chaining intact. Which errors are retried is unchanged, since the new flag only selects the sleep formula and never continues, breaks or raises, confirmed by identical attempt counts across the matrix. The failover reset invariant holds: indexing off the attempt counter means the reset re-warms the backoff to the base sleep, and the 404 row shows the same 6 attempts and [3,3,3,3] as before. The cap holds on every path, asserted at retries=10 where 4 of 9 sleeps saturate. The flag is initialized at the top of each loop iteration, so both the generic exception path and the continue path are well-defined and no iteration reads a stale value.

Session id: cron:clickhouse-review-slot-9:20260802-023001

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @leshikus, could you review this? get_gh_api retried a 5xx five times with a fixed 3 second sleep, so a GitHub API blip longer than 12 seconds hard-failed Upgrade check in setup; the retry tail now uses a capped exponential backoff for 5xx, 429 and transport errors, multiplying the caller's own sleep so the RETRY_SLEEP = 0 callers in pr_info.py still sleep not at all.

@leshikus
leshikus self-requested a review August 3, 2026 11:03

@leshikus leshikus left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The change of retry policy is not in changed files, only the tests present

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

The retry policy change is in tests/ci/build_download_helper.py. That path has a tests/ prefix but it is production CI code: tests/docker_scripts/upgrade_runner.sh symlinks tests/ci/get_previous_release_tag.py into the upgrade job, and it calls get_gh_api from this file. Three hunks inside get_gh_api:

Likely what you looked at: of the seven commits on the branch, the policy is in the first two (9b4c68a7, 5473c304). The remaining five are test hardening, and the head commit 75a01ed0 touches only ci/defs/job_configs.py and the test file. So the head commit, or the latest push, shows no policy change. The Files changed tab, or gh pr diff 112974, shows all three files.

@leshikus

leshikus commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

‎tests/ci/build_download_helper.py is not a correct place where to put timeout policy; consider something like ci/praktika/gh.py

@groeneai

Copy link
Copy Markdown
Collaborator Author

I checked whether the failing call can reach ci/praktika/gh.py, and it cannot, for two independent reasons.

gh.py is a gh CLI wrapper, not an HTTP client. It imports no requests/urllib and every request goes through Shell running gh ... (do_command_with_retries, get_output_with_retries). The gh CLI requires a token even for public reads: with no GH_TOKEN and no gh auth login, gh api repos/ClickHouse/ClickHouse/releases exits 4 with "populate the GH_TOKEN environment variable", while the same unauthenticated request over requests returns 200. The failing call is get_previous_release() paging that public releases endpoint (get_previous_release_tag.py:65), and its container gets no GitHub token: get_run_command passes only S3_URL, RANDOMIZE_KEEPER_FEATURE_FLAGS, optionally USE_AZURE_/USE_S3_STORAGE_FOR_MERGE_TREE, and STRESS_GLOBAL_TIME_LIMIT (stress_job.py:127-180). I ran the gh.py path in that environment: it retries 3 times over 28s and returns an empty string rather than raising, so moving the policy there converts a loud 504 into a silent empty result.

praktika is not importable on that path. upgrade_runner.sh:15 symlinks the script to /usr/bin/get_previous_release_tag and pipes into it at line 30, so sys.path[0] is /repo/tests/ci and import praktika raises ModuleNotFoundError (measured, both with cwd /repo and outside it). This is the same constraint you documented in 1f35293: "auto_release.py could not simply import PackageDownloader: create_release.py imports ci.praktika.* at module top, while auto_release.py runs in the praktika-free tests/ci world."

If the objection is that the policy should not live in a tests/ path, the precedent you set in that commit does work here: a stdlib-only module under ci/jobs/scripts/ holding the backoff constants and the retryable-status predicate, consumed by get_gh_api. I verified the import works from a symlink-invoked tests/ci script, but only when the root is derived from os.path.realpath(__file__); os.path.abspath resolves to /usr/bin's parent through the symlink and fails.

I can do that split if you want the constants out of tests/ci. Relocating into gh.py is the one option I would avoid, since the retry would then never execute on the path that produced the failure. Which do you prefer?

@leshikus

Copy link
Copy Markdown
Collaborator

Why not to add a gh_api request wrapper to gh.py? in this case you can put the retry policy in there

@groeneai

Copy link
Copy Markdown
Collaborator Author

That works, and it corrects me: I said praktika is not importable on that path, and that was too strong. I had only tested a bare import praktika, which fails because sys.path[0] is /repo/tests/ci; inserting /repo/ci first imports fine. Re-ran against master 57b9bc5ef469 with the symlink invocation upgrade_runner.sh actually uses and with boto3, botocore and PyGithub masked to match the container: from praktika.gh import GH succeeds in 0.1s. boto3 is only reached via result.py to s3.py, where it is already try/except ImportError guarded, and python3-requests is in the stress-test image. pr_version_info.py already imports ci.praktika.result from tests/ci, so the precedent is in-tree. requests is not a new praktika dependency either: its pyproject lists requests>=2.25.0 as the one core dep and gh_auth.py already posts to api.github.com.

One property has to survive the move. get_gh_api raises on exhaustion, while get_output_with_retries returns '' by default, and report.py catches APIException specifically. It also does an unauthenticated first attempt with a 403-rate-limit/404 failover to a robot token, which needs get_robot_token (PyGithub, boto3) and so cannot move into praktika.

Plan, unless you want it differently:

  1. GH.api_get(url, retries, sleep, **kwargs) in gh.py: unauthenticated requests.get, capped exponential backoff on 5xx, 429 and transport errors, raising on exhaustion. Constants and the retryable-status predicate live there.
  2. build_download_helper.get_gh_api becomes a thin shim over it, keeping its signature, APIException and the token failover.
  3. The 20 retry cases move onto GH.api_get, with a smaller set left on the shim for the failover path.

The 8 call sites in get_previous_release_tag.py, pr_info.py and report.py stay unchanged, so RETRY_SLEEP = 0 still means no sleep. If you would rather I migrate those call sites to GH.api_get and drop the shim, say so; that is a larger diff and it moves the token failover into praktika, which is why I did not assume it.

ci/praktika/gh.py drifted since this branch's base and is now touched by this
change, so the merge happens before the edit.
The capped exponential backoff added earlier in this branch lived in
tests/ci/build_download_helper.py. A timeout/retry policy for GitHub HTTP reads is
framework knowledge that every praktika job can reuse, so it moves to ci/praktika/gh.py
as GH.api_get, and get_gh_api becomes a thin shim over it.

The split follows what can move: the policy is generic, while the robot-token failover
cannot leave tests/ci because get_robot_token imports boto3 and PyGithub at module level.
The shim therefore keeps its signature, its APIException, and the failover, driving the
latter through an on_http_error callback so the attempt budget still restarts exactly once
when a token is acquired.

Behaviour is unchanged for all eight production call sites. gh.py had no HTTP client
before this (0 requests calls, 11 Shell calls), so it gains a top level import requests;
gh_auth.py already imports it unguarded and runner.py already imports gh_auth, and
requests is praktika's one core dependency in ci/praktika/pyproject.toml.

api_get raises RuntimeError on exhaustion rather than returning an empty value like
get_output_with_retries, because a caller cannot tell an empty result from a failed read.
The shim translates that to APIException, which report.py catches to fall back to a run
URL instead of failing the job.

API_GET_RETRIES_COUNT is deliberately separate from Settings.MAX_RETRIES_GH: the latter
bounds gh CLI invocations, which need a token even for a public read, so the two paths
have different failure classes.

Two hazards the tests pin. ci/praktika/gh.py is importable under two module names that are
distinct module objects (praktika/__init__.py appends ci/ to sys.path), so the shim and
the tests both use the dotted ci.praktika.gh form; patching the other form leaves the
production path unpatched and reaching the network. And the sys.path root is derived with
realpath, not abspath, because get_previous_release_tag.py is invoked through a /usr/bin
symlink where abspath yields "/".

Tests split accordingly: policy cases drive GH.api_get, failover and error-class cases
drive the shim, plus new cases for the error translation and for raising on exhaustion.
tests/docker_scripts/upgrade_runner.sh:30 captures the stdout of
get_previous_release_tag.py into a shell variable and splices it unquoted
into `git clone --branch=$previous_release_tag`. That script prints the tag
on stdout and resolves it through get_gh_api, so the retry warning shared
the stream with the tag: as soon as a read was retried the variable held
the WARNING lines too and the clone was invoked with `--branch=WARNING:`.
The retry path is exactly the path this branch makes reachable, so it
turned a rare hard failure on a GitHub blip into a corrupted setup on the
same trigger. Measured with a scripted 504,504,200 through the real
get_gh_api: the captured stdout was two WARNING lines followed by the tag,
and is now the tag alone.

The test row that pinned this diagnostic asserted it on stdout, which made
the polluting stream the contract and let all 27 cases pass green with the
corruption present. It now asserts stderr and also asserts that stdout
carries no WARNING, so an echo-to-both regression still reddens, and a new
case pins the shell-capture contract directly.

Separately, an on_http_error callback returning True reset the attempt
budget before the sleep block with nothing bounding how many times it
could. The in-tree shim is safe because its token latch fires once, but
the hook is documented as an extension point, so a caller taking that at
face value got a sleepless loop against api.github.com: an always-true
callback issued over 200 requests with zero sleeps. Resets are now capped
at API_GET_MAX_BUDGET_RESETS = 1, which reproduces the shim's existing
behaviour exactly, and past the allowance the status is handled as an
ordinary error. The same probe now issues 6 requests and raises.

The local `import sys` in the __main__ block became redundant once sys was
imported at module level, and was removed; pylint findings on the file go
from 18 to 13 with no new messages.
@groeneai groeneai changed the title Back off exponentially when the GitHub API returns 5xx or 429 Back off exponentially on transient GitHub API failures, in praktika Aug 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — 8 rounds, 2 residual test-liveness gaps (click to expand)

An independent model reviewed each revision cold. Every accepted finding was reproduced by
building the implementation it describes and measuring it green before the fix, red after.

Equivalence, measured. I drove the pre-change get_gh_api and the post-change shim
against 11 scripted scenarios, comparing attempt count, sleep sequence, auth-header sequence
and exception class. Byte-identical except the three intended classes — including all three
403 bodies, both 404 failover paths, 401, 422, 200, sleep=0. The 404 failover
budget is retries + 1 = 6 in both trees, so routing the reset through on_http_error
reproduces the old try_cnt = 0 exactly.

❌ Fixed during the branch. The retry diagnostic went to stdout, which
upgrade_runner.sh:30 captures and splices unquoted into git clone --branch=$var; after
the fix, scripted 504, 504, 200 leaves stdout as exactly v25.8.1.100-lts, one shell
word. An unbounded on_http_error reset spun >200 requests with zero sleeps. The >= 500
threshold, the backoff growth before saturation, ReadTimeout, and the 429/403 predicate
boundaries were each pinned only after a mutation showed the suite blind to them. CI Tests
did not digest the helper, so a helper-only change could hit a cached result.

⚠️ Residual 1 — caller request options are not pinned across the new two-layer
delegation.
Deleting **kwargs from the shim's GH.api_get call leaves all 29 cases
green, yet get_previous_release_tag.py:65 needs params={per_page, page} and
pr_info.py:427-430 needs headers={"Accept": ...v3.diff}. The code is correct — both
really reach the request — but the fake transport ignores arbitrary kwargs. Fix: record the
kwargs per attempt and assert they survive.

⚠️ Residual 2 — the budget-reset test derives its bound from the constant it pins.
API_GET_MAX_BUDGET_RESETS 1 → 2 and 1 → 5 both leave the suite green. The bound is
enforced (an always-accepting callback yields exactly 6 requests, sleeps [3, 3, 3, 3]);
only the pin is self-referential. Fix: assert the constant and API_GET_RETRIES_COUNT + 1
as literals.

Both are test-liveness only, and both arrived at my internal round cap, so this publishes
as-is rather than taking a ninth round.

💡 Corrected in the description here: the case count read 27 where the suite collects 29,
and the 403 sentence claimed the predicate misses all three tested bodies — the primary
one matches it, which is why the failover fires for it.

One concern of my own, dismissed: the new unguarded import requests in gh.py cannot
break local runs — praktika.runner already reaches requests through cidb at the merge
base, gh_auth.py imports it unguarded, and pyproject.toml declares it praktika's single
strictly-required dependency. Putting the repository root on sys.path collides by name
only with docker, whose in-tree directory has no __init__.py, so the installed package
still wins.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A scripted 504 transport drives the pre-change flat-sleep loop to exhaustion in 12 s on every run, matching the production job log on PR #112205 (read timeout 10:06:15, four 504 retries 3 s apart, exhausted 10:06:27) to the second. Pure Python: no build, no server.
b Root cause explained? Yes. The retry loop slept a constant sleep regardless of failure class, so retries bounded the attempt count but not the time window. Five attempts times 3 s is a 12 s budget, shorter than a routine GitHub blip, so a transient 5xx exhausts it, APIException escapes, and upgrade_runner.sh prints Download script failed.
c Fix matches root cause? Yes. The delay grows with the attempt for the classes transient by definition (5xx, 429, transport errors), capped at 60 s, so the default window becomes 45 s. Terminal statuses keep the flat sleep. No assertion widened, no check disabled, no timeout bumped.
d Test intent preserved / new tests added? Yes. All 11 pre-existing cases survive the relocation, redistributed so policy cases drive GH.api_get and failover cases drive the shim; 7 new cases pin the seam the relocation creates (the RuntimeError to APIException translation, a success returned unchanged through the shim, raising rather than returning an empty value on exhaustion, the stdout contract below, the reset bound, a terminal 4xx keeping the flat sleep, and a bare 429 taking the backoff but no failover), and one was renamed when the diagnostic moved to stderr, for 18 functions and 29 collected cases. 14 mutation arms each redden exactly their named case over a green baseline; the reset-bound case caps its own fake transport so removing the guard fails fast rather than spinning.
e Both directions demonstrated? Yes. Same scripted transport: 12 s window without the fix, 45 s with it. Separately, the stdout of a retried read went from carrying two WARNING lines ahead of the tag to carrying the tag alone, and an always-accepting on_http_error went from over 200 sleepless requests to 6. 29 retry cases plus the pre-existing gh.py and download-helper cases pass.
f Fix is general across code paths? Yes at the intended layer. The policy now sits in praktika, where any job can reuse it, and all eight get_gh_api call sites inherit it through the shim. The only in-tree on_http_error and api_get caller is that shim, so the reset bound needs no caller changes. The retry diagnostic is the only print() in gh.py on a path whose stdout a caller parses; the other 36 are deliberately untouched. The other unauthenticated GitHub HTTP callers in tests/ci (ci_utils.py, github_helper.py) are enumerated and deliberately left out of scope for this PR.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Parametrized over 500/502/503/504/599, 401/422/499, a bare 429, 403 with three distinct bodies, 404 with and without a preset token, and both ConnectionError and ReadTimeout. The sleep=0 and retries=10 boundaries are pinned, and 499 pins the >= 500 threshold from below.
h Backward compatible? (maintainer-approved exception only) Yes, and there is no compatibility surface: no setting, no serialization format, no SettingsChangesHistory.cpp entry, no user-visible behaviour. All eight call sites keep their signature and exception class, and Settings.MAX_RETRIES_GH is untouched.
i Invariants and contracts preserved? Yes. get_gh_api still returns a requests.Response or raises APIException; the token failover still fires at most once and still grants exactly one fresh budget (retries + 1 attempts, re-verified unchanged); a caller's sleep=0 stays 0; the stdout of this read path carries only caller data, so a shell-captured release tag stays parseable across a retry; DOWNLOAD_RETRIES_COUNT and DOWNLOAD_RETRY_MAX_BACKOFF stay bound for download_build_with_progress; and the praktika import is guarded so importers needing only the download helpers keep working.

Session id: cron:clickhouse-impl-slot-7:20260811-095900

@groeneai

Copy link
Copy Markdown
Collaborator Author

Done, as you suggested: the retry policy is now GH.api_get in ci/praktika/gh.py, and
get_gh_api is a thin shim over it.

The failover has to stay in tests/ci, because get_robot_token imports boto3 and
PyGithub at module level and praktika must not depend on those. So the shim keeps its
signature, its APIException and the token failover, and drives the failover through an
on_http_error callback that restarts the attempt budget once. All eight call sites are
unchanged.

I checked the relocation is behaviour-preserving rather than assuming it: driving the old
and new implementations against 11 scripted scenarios gives identical attempt counts, sleep
sequences, auth-header sequences and exception classes everywhere except the three classes
this PR intends to change. In particular the 404 failover budget is retries + 1 = 6 in
both, so routing the reset through the callback reproduces the old try_cnt = 0.

Two test-liveness gaps disclosed at the previous round cap, both now closed and
each verified by a mutation that reddens only the new row.

The fake transport recorded a single boolean per attempt, so nothing proved that
caller options survive the shim's extra hop into `GH.api_get`. It now snapshots
every request. `test_caller_request_options_survive_delegation` asserts the two
live shapes -- `params` plus `timeout` from `get_previous_release_tag.py`, the
`Accept` header from `pr_info.py` -- and `test_failover_sends_the_fetched_token`
asserts the installed value is `Bearer fetched-token`, not merely that an
`Authorization` key appeared. Dropping `**kwargs` from the delegation reddens the
first; installing an empty bearer reddens the second, while the pre-existing
failover rows stay green, which is what made them blind to it.

`test_budget_resets_are_bounded` derived both its expected count and its ceiling
from `API_GET_MAX_BUDGET_RESETS`, so raising the constant moved the goalposts with
it. The bound is now a literal, and changing the constant to 2 reddens the row.

Dropped the `realpath` comment in the download helper: it attributed the path
requirement to a `/usr/bin` symlink, but `upgrade_runner.sh` symlinks only the two
entry scripts and this module is imported from its repository path, where
`abspath` and `realpath` agree.

Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112205&sha=66f93bffd6aa9d3b6f038bf7a6b59ac02a5b3f10&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29
PR: ClickHouse#112205
The job this fixes was filtered out by its own change. `upgrade_test_jobs`
digested the two entry scripts but not `tests/ci/build_download_helper.py`, which
both import at module level, nor `ci/praktika/gh.py`, which the helper now imports
for the retry policy. Measured against `Job.is_affected_by` with the four changed
paths: `Upgrade check (amd_release)` read False before, True after, and still
False for an unrelated `src/` change.

Strengthened the delegation oracle, which observed only the first successful
request: it now drives the shim through two retries with `sleep=0` and asserts the
params, timeout and `Accept` header on every attempt, plus the forwarded sleep
sequence. The failover row asserts the same across the budget restart. Dropping
`sleep=sleep` from the delegation reddens it, and so does clearing an option after
a failure.

Corrected the `api_get` docstring formula to `sleep * 2 ** (attempt - 1)`: attempt
1 uses exponent zero, which is what the pinned `[3, 6, 12, 24]` sequence shows.

Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112205&sha=66f93bffd6aa9d3b6f038bf7a6b59ac02a5b3f10&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29
PR: ClickHouse#112205
The failover row passed only `params` and inspected headers on the first
authenticated request, so losing an option, the bearer or the caller's sleep on a
later post-reset attempt stayed invisible. It now drives the persistent `404` with
the shapes the callers actually use (`sleep=0`, `params`, the diff `Accept` header,
`timeout=10`) and asserts all of them, plus the sleep sequence, on every attempt
after the reset. Clearing an option at the reset reddens it, and so does dropping
the bearer from the third attempt onward, while the pre-existing failover rows stay
green.

Corrected two comments that said `report.py` falls back to the run URL after
catching `APIException`: `GITHUB_JOB_ID` swallows it by default, so `GITHUB_JOB_URL`
returns an empty string without entering that branch. The invariant the test pins
is only that the class stays catchable at the existing caller boundary.

Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112205&sha=66f93bffd6aa9d3b6f038bf7a6b59ac02a5b3f10&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29
PR: ClickHouse#112205
@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebased on master (the conflict was one include_paths list: master's two CFI entries and
this branch's helper entry both kept).

The merge surfaced a real gap: Upgrade check, the job this fixes, digested the two entry
scripts but not build_download_helper.py or praktika/gh.py, which they import. Measured
with Job.is_affected_by on the four changed paths: False before, True after, still
False for an unrelated src/ change. So this change would have been filtered out of its
own target job. Both are now in the digest.

Also closed the two test-liveness gaps left at the previous round cap. The suite recorded
one boolean per request, so nothing proved caller options survive the extra hop into
GH.api_get; it now asserts params, timeout and the Accept header on every retried
attempt, across the failover reset, plus the forwarded sleep=0 and the actual bearer value.
The budget-reset bound is a literal instead of being derived from the constant it pins.

Each is backed by a mutation that reddens only the new row: dropping **kwargs or
sleep=sleep from the delegation, clearing an option at the reset, dropping the bearer after
the reset, and changing API_GET_MAX_BUDGET_RESETS to 2. 31 focused plus 65 sibling cases
pass.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a2f2fbb]

Summary: ✅


AI Review

Summary

The PR centralizes GitHub API read retries in GH.api_get, adds capped exponential backoff for transient failures, and includes the changed helpers in the Upgrade check digest. No actionable findings remain; 27 local scripted-response cases passed. The earlier inline digest finding was withdrawn and resolved because the cited package imports already existed through git_helper and clickhouse_version before this PR.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

I read Shell.run (ci/praktika/utils.py:314). Its retry does not carry the semantics this
path needs, on four counts:

  • The growth base is a hardcoded delay = 1 (:344) and the signature has no sleep
    parameter. Five of the eight get_gh_api call sites pass sleep=RETRY_SLEEP with
    RETRY_SLEEP = 0 (tests/ci/pr_info.py:78) precisely to get no sleep at all, which that
    loop cannot express.
  • Retry selection is retry_errors, substring matching on stderr lines. I need status
    classification instead: 5xx and 429 grow, a terminal 4xx keeps the flat sleep so it is not
    turned into a long wait.
  • on_retry's return value is discarded (:436), so it is a reporting hook. on_http_error
    has to be able to return True to restart the attempt budget, which is what drives the
    403-rate-limit/404 failover to the robot token.
  • It returns an exit code. Callers need the response object itself
    (get_previous_release_tag.py:74: .ok, .reason, .raise_for_status(), .json()).

Threading a callable through it would also bypass everything it exists for: the shell=True
Popen, the bash executable, the output-streaming threads, the process-group kill on timeout.

Your point about the duplication is right, though the closest copies are inside gh.py
itself: do_command_with_retries:302 and get_output_with_retries:349 both compute
min(2 ** (retry_count + 1), 60). A small shared backoff helper that those two and api_get
all call would remove it without routing HTTP through the subprocess path. That is a praktika
core change, so it is your call: want it in this PR, or separately?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Hi @leshikus, gentle ping - the open question is whether the shared backoff helper for gh.py's three retry loops should go in this PR or a separate one. Happy either way; it is a praktika core change so it is your call. Thanks.

@clickhouse-gh
clickhouse-gh Bot requested review from leshikus and maxknv September 26, 2026 01:11
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 15, 2026
Comment thread ci/defs/job_configs.py Resolved
groeneai and others added 2 commits October 15, 2026 19:46
…retry-v2

Resolves the conflict with ClickHouse#119166 in ci/praktika/gh.py: GH.api_get stays
in place before do_command_with_retries, which keeps master's new strict
parameter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
No CI job runs `ci/tests` since the `CI Tests` job was removed, and changes
to the CI infrastructure ship without tests of that infrastructure. The
31 scripted-response cases were run locally against this tree instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Oct 15, 2026
yariks5s pushed a commit to ylw510/ClickHouse that referenced this pull request Oct 23, 2026
`get_previous_release_tag` reads page 1 of the GitHub releases list and,
since ClickHouse#115228, refuses a page shorter than the 100 releases it asks for,
because choosing from or walking past a degraded page gave stale
baselines. It refused after a single request, though. GitHub sometimes
answers that request with HTTP 200 and `[]`, which `get_gh_api` returns
as a success (it retries only on HTTP errors), so one degraded answer
killed the job: on 2026-10-22, 14:58-15:32 UTC, `Upgrade check
(amd_release)` ended after about a minute with `Unknown job error` on 5
unrelated PRs. Probing the same URL returned `[]` on 4 of 19 requests,
each followed by a full page within 10-22 s; answers carry
`cache-control: s-maxage=60`, and one empty answer came from the edge
cache.

Retry a short first page up to 4 times, 60 s apart, so the cached answer
has expired before the next request, then raise the same
`ReleaseNotFoundException` as before. A full page still costs one request
and no wait. HTTP 5xx on the same request is left to ClickHouse#112974.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai manual approve Manual approve required to run CI pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants