Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion .github/workflows/odh-deploy-contract.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,21 @@ jobs:
with:
python-version: "3.12"

# Keep this version aligned with mise.toml. This workflow stays lean and
# installs only uv instead of bootstrapping the full mise toolchain.
- uses: astral-sh/setup-uv@ae62891fec2bb8e7d6c99fc78c9fec3a63790f8d # v10.0.0
with:
version: "0.10.12"

- name: Run the deploy digest contract suite
run: bash odh/scripts/tests/test-openshell-deploy-from-quay.sh

- name: Verify generic-fetcher synchronization
env:
# Keep pytest on the Python version installed above instead of
# resolving the repository-wide development interpreter.
UV_PYTHON: ${{ env.pythonLocation }}/bin/python
run: |
python3 deploy/konflux/e2e-odh/sync-generic-fetcher.py --check
python3 deploy/konflux/e2e-odh/sync-generic-fetcher_test.py
# Keep this invocation in sync with test:odh-generic-fetcher in tasks/test-odh.toml.
uv run --no-project --with "pytest==9.0.3" --with "pytest-asyncio==1.3.0" pytest -o "python_files=*_test.py" deploy/konflux/e2e-odh/
31 changes: 26 additions & 5 deletions deploy/konflux/e2e-odh/sync-generic-fetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,25 @@ def check(versions: dict[str, str], artifacts: list[Artifact]) -> list[str]:


RETRY_ATTEMPTS = 3
MAX_RETRY_AFTER_SECONDS = 60


def retry_delay(retry_after: str | None, attempt: int) -> tuple[int, str | None]:
"""Return a bounded delay and the requested value when it was capped."""
fallback_delay = 2 ** (attempt - 1)
if not retry_after or not retry_after.isascii() or not retry_after.isdecimal():
Comment thread
gmenher marked this conversation as resolved.
Resolved

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor: retry_delay still rejects padded values itself (" 60".isdecimal() is False); only _with_retry strips, at line 250, so the helper depends on caller hygiene. Moving the .strip() into retry_delay makes it self-contained for any future direct caller.

return fallback_delay, None

significant_digits = retry_after.lstrip("0")
# Avoid converting an unbounded value supplied by a remote server, while
# retaining a useful exact value in the retry log for normal headers.
if len(significant_digits) > 10:
return MAX_RETRY_AFTER_SECONDS, f"more than {MAX_RETRY_AFTER_SECONDS}s"

requested_delay = int(significant_digits or "0")
if requested_delay > MAX_RETRY_AFTER_SECONDS:
return MAX_RETRY_AFTER_SECONDS, f"{requested_delay}s"
return requested_delay, None


