Skip to content

[rhoai-3.5] fix(tests): bound exposing_contextmanager's portforward retry loop - #2692

Open
jiridanek wants to merge 1 commit into
rhoai-3.5from
fix/rhoai-3.5-socket-proxy-bounded-remote-timeout
Open

[rhoai-3.5] fix(tests): bound exposing_contextmanager's portforward retry loop#2692
jiridanek wants to merge 1 commit into
rhoai-3.5from
fix/rhoai-3.5-socket-proxy-bounded-remote-timeout

Conversation

@jiridanek

@jiridanek jiridanek commented Aug 2, 2026

Copy link
Copy Markdown
Member

Summary

Implements "Fix #2" from the suggested (not-yet-implemented) hardening ideas in
#2684: bound
exposing_contextmanager()'s kubernetes.stream.portforward() retry loop in
tests/containers/kubernetes_utils.py.

Why

exposing_contextmanager() retried portforward() in a
while not pf or not pf.connected or not s: loop with no deadline and no give-up
condition
. Verified via the kubernetes client library source that the underlying
websocket.connect(...) call has no per-call timeout plumbed through portforward()'s
public API -- a single iteration can, in principle, hang forever (e.g. a wedged
connection to the API server), not just retry quickly.

Because SocketProxy.listen_and_serve_until_canceled() handles one client
synchronously, a stuck call here blocks the entire proxy -- no other Wait.until
retry can ever be serviced again for that pod, with no way to recover.

Changes

  • exposing_contextmanager() gains a timeout: float = 30 parameter. Once exceeded,
    cleans up any partial s/pf and raises TimeoutError.
  • The deadline check alone only runs between retry loop iterations, so a single
    portforward() call that itself hangs would never let it fire again -- added
    _portforward_with_timeout(), which runs that specific call in a daemon thread
    bounded by join(timeout). On timeout the call is abandoned (thread/connection
    leaked for the remainder of the test process) rather than joined; deliberately not
    using a process-wide websocket.setdefaulttimeout() since multiple SocketProxy
    instances (one per ImageDeployment) can call portforward() concurrently from
    different threads.
  • SocketProxy.listen_and_serve_until_canceled() now also catches the new
    TimeoutError alongside the existing BrokenPipeError/ConnectionResetError, so
    the proxy gives up on just that one connection and keeps serving future retries.

