From cda02bce9425b11000787f31963145ccf880dfe4 Mon Sep 17 00:00:00 2001 From: Dev Desai Date: Wed, 18 Nov 2026 13:25:12 -0500 Subject: [PATCH 1/4] fix: Add --forced to Kill Stale SSH (#254) * fix: hint `--force` in HTTP 429 error messages Both 429 variants (with and without session limit) now tell the user to retry with `--force` when a previous client died. * feat: add _killStaleSshd helper for force-reconnect Executes `pkill -P ` on the runtime kernel to kill stale per-connection sshd children left behind by a dead client, then waits 2s for the port to free. * feat: add --force flag to `colab ssh` Wires `--force` into all four ssh() code paths (cmd, proxy+cmd, proxy, interactive). When set, kills stale sshd children on the runtime before connecting, resolving HTTP 429 when a previous client died. Closes #242 * test: add --force flag tests for colab ssh Covers interactive mode, proxy mode, no-force skip, and both 429 message variants mentioning --force. * fix: prevent kernel leak in _killStaleSshd Pass kernel_id to ColabRuntime and call rt.stop() in a finally block so the websocket is always closed. Simplify the kernel snippet to os.system, unquote the type annotation, and move the sleep outside the try block. Update --force help text to reflect that all SSH sessions are killed, not only stale ones. * refactor: remove dead --force in proxy+cmd child path _proxy_command() never forwards --force, so force is always False in the hidden --colab-internal-mode cmd branch. * refactor: consolidate --force tests into parametrized test Replace three separate tests + a redundant 429 message test with one parametrized test covering interactive, proxy-mode, cmd, and no-force paths. Add a body-coverage test that asserts kernel_id is forwarded and rt.stop() is called. * fix: remove time.sleep(2) from _killStaleSshd --- src/colab_cli/commands/ssh.py | 40 ++++++++++++++++++++++-- tests/test_ssh.py | 58 ++++++++++++++++++++++++++++++++--- 2 files changed, 92 insertions(+), 6 deletions(-) diff --git a/src/colab_cli/commands/ssh.py b/src/colab_cli/commands/ssh.py index 8c71a0d0..55f9d3b6 100644 --- a/src/colab_cli/commands/ssh.py +++ b/src/colab_cli/commands/ssh.py @@ -331,13 +331,15 @@ def _explain_handshake_failure(status: Optional[int], body: bytes) -> str: message = ( f"SSH session limit reached (HTTP 429): {limit} of {limit} " "SSH sessions in use on this runtime. Close another " - "`colab ssh` or IDE connection to it and retry. The limit " + "`colab ssh` or IDE connection to it and retry. If the " + "previous client died, retry with `--force`. The limit " "depends on your Colab plan." ) case 429: message = ( "Already-active SSH session (HTTP 429): another `colab ssh` " - "is connected to this runtime. Disconnect it and retry." + "is connected to this runtime. Disconnect it and retry. " + "If the previous client died, retry with `--force`." ) case 502: message = ( @@ -405,6 +407,23 @@ def _close_quietly(ws: websocket.WebSocket) -> None: pass +def _killStaleSshd(session: SessionState) -> None: + """Kills existing SSH sessions on the runtime via the kernel.""" + from colab_cli.runtime import ColabRuntime + + typer.echo("[colab] --force: killing stale SSH sessions...", err=True) + rt = ColabRuntime(session.url, session.token, kernel_id=session.kernel_id) + try: + rt.execute_code( + "import os; os.system('pkill -P $(pgrep -o -x sshd)')", + timeout=10.0, + ) + except Exception as e: + typer.echo(f"[colab] --force: failed to kill sshd: {e}", err=True) + finally: + rt.stop() + + _DATA_OPCODES = (websocket.ABNF.OPCODE_BINARY, websocket.ABNF.OPCODE_TEXT) @@ -785,6 +804,17 @@ def ssh( ), ), ] = False, + force: Annotated[ + bool, + typer.Option( + "--force", + help=( + "Kill all existing SSH sessions on the runtime before " + "connecting. Use when a dead client causes HTTP 429 on " + "reconnect." + ), + ), + ] = False, ssh_mode: Annotated[ str, typer.Option("--colab-internal-mode", hidden=True) ] = _DEFAULT_SSH_MODE, @@ -812,6 +842,8 @@ def ssh( if cmd: with contextlib.redirect_stdout(sys.stderr): s = _resolve_session(session) + if force: + _killStaleSshd(s) _warn_accelerator_ignored(gpu, tpu, False, high_mem=high_mem) if rm: typer.echo("[colab] --rm ignored with -- CMD.", err=True) @@ -822,10 +854,14 @@ def ssh( raise typer.Exit(code=_run_proxy_bridge(s, identity, rm, ssh_mode)) if proxy_mode: s, created = _select_proxy_session(session, gpu, tpu, high_mem=high_mem) + if force: + _killStaleSshd(s) _warn_accelerator_ignored(gpu, tpu, created, high_mem=high_mem) raise typer.Exit(code=_run_proxy_bridge(s, identity, rm, ssh_mode)) s, created = _select_interactive_session(session, gpu, tpu, high_mem=high_mem) + if force: + _killStaleSshd(s) _warn_accelerator_ignored(gpu, tpu, created, high_mem=high_mem) raise typer.Exit(code=_run_interactive_shell(s, identity, created, rm)) diff --git a/tests/test_ssh.py b/tests/test_ssh.py index dea80273..5b959efb 100644 --- a/tests/test_ssh.py +++ b/tests/test_ssh.py @@ -225,23 +225,27 @@ def test_explain_handshake_failure_mapping(status, body, must_contain): _FALLBACK_429 = ( "Already-active SSH session (HTTP 429): another `colab ssh` is " - "connected to this runtime. Disconnect it and retry." + "connected to this runtime. Disconnect it and retry. " + "If the previous client died, retry with `--force`." ) _LIMIT_BODY_PREFIX = b'{"error":"already-active-session","limit":' _LIMIT_1_TEXT = ( "SSH session limit reached (HTTP 429): 1 of 1 SSH sessions in use on " "this runtime. Close another `colab ssh` or IDE connection to it and " - "retry. The limit depends on your Colab plan." + "retry. If the previous client died, retry with `--force`. " + "The limit depends on your Colab plan." ) _LIMIT_2_TEXT = ( "SSH session limit reached (HTTP 429): 2 of 2 SSH sessions in use on " "this runtime. Close another `colab ssh` or IDE connection to it and " - "retry. The limit depends on your Colab plan." + "retry. If the previous client died, retry with `--force`. " + "The limit depends on your Colab plan." ) _LIMIT_4_TEXT = ( "SSH session limit reached (HTTP 429): 4 of 4 SSH sessions in use on " "this runtime. Close another `colab ssh` or IDE connection to it and " - "retry. The limit depends on your Colab plan." + "retry. If the previous client died, retry with `--force`. " + "The limit depends on your Colab plan." ) @@ -656,3 +660,49 @@ def test_proxy_command_keeps_global_options( *[sys.executable, "-m", "colab_cli.cli", *global_args, "ssh"], *["--proxy-mode", "-s", "s", "--colab-internal-mode", "interactive"], ] + + +# --- --force flag ----------------------------------------------------------- + + +@pytest.mark.parametrize( + ("argv", "kills"), + [ + (["--force"], 1), + (["--proxy-mode", "--force"], 1), + (["--force", "--", "true"], 1), + ([], 0), + ], + ids=["interactive", "proxy-mode", "cmd", "no-force"], +) +def test_force_kills_stale_sshd(mock_common_state, mocker, argv, kills): + """--force calls _killStaleSshd; without it, the helper is skipped.""" + sess = _make_session() + mock_common_state.resolve_session.return_value = "s1" + mock_common_state.store.get.return_value = sess + mock_common_state.store.list.return_value = [sess] + + killSshd = mocker.patch.object(ssh_module, "_killStaleSshd") + mocker.patch.object(ssh_module, "_run_interactive_ssh", return_value=0) + mocker.patch.object(ssh_module, "_run_proxy_bridge", return_value=0) + mocker.patch.object(ssh_module, "_run_remote_command", return_value=0) + + result = runner.invoke(app, ["ssh", "-s", "s1", *argv]) + assert result.exit_code == 0 + assert killSshd.call_count == kills + + +def test_kill_stale_sshd_body(mock_common_state, mocker): + """_killStaleSshd passes kernel_id and calls rt.stop().""" + sess = _make_session() + sess.kernel_id = "k123" + mockRt = MagicMock() + mockRt.execute_code.return_value = [] + rtCls = mocker.patch("colab_cli.runtime.ColabRuntime", return_value=mockRt) + mocker.patch.object(ssh_module.time, "sleep") + + ssh_module._killStaleSshd(sess) + + rtCls.assert_called_once_with(sess.url, sess.token, kernel_id="k123") + mockRt.execute_code.assert_called_once() + mockRt.stop.assert_called_once() From 33610a03d598312e6f390ab27c12113696af87f6 Mon Sep 17 00:00:00 2001 From: lw <90660621+lw-liuwang@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:46:09 +0800 Subject: [PATCH 2/4] fix(examples): annotate imports after runtime dependency installation (#222) --- examples/finetune_run.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/examples/finetune_run.py b/examples/finetune_run.py index 21a80578..fc69cec9 100644 --- a/examples/finetune_run.py +++ b/examples/finetune_run.py @@ -30,13 +30,14 @@ import os +# Keep training-library imports after the runtime dependency installation. os.system("pip install -q -U 'bitsandbytes>=0.46.1'") -import torch -from datasets import load_dataset -from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig -from peft import LoraConfig, get_peft_model -from trl import SFTConfig, SFTTrainer +import torch # noqa: E402 +from datasets import load_dataset # noqa: E402 +from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig # noqa: E402 +from peft import LoraConfig, get_peft_model # noqa: E402 +from trl import SFTConfig, SFTTrainer # noqa: E402 MODEL_ID = "google/gemma-3-1b-it" NUM_SAMPLES = 200 # demo size; bump to 5000+ for a real run From aa01a39019ed6570c7496ec8ec5330daf1730b33 Mon Sep 17 00:00:00 2001 From: Yida Weng <84164537+YidaWeng@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:22:50 +0800 Subject: [PATCH 3/4] fix(drivemount): report propagation failures instead of dumping HTML (#212) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the Drive consent is approved for a Google account other than the one the CLI authenticated as, the propagation POST returns 400. The hook assumed every failure was an auth challenge, so it printed the raw response body (HTML), waited for the user to approve again, and retried forever. If the body was not JSON, parsing raised inside the websocket hook, which swallows the exception — leaving drive.mount() blocked until the 600s timeout. - Parse propagation responses defensively; HTML, plain text, empty and non-object bodies become an empty dict instead of raising. - Only show the consent prompt when the server returns an `unauthorized_redirect_uri`; other failures are reported directly. - Never echo the raw body. Print the status, a short server detail when present, and the multi-account guidance (select the account from `colab whoami`); log the body to the history file. - Answer the intercepted kernel request on failure too, so the command exits promptly rather than hanging. Co-authored-by: Seth Troisi --- docs/04_automation_and_utility.md | 11 ++ src/colab_cli/commands/automation.py | 112 +++++++++++++++--- tests/test_automation.py | 167 ++++++++++++++++++++++++++- 3 files changed, 273 insertions(+), 17 deletions(-) diff --git a/docs/04_automation_and_utility.md b/docs/04_automation_and_utility.md index 5297390c..8a9637a5 100644 --- a/docs/04_automation_and_utility.md +++ b/docs/04_automation_and_utility.md @@ -3,6 +3,7 @@ log: 2026-11-13: `_get_adc_credentials` in `auth.py` now catches `DefaultCredentialsError` from `google.auth.default()` so missing local ADC prints the 4-scope `gcloud auth application-default login` command and exits 1 instead of surfacing `google-auth`'s stock unscoped setup message. Updated scope documentation to clarify that both `colaboratory` and `userinfo.email` are required by `colab.research.google.com`. 2026-11-07: Optimized `_get_adc_credentials` in `auth.py` to stub `google.auth._cloud_sdk.get_project_id` around `google.auth.default()`. When ADC user credentials lack a `quota_project_id`, `google-auth` otherwise spawns `gcloud config get-value project` on every CLI invocation to resolve a `project_id` that `_get_adc_credentials` immediately discards (`_`). 2026-11-04: `colab drivemount` now opens the Drive consent URL in the system browser (`utils.open_url_in_browser`, also used by `colab pay`/`colab url --open`) instead of only printing it. The URL is still printed first, and a missing browser opener (SSH, containers, CI) is treated as normal: the flow keeps waiting for the user exactly as before. The prompt moved into `commands/automation.py::show_drive_auth_url` so it can be unit-tested. +2026-11-04: `colab drivemount` now handles credentials-propagation failures instead of dumping the HTTP body. Responses are parsed defensively (HTML/empty bodies no longer raise out of the websocket hook), an authentication prompt is only shown when the server actually returns an `unauthorized_redirect_uri`, and failures print the status plus the multi-account guidance (select the account from `colab whoami`) while logging the raw body to history. The intercepted kernel request is answered on failure too, so the command exits promptly instead of hanging until its 600s timeout. 2026-11-02: Added `_check_linux_keyring_locked` in `auth.py` to inspect the active Linux `SecretService` collection via `secretstorage` before `get_password`/`set_password`, warning immediately when the keyring is locked so users know why the CLI is waiting on an unlock prompt (and suggesting `--auth=adc`). 2026-10-29: Session history files are created readable only by the owner (0600), and existing ones are tightened to 0600 whenever the history logger starts. 2026-10-22: Added hidden `colab test-public-api` subcommand and `Client.check_api_access()` to probe both `colaboratory.googleapis.com/v1beta/runtimes` and `colab.research.google.com/tun/m/assignments`, caching `public_api_supported` and `tunnel_api_supported` in `Settings` for targeted HTTP 401/403 error hints. @@ -146,6 +147,16 @@ How each provider supplies the scopes: `jupyter_kernel_client` default raising `TimeoutError` mid-flow, this subcommand passes `timeout=INTERACTIVE_AUTOMATION_TIMEOUT_SEC` (600s) to `ColabRuntime.execute_code`. Same applies to `colab auth`. +- **Multi-account browsers**: Drive propagation is attributed to the Google + account that approves the consent page, which may not be the account the + CLI authenticated as. If the browser shows an account chooser, select the + account reported by `colab whoami`; approving with another account fails + with HTTP 400 even though the consent itself succeeded. A private window + only helps if it is already signed in to that account. +- **Failure reporting**: errors from the propagation endpoint never echo the + raw response body (often HTML). The CLI prints the status, points at + `colab whoami`, logs the body to the history file, and answers the waiting + kernel request so `drivemount` exits instead of hanging until its timeout. ### 4. Logging and Notebook Capture (`colab log`) diff --git a/src/colab_cli/commands/automation.py b/src/colab_cli/commands/automation.py index 00f89e8b..4261365f 100644 --- a/src/colab_cli/commands/automation.py +++ b/src/colab_cli/commands/automation.py @@ -38,6 +38,69 @@ INTERACTIVE_AUTOMATION_TIMEOUT_SEC = 600 +def _parse_propagation_response(resp) -> dict: + """Extract the JSON payload from a credentials-propagation response. + + Successful bodies are ``\\n{json}``. Failures can return HTML, a + plain-text reason, or an empty body — none of those should raise, because + the exception would escape the websocket hook and leave the kernel waiting. + """ + text = getattr(resp, "text", "") or "" + for candidate in (text, text.split("\n", 1)[-1], text.rsplit("\n", 1)[-1]): + candidate = candidate.strip() + if not candidate: + continue + try: + data = json.loads(candidate) + except ValueError: + continue + if isinstance(data, dict): + return data + return {} + + +def drive_propagation_failure_message(status: Optional[int], data: dict) -> str: + """Actionable text for a failed Drive credential propagation. + + The usual cause is a browser that approved Drive access for a different + Google account than the one the CLI authenticated as. The raw response + body (often HTML) is never echoed; it goes to the history log instead. + """ + headline = "[colab] Drive credentials could not be propagated" + if status is not None and status != 200: + headline += f" (HTTP {status})" + lines = [headline + "."] + detail = data.get("error") or data.get("message") + if isinstance(detail, str) and detail.strip(): + lines.append(f"[colab] Server said: {detail.strip()[:300]}") + lines.append("[colab] If the browser showed an account chooser, re-run the command") + lines.append("[colab] and select the account reported by `colab whoami`. Approving") + lines.append( + "[colab] Drive access as a different Google account makes propagation fail" + ) + lines.append("[colab] even though the consent itself succeeded.") + return "\n".join(lines) + + +def _report_propagation_failure(history, session_name, status, body, data) -> None: + typer.echo(drive_propagation_failure_message(status, data)) + history.log_event( + session_name, + "drive_auth_failed", + {"status": status, "body": (body or "")[:2000]}, + ) + + +def _send_colab_reply(wsclient, deserialize_msg, msg_id) -> None: + """Answer the intercepted request so the kernel stops waiting.""" + reply = wsclient.session.msg( + "input_reply", + {"value": {"type": "colab_reply", "colab_msg_id": msg_id}}, + ) + if "header" in deserialize_msg: + reply["parent_header"] = deserialize_msg["header"] + wsclient.stdin_channel.send(reply) + def show_drive_auth_url(uri: str) -> bool: """Print the Drive consent URL and try to open it in the browser. @@ -92,11 +155,14 @@ def drivefs_hook(deserialize_msg, wsclient): state.client_oauth_config, provider=state.auth_provider ) resp = creds.request("GET", url, params=params) - token = ( - json.loads(resp.text.split("\n", 1)[-1]).get("token") - if get_status_code(resp) == 200 - else None - ) + data = _parse_propagation_response(resp) + token = data.get("token") if get_status_code(resp) == 200 else None + if not token: + _report_propagation_failure( + state.history, s.name, get_status_code(resp), resp.text, data + ) + _send_colab_reply(wsclient, deserialize_msg, msg_id) + return True headers = {"x-goog-colab-token": token} resp = creds.request( @@ -106,10 +172,25 @@ def drivefs_hook(deserialize_msg, wsclient): headers=headers, files={"file_id": (None, "empty.ipynb")}, ) - data = json.loads(resp.text.split("\n", 1)[-1]) + data = _parse_propagation_response(resp) if not data.get("success"): uri = data.get("unauthorized_redirect_uri") + if not uri: + # A failure that is not an auth challenge cannot be fixed + # by approving again; report it instead of looping. + _report_propagation_failure( + state.history, + s.name, + get_status_code(resp), + resp.text, + data, + ) + _send_colab_reply(wsclient, deserialize_msg, msg_id) + return True + typer.echo( + f"\n[colab] REQUIRED: Google Drive Authorization needed.\nPlease visit:\n\n{uri}\n" + ) show_drive_auth_url(uri) state.history.log_event(s.name, "drive_auth_needed", {"uri": uri}) sys.stdout.write("Press Enter after you have granted access... ") @@ -136,20 +217,19 @@ def drivefs_hook(deserialize_msg, wsclient): headers=headers, files={"file_id": (None, "empty.ipynb")}, ) - if get_status_code(resp) == 200: + status = get_status_code(resp) + if status == 200: typer.echo("[colab] Credentials propagated. Resuming mount...") state.history.log_event(s.name, "drive_auth_success", {}) - reply = wsclient.session.msg( - "input_reply", - {"value": {"type": "colab_reply", "colab_msg_id": msg_id}}, - ) - if "header" in deserialize_msg: - reply["parent_header"] = deserialize_msg["header"] - wsclient.stdin_channel.send(reply) else: - typer.echo( - f"[colab] Error propagating: {get_status_code(resp)} {resp.text}" + _report_propagation_failure( + state.history, + s.name, + status, + resp.text, + _parse_propagation_response(resp), ) + _send_colab_reply(wsclient, deserialize_msg, msg_id) return True return False diff --git a/tests/test_automation.py b/tests/test_automation.py index 16df7dab..34ac2b7a 100644 --- a/tests/test_automation.py +++ b/tests/test_automation.py @@ -12,16 +12,28 @@ # See the License for the specific language governing permissions and # limitations under the License. -from unittest.mock import patch +from unittest.mock import MagicMock, mock_open, patch import pytest from typer.testing import CliRunner from colab_cli.cli import app +from colab_cli.commands.automation import ( + _parse_propagation_response, + drive_propagation_failure_message, +) from colab_cli.commands.automation import show_drive_auth_url from colab_cli.state import SessionState runner = CliRunner() +class _FakeResponse: + """Minimal stand-in for the requests.Response returned by creds.request.""" + + def __init__(self, text, status_code=200): + self.text = text + self.status_code = status_code + + @pytest.fixture def mock_session(): return SessionState( @@ -126,6 +138,159 @@ def test_cli_auth_uses_long_timeout(mock_state, mock_runtime_class, mock_session assert kwargs.get("timeout") is not None and kwargs["timeout"] >= 300 +def _drive_request(msg_id="m1"): + return { + "content": {"request": {"authType": "dfs_ephemeral"}}, + "metadata": {"colab_msg_id": msg_id}, + } + + +@pytest.mark.parametrize( + "body", + [ + '{"success": true, "token": "tok"}', + 'prefix\n{"success": true, "token": "tok"}', + 'rendered\nprefix\n{"success": true, "token": "tok"}', + ], +) +def test_parse_propagation_response_reads_json(body): + assert _parse_propagation_response(_FakeResponse(body))["token"] == "tok" + + +@pytest.mark.parametrize( + "body", + ["", "400 Bad Request", "not json", "null", "[1, 2]"], +) +def test_parse_propagation_response_never_raises(body): + """Error bodies are often HTML; parsing must degrade to an empty dict.""" + assert _parse_propagation_response(_FakeResponse(body)) == {} + + +def test_drive_propagation_failure_message_is_actionable(): + message = drive_propagation_failure_message(400, {}) + + assert "HTTP 400" in message + assert "colab whoami" in message + assert "different Google account" in message + assert "400 Bad Request", status_code=400), + ] + wsclient = MagicMock() + wsclient.session.msg.return_value = {} + + with patch("builtins.open", mock_open(read_data="\n")): + hook(_drive_request(), wsclient) + + out = capsys.readouterr().out + assert "HTTP 400" in out + assert "colab whoami" in out + assert " Date: Wed, 18 Nov 2026 21:42:32 -0800 Subject: [PATCH 4/4] build: cleanup after #212 and #254 (#259) --- src/colab_cli/commands/automation.py | 4 +--- src/colab_cli/commands/session.py | 1 - tests/test_ssh.py | 1 - 3 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/colab_cli/commands/automation.py b/src/colab_cli/commands/automation.py index 4261365f..cd1e464b 100644 --- a/src/colab_cli/commands/automation.py +++ b/src/colab_cli/commands/automation.py @@ -101,6 +101,7 @@ def _send_colab_reply(wsclient, deserialize_msg, msg_id) -> None: reply["parent_header"] = deserialize_msg["header"] wsclient.stdin_channel.send(reply) + def show_drive_auth_url(uri: str) -> bool: """Print the Drive consent URL and try to open it in the browser. @@ -188,9 +189,6 @@ def drivefs_hook(deserialize_msg, wsclient): ) _send_colab_reply(wsclient, deserialize_msg, msg_id) return True - typer.echo( - f"\n[colab] REQUIRED: Google Drive Authorization needed.\nPlease visit:\n\n{uri}\n" - ) show_drive_auth_url(uri) state.history.log_event(s.name, "drive_auth_needed", {"uri": uri}) sys.stdout.write("Press Enter after you have granted access... ") diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index dc994f34..2ee50b86 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -397,4 +397,3 @@ def register(app: typer.Typer): app.command(name="restart-kernel")(restart_kernel) app.command()(status) app.command()(stop) - diff --git a/tests/test_ssh.py b/tests/test_ssh.py index 5b959efb..1c57e5ea 100644 --- a/tests/test_ssh.py +++ b/tests/test_ssh.py @@ -699,7 +699,6 @@ def test_kill_stale_sshd_body(mock_common_state, mocker): mockRt = MagicMock() mockRt.execute_code.return_value = [] rtCls = mocker.patch("colab_cli.runtime.ColabRuntime", return_value=mockRt) - mocker.patch.object(ssh_module.time, "sleep") ssh_module._killStaleSshd(sess)