def _with_retry(url: str, consume, what: str):
Expand Down Expand Up @@ -228,14 +247,16 @@ def _with_retry(url: str, consume, what: str):
if isinstance(last_error, urllib.error.HTTPError)
else None
)
delay = (
int(retry_after)
if retry_after and retry_after.isdigit()
else 2 ** (attempt - 1)
retry_after = retry_after.strip() if retry_after else None
delay, capped_retry_after = retry_delay(retry_after, attempt)
cap_note = (
f"; server Retry-After was {capped_retry_after}"
if capped_retry_after is not None
else ""
)
print(
f"{url}: {last_error}; attempt {attempt}/{RETRY_ATTEMPTS} failed "
f"while {what}, retrying in {delay}s",
f"while {what}, retrying in {delay}s{cap_note}",
file=sys.stderr,
)
time.sleep(delay)
Expand Down
135 changes: 109 additions & 26 deletions deploy/konflux/e2e-odh/sync-generic-fetcher_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@

import hashlib
import importlib.util
import io
import sys
import unittest
from contextlib import redirect_stderr
from email.message import Message
from pathlib import Path
from unittest.mock import patch
from unittest.mock import call, patch
from urllib.error import HTTPError


Expand Down Expand Up @@ -58,47 +60,128 @@ def open(self, _url: str, timeout: int):
return response


def _rate_limited(retry_after: str | None = None) -> HTTPError:
headers = Message()
if retry_after is not None:
headers["Retry-After"] = retry_after
return HTTPError(
"https://example.test/artifact", 429, "rate limited", headers, None
)


def _sha256_with_responses(responses: list[_Response | Exception]):
opener = _Opener(responses)
with (
patch.object(
sync_generic_fetcher.urllib.request,
"build_opener",
return_value=opener,
),
patch.object(sync_generic_fetcher.time, "sleep") as sleep,
):
checksum = sync_generic_fetcher.sha256_of("https://example.test/artifact")
return checksum, sleep


class SyncGenericFetcherTests(unittest.TestCase):
def test_sha256_of_retries_with_a_fresh_hash(self) -> None:
complete = b"the complete retry response"
opener = _Opener(
checksum, _ = _sha256_with_responses(
[
_Response([b"partial first response", OSError("interrupted")]),
_Response([complete, b""]),
]
)
with (
patch.object(
sync_generic_fetcher.urllib.request,
"build_opener",
return_value=opener,
),
patch.object(sync_generic_fetcher.time, "sleep"),
):
checksum = sync_generic_fetcher.sha256_of("https://example.test/artifact")

self.assertEqual(checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}")

def test_retry_after_is_honored_for_rate_limiting(self) -> None:
Comment thread
gmenher marked this conversation as resolved.
Resolved
headers = Message()
headers["Retry-After"] = "7"
rate_limited = HTTPError(
"https://example.test/artifact", 429, "rate limited", headers, None
for retry_after, expected_delay in (
("0", 0),
("00", 0),
("007", 7),
("7", 7),
("10", 10),
("60", 60),
("60 ", 60),
("0" * 10_000 + "7", 7),
):
with self.subTest(retry_after=retry_after[:8]):
complete = b"complete retry response"
checksum, sleep = _sha256_with_responses(
[_rate_limited(retry_after), _Response([complete, b""])]
)

self.assertEqual(
checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}"
)
sleep.assert_called_once_with(expected_delay)

def test_retry_after_is_capped_for_rate_limiting(self) -> None:
Comment thread
gmenher marked this conversation as resolved.
Resolved
for retry_after in ("61", "3600", "9" * 10_000):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor: The over-long-header branch's cap note (more than 60s) has no stderr assertion: this subtest checks only sleep(60), and the log test further down asserts only the 3600s wording, so a regression in that branch's message or tuple shape ships undetected.

with self.subTest(retry_after=retry_after[:4]):
complete = b"complete retry response"
checksum, sleep = _sha256_with_responses(
[_rate_limited(retry_after), _Response([complete, b""])]
)

self.assertEqual(
checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}"
)
sleep.assert_called_once_with(60)

def test_retry_after_falls_back_to_exponential_backoff_when_invalid(self) -> None:
for retry_after in (None, "later", "²", "\N{ARABIC-INDIC DIGIT SEVEN}"):
with self.subTest(retry_after=retry_after):
complete = b"complete retry response"
checksum, sleep = _sha256_with_responses(
[_rate_limited(retry_after), _Response([complete, b""])]
)

self.assertEqual(
checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}"
)
sleep.assert_called_once_with(1)

def test_retry_after_fallback_doubles_on_consecutive_retries(self) -> None:
complete = b"complete retry response"
checksum, sleep = _sha256_with_responses(
[_rate_limited(), _rate_limited(), _Response([complete, b""])]
)

self.assertEqual(checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}")
self.assertEqual(sleep.call_args_list, [call(1), call(2)])

def test_retry_after_invalid_fallback_doubles_on_consecutive_retries(self) -> None:
complete = b"complete retry response"
opener = _Opener([rate_limited, _Response([complete, b""])])
with (
patch.object(
sync_generic_fetcher.urllib.request,
"build_opener",
return_value=opener,
),
patch.object(sync_generic_fetcher.time, "sleep") as sleep,
):
checksum = sync_generic_fetcher.sha256_of("https://example.test/artifact")
checksum, sleep = _sha256_with_responses(
[_rate_limited("later"), _rate_limited("later"), _Response([complete, b""])]
)

self.assertEqual(checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}")
self.assertEqual(sleep.call_args_list, [call(1), call(2)])

def test_retry_after_is_honored_after_a_fallback_retry(self) -> None:
complete = b"complete retry response"
checksum, sleep = _sha256_with_responses(
[_rate_limited(), _rate_limited("7"), _Response([complete, b""])]
)

self.assertEqual(checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}")
sleep.assert_called_once_with(7)
self.assertEqual(sleep.call_args_list, [call(1), call(7)])

def test_capped_retry_after_reports_the_requested_delay(self) -> None:
complete = b"complete retry response"
stderr = io.StringIO()
with redirect_stderr(stderr):
_, sleep = _sha256_with_responses(
[_rate_limited("3600"), _Response([complete, b""])]
)

sleep.assert_called_once_with(60)
self.assertIn(
"retrying in 60s; server Retry-After was 3600s", stderr.getvalue()
)

def test_published_checksum_requires_the_sidecar_asset_name(self) -> None:
with (
Expand Down
3 changes: 2 additions & 1 deletion tasks/test-odh.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,6 @@ hide = true

["test:odh-generic-fetcher"]
description = "Test ODH generic-fetcher checksum synchronization"
run = "python3 deploy/konflux/e2e-odh/sync-generic-fetcher_test.py"
# Keep this invocation in sync with odh-deploy-contract.yml.
run = "uv run --no-project --with \"pytest==9.0.3\" --with \"pytest-asyncio==1.3.0\" pytest -o \"python_files=*_test.py\" deploy/konflux/e2e-odh/"
hide = true
Loading