This is a mechanical, identical port of
red-hat-data-services/notebooks#2691
(rhoai-2.25) and opendatahub-io/notebooks#4273
(main) -- rhoai-3.5's tests/containers/kubernetes_utils.py/socket_proxy.py
were confirmed byte-identical to main's pre-change state (modulo one unrelated
logging.basicConfig line), where this was already implemented and CI-verified,
including a CodeRabbit review catching a real gap in the first iteration (the
single-hung-call issue this PR's _portforward_with_timeout() addresses).

Verification

exposing_contextmanager() retried kubernetes.stream.portforward() forever with
no deadline and no give-up condition. Because SocketProxy handles one client
synchronously, a single stuck iteration (e.g. a wedged connection to the API
server -- the kubernetes client doesn't expose a per-call connect timeout for
portforward()) blocks the entire proxy, starving every later Wait.until retry
with no way to recover.

Add a bounded deadline (default 30s) that raises TimeoutError once exceeded,
and catch it in SocketProxy.listen_and_serve_until_canceled() alongside the
existing BrokenPipeError/ConnectionResetError handling so the proxy gives up
on just that one connection and keeps serving future retries instead of the
exception escaping to the outer handler and killing the whole proxy thread.

The deadline check alone only runs between retry loop iterations, so a single
portforward() call that itself hangs would never let it fire again -- bound
that specific call too via a new _portforward_with_timeout() helper, which
runs it in a daemon thread bounded by join(timeout). On timeout the call is
abandoned (thread/connection leaked for the remainder of the test process)
rather than joined; deliberately not using a process-wide
websocket.setdefaulttimeout() since multiple SocketProxy instances can call
portforward() concurrently from different threads.

Straight port of #2691 (rhoai-2.25) and
opendatahub-io#4273 (main), where this was implemented and
CI-verified first.

#2684
@openshift-ci
openshift-ci Bot requested review from ayush17 and ysok August 2, 2026 21:04
@openshift-ci

openshift-ci Bot commented Aug 2, 2026

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign ysok for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@coderabbitai

coderabbitai Bot commented Aug 2, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Kubernetes port forwarding now has per-attempt and overall deadlines. Resource cleanup occurs when the deadline expires. Socket proxy retry handling now includes TimeoutError.

Changes

Kubernetes timeout handling

Layer / File(s) Summary
Port-forward deadline enforcement
tests/containers/kubernetes_utils.py
_portforward_with_timeout bounds port-forward setup and propagates errors. exposing_contextmanager enforces an overall deadline, limits retries, and closes resources on timeout.
Socket proxy timeout retries
tests/containers/socket_proxy.py
listen_and_serve_until_canceled catches TimeoutError and logs the retry while preserving existing connection-error handling.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: ysok

Sequence Diagram(s)

sequenceDiagram
  participant exposing_contextmanager
  participant _portforward_with_timeout
  participant kubernetes_stream
  participant listen_and_serve_until_canceled
  exposing_contextmanager->>_portforward_with_timeout: request port-forward with remaining timeout
  _portforward_with_timeout->>kubernetes_stream: start portforward()
  kubernetes_stream-->>_portforward_with_timeout: port-forward or TimeoutError
  _portforward_with_timeout-->>exposing_contextmanager: return handle or raise error
  listen_and_serve_until_canceled-->>listen_and_serve_until_canceled: log timeout and retry
Loading
🚥 Pre-merge checks | ✅ 5 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Branch Prefix Policy ⚠️ Warning Base branch is rhoai-3.5, but the observed title fix(tests): bound exposing_contextmanager's portforward retry loop lacks the required prefix. Rename the title to [rhoai-3.5] fix(tests): bound exposing_contextmanager's portforward retry loop.
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The linked issue has no coding requirements, and the PR implements the stated synchronization and port-forward timeout changes without conflict.
Out of Scope Changes check ✅ Passed The changes are limited to bounding Kubernetes port-forward retries and handling the resulting timeout in the socket proxy.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly describes the port-forward retry change, uses imperative mood, and has no trailing period.
Description check ✅ Passed The description clearly explains the change, rationale, limitations, and testing, although it omits the repository checklist sections.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/rhoai-3.5-socket-proxy-bounded-remote-timeout
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch fix/rhoai-3.5-socket-proxy-bounded-remote-timeout

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown

CI status [antigravity]

Run: Build Notebooks (pr) #307670607903/3 complete · 1 passed · 2 skipped
Last updated: 2026-08-02T21:05:10Z

No workbench image jobs ran; all matrix jobs were skipped.

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown

📋 Review Summary

This PR correctly implements a robustness fix by bounding the kubernetes.stream.portforward() retry loop in exposing_contextmanager() with a wall-clock timeout and a dedicated daemon-threaded execution helper, preventing indefinite blocking of the SocketProxy.

🔍 General Feedback

  • The implementation matches established ports in other branches (main and rhoai-2.25) and is clean, well-tested via static analysis, and properly handles cleanup on timeout.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/containers/kubernetes_utils.py`:
- Around line 526-543: Update the retry loop around _portforward_with_timeout
and pf.socket(8888) so socket creation failures close the newly assigned pf
before propagating the exception. Preserve the existing retry cleanup and
timeout behavior for successful socket creation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Repository UI (inherited), Organization UI (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: 102fc22e-024e-4409-9175-0c7e4acd2f11

📥 Commits

Reviewing files that changed from the base of the PR and between 7ff8530 and 73c2865.

📒 Files selected for processing (2)
  • tests/containers/kubernetes_utils.py
  • tests/containers/socket_proxy.py

Comment on lines +526 to 543
deadline = time.monotonic() + timeout
pf: kubernetes.stream.ws_client.PortForward | None = None
s = None
while not pf or not pf.connected or not s:
remaining = deadline - time.monotonic()
if remaining <= 0:
if s is not None:
s.close()
if pf is not None:
pf.close()
raise TimeoutError(f"Failed to establish a working portforward to {pod.metadata.name} within {timeout}s")
if s is not None:
s.close()
s = None
if pf is not None:
pf.close()
pf = kubernetes.stream.portforward(
api_method=core_v1_api.connect_get_namespaced_pod_portforward,
name=pod.metadata.name,
namespace=pod.metadata.namespace,
ports=",".join(str(p) for p in [8888]),
)
pf = _portforward_with_timeout(core_v1_api, pod, remaining)
s = pf.socket(8888)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Close pf if pf.socket(8888) fails.

This loop closes the previous pf/s before every retry and on deadline expiry, but not if pf.socket(8888) itself raises right after a successful _portforward_with_timeout() call. In that case, the exception propagates out of the generator immediately, before the next iteration's cleanup or the try/finally around yield can run. The newly created pf (and its underlying websocket) leaks for the rest of the test process.

Wrap the socket creation so failure closes pf first.

🔧 Proposed fix
         pf = _portforward_with_timeout(core_v1_api, pod, remaining)
-        s = pf.socket(8888)
+        try:
+            s = pf.socket(8888)
+        except Exception:
+            pf.close()
+            raise
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
deadline = time.monotonic() + timeout
pf: kubernetes.stream.ws_client.PortForward | None = None
s = None
while not pf or not pf.connected or not s:
remaining = deadline - time.monotonic()
if remaining <= 0:
if s is not None:
s.close()
if pf is not None:
pf.close()
raise TimeoutError(f"Failed to establish a working portforward to {pod.metadata.name} within {timeout}s")
if s is not None:
s.close()
s = None
if pf is not None:
pf.close()
pf = kubernetes.stream.portforward(
api_method=core_v1_api.connect_get_namespaced_pod_portforward,
name=pod.metadata.name,
namespace=pod.metadata.namespace,
ports=",".join(str(p) for p in [8888]),
)
pf = _portforward_with_timeout(core_v1_api, pod, remaining)
s = pf.socket(8888)
deadline = time.monotonic() + timeout
pf: kubernetes.stream.ws_client.PortForward | None = None
s = None
while not pf or not pf.connected or not s:
remaining = deadline - time.monotonic()
if remaining <= 0:
if s is not None:
s.close()
if pf is not None:
pf.close()
raise TimeoutError(f"Failed to establish a working portforward to {pod.metadata.name} within {timeout}s")
if s is not None:
s.close()
s = None
if pf is not None:
pf.close()
pf = _portforward_with_timeout(core_v1_api, pod, remaining)
try:
s = pf.socket(8888)
except Exception:
pf.close()
raise
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/containers/kubernetes_utils.py` around lines 526 - 543, Update the
retry loop around _portforward_with_timeout and pf.socket(8888) so socket
creation failures close the newly assigned pf before propagating the exception.
Preserve the existing retry cleanup and timeout behavior for successful socket
creation.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant