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
11 changes: 11 additions & 0 deletions docs/compute/runner.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,17 @@ startup script, and the runner starts within a minute of the rental. `authorized
(`VAST_TCP_PORT_22`), which is what the job page shows; Vast's own SSH proxy (`sshN.vast.ai`) works too. Krater
refuses to start boxes while the Vast account has any SSH keys, since Vast may install them in every instance.

A host can map the direct port and still refuse every connection to it. On production (2026-11-22), Vast machine
153597 mapped 22/tcp to port 20056, sshd listened on 22 in the container, and Vast said the box was running. The
port refused connections from everywhere, but the proxy reached the same sshd. So the worker tests a running box's
direct port with one TCP connection (`krater.compute.ssh_reach`), only while the box's runner reports from the
current container and Krater's own network is up. A refusal moves the box to the proxy address, and the job page,
`krater ssh` and `krater show` give that address; the box's events say so once (`ssh_proxy`). A timeout decides
nothing. (A host that drops connections, not refuses them, keeps its direct address.) While the port can't be tested (a paused box, a quiet runner), a box moved to the proxy stays there. The
worker tests a working port once per process and a refused one again after 30 minutes, at most 5 new tests a pass.
It never connects to an address that isn't public. The test runs from the worker, so a member whose own network
blocks Vast's direct ports still gets the direct address.

What a member can read inside their box: the container's environment (`/proc/1/environ`) has `KRATER_JOB_TOKEN`
(this instance's runner token: it can only report for this box), Vast's `CONTAINER_API_KEY` (it can stop or destroy
this one instance; Krater treats that like any unexpected stop) and a `JUPYTER_TOKEN` Vast generates. Boxes are
Expand Down
71 changes: 66 additions & 5 deletions krater/compute/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
from sqlalchemy.orm import Session

from krater import net_errors, providers
from krater.compute import launch, market, offers, runner_api, search_quota, spend
from krater.compute import launch, market, offers, runner_api, search_quota, spend, ssh_reach
from krater.compute.search_pacing import SearchPacer
from krater.config import Settings
from krater.models import (
Expand Down Expand Up @@ -313,8 +313,12 @@ def __init__(
pacer: SearchPacer | None = None,
registry: Registry | None = None,
network: network_watch.NetworkCheck | None = None,
ssh_check: ssh_reach.SshCheck | None = None,
) -> None:
self.session = session
# Asked whether a box's direct SSH port takes connections (`_record_ssh`). Without one (tests, one-off
# passes), the direct port is trusted, as Vast lists it.
self.ssh_check = ssh_check
# Asked before acting on a silent runner (`_hold_for_network`). Without one (tests, one-off passes), the
# network counts as up.
self.network = network
Expand Down Expand Up @@ -1366,12 +1370,67 @@ def _start_self_stopped(self, row: ComputeInstance) -> None:
# -- Boxes -----------------------------------------------------------------------------------------

def _record_ssh(self, row: ComputeInstance, seen: Instance) -> None:
"""Where the member's SSH client should connect: the direct port when Vast mapped one, else Vast's proxy."""
"""Where the member's SSH client should connect: the direct port when Vast mapped one and it takes
connections, else Vast's proxy (`krater.compute.ssh_reach`). While the direct port can't be tested, an
address already moved to the proxy stays there."""
direct = None
mapped = (seen.ports or {}).get("22/tcp") or []
if seen.public_ipaddr and mapped and isinstance(mapped[0], dict) and mapped[0].get("HostPort"):
row.ssh_host, row.ssh_port = seen.public_ipaddr, int(mapped[0]["HostPort"])
elif seen.ssh_host and seen.ssh_port:
row.ssh_host, row.ssh_port = seen.ssh_host, seen.ssh_port
try:
direct = (seen.public_ipaddr, int(mapped[0]["HostPort"]))
except (TypeError, ValueError):
direct = None
proxy = (seen.ssh_host, seen.ssh_port) if seen.ssh_host and seen.ssh_port else None
if direct is None:
if proxy is not None:
row.ssh_host, row.ssh_port = proxy
return
if proxy is None:
row.ssh_host, row.ssh_port = direct
return
works = self._direct_ssh_works(row, seen, direct)
if works is None:
# Untested now: stay on the proxy only if Krater moved it there for a refused direct port.
works = (row.ssh_host, row.ssh_port) == direct or not self._told_ssh_proxy(row)
if works:
row.ssh_host, row.ssh_port = direct
return
if not self._told_ssh_proxy(row):
_event(
self.session,
row.job,
"ssh_proxy",
f"The machine's direct SSH port ({direct[0]}:{direct[1]}) refuses connections, so SSH goes "
f"through {self.provider.title}'s proxy ({proxy[0]}:{proxy[1]}).",
now=self.now,
instance=row,
)
row.ssh_host, row.ssh_port = proxy

def _direct_ssh_works(self, row: ComputeInstance, seen: Instance, direct: tuple[str, int]) -> bool | None:
"""Whether `direct` takes connections, or `None` when it can't be told now. Only a running box's port is
tested, and only while its runner reports from the current container: sshd starts before the runner, so a
refusal then is the host's doing. Not while Krater's own network is down, or the box is ending."""
if self.ssh_check is None or row.job.kind is not ComputeJobKind.BOX:
return None
if row.state is not ComputeInstanceState.RUNNING or seen.phase is not Phase.RUNNING or seen.stopping:
return None
if row.destroy_requested_at is not None or row.stop_requested_at is not None:
return None
if row.runner_starts < row.runner_starts_needed or not self._beat_is_fresh(row):
return None
if self.network is not None:
if self._network_problem is False:
self._network_problem = self.network.problem(self.session, now=self.now)
if self._network_problem:
return None
return self.ssh_check.direct_works(row.provider_instance_id or row.label, *direct, now=self.now)

def _told_ssh_proxy(self, row: ComputeInstance) -> bool:
stmt = sa.select(ComputeEvent.id).where(
ComputeEvent.job_id == row.job_id, ComputeEvent.instance_id == row.id, ComputeEvent.kind == "ssh_proxy"
)
return self.session.scalar(stmt.limit(1)) is not None

def _check_idle(self, row: ComputeInstance, job: ComputeJob, policy: ComputePolicy) -> None:
"""A box is idle while its runner reports low GPU (and CPU) use and no open session. Idle for the box idle
Expand Down Expand Up @@ -2152,6 +2211,7 @@ def run_pass(
pacer: SearchPacer | None = None,
registry: Registry | None = None,
network: network_watch.NetworkCheck | None = None,
ssh_check: ssh_reach.SshCheck | None = None,
) -> PassResult:
return Scheduler(
session,
Expand All @@ -2163,4 +2223,5 @@ def run_pass(
pacer=pacer,
registry=registry,
network=network,
ssh_check=ssh_check,
).run()
99 changes: 99 additions & 0 deletions krater/compute/ssh_reach.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""Whether a box's direct SSH port takes connections, so Krater gives members an address that works.

Vast gives a box two ways in: a direct port on the host's public address (`ports["22/tcp"]`), and its own SSH proxy
(`ssh_host`, `ssh_port`). Krater prefers the direct port: it skips a hop. But a host can list a mapped direct port
that refuses every connection. Seen live 2026-11-22: Vast machine 153597 mapped 22/tcp to port 20056, sshd listened
on 22 in the container and Vast said the box was running, yet the port refused connections from everywhere. The
proxy reached the same sshd. Every box rented there gave its member a dead `krater ssh`.

So the worker opens a TCP connection to a running box's direct port (`krater.compute.scheduler`, `_record_ssh`):

- **Refused** (the host answered: nothing is forwarded) means it doesn't work, and Krater records the proxy. The
scheduler asks only while the box's runner reports from the current container, and sshd starts before the runner,
so a refusal then is the host's doing, not a container still starting.
- **Accepted** means it works, and the direct address stays.
- **No answer** (a timeout, an unreachable network, any other error) decides nothing, and the address stays as it
is: the fault may be on the worker's side.

A host-supplied address that isn't a public one, or a port out of range, can't be what a member connects to, so it
counts as not working without a connection: the worker never connects to a private or loopback address for a host.

Each answer is kept for the worker's process, per instance and address: an accepted one for good, the others for
`RECHECK`, so a box is tested about twice an hour at most, not every pass (each test is a login attempt sshd logs).
A pass tests at most `PROBES_PER_MINUTE` new addresses; the rest wait for the next pass, so hosts that drop packets
can't stretch the scheduler's pass.

Framework-free.
"""

from __future__ import annotations

import ipaddress
import socket
from datetime import datetime, timedelta
from typing import Protocol

#: A refusal answers at once; a dropped connection waits this long and decides nothing.
CONNECT_TIMEOUT_SECONDS = 2.0
#: How long a refusal or no answer is kept before the address is tested again.
RECHECK = timedelta(minutes=30)
#: New tests in one minute (one scheduler pass), so a pass waits at most this many timeouts.
PROBES_PER_MINUTE = 5
#: Answers kept; past this the oldest are dropped (destroyed instances' answers, mostly).
MAX_KNOWN = 1000


def probe_tcp(host: str, port: int) -> bool | None:
"""`True` when a TCP connection to `host:port` opens, `False` when it is refused, `None` with no answer."""
try:
with socket.create_connection((host, port), timeout=CONNECT_TIMEOUT_SECONDS):
return True
except ConnectionRefusedError:
return False
except Exception: # noqa: BLE001 - a timeout, no route, a bad address: none of them says the port is closed
return None


def reachable_address(host: str, port: int) -> bool:
"""Whether `host:port` could be a member's way in: a public IP address and a real port."""
if not 1 <= port <= 65535:
return False
try:
return ipaddress.ip_address(host).is_global
except (TypeError, ValueError):
return False


class SshCheck(Protocol):
def direct_works(self, instance_id: str, host: str, port: int, *, now: datetime) -> bool | None:
"""Whether the direct SSH address `host:port` of `instance_id` takes connections; `None` when unknown."""


class LiveSshCheck:
"""The worker's check. One instance lives for the worker's process and remembers each answer."""

def __init__(self, *, probe=probe_tcp) -> None:
self._probe = probe
self._known: dict[tuple[str, str, int], tuple[bool | None, datetime]] = {}
self._minute: datetime | None = None
self._probes_this_minute = 0

def direct_works(self, instance_id: str, host: str, port: int, *, now: datetime) -> bool | None:
if not reachable_address(host, port):
return False
key = (instance_id, host, port)
known = self._known.get(key)
if known is not None and (known[0] is True or now - known[1] < RECHECK):
return known[0]
minute = now.replace(second=0, microsecond=0)
if minute != self._minute:
self._minute, self._probes_this_minute = minute, 0
if self._probes_this_minute >= PROBES_PER_MINUTE:
return known[0] if known is not None else None
self._probes_this_minute += 1
answer = self._probe(host, port)
if len(self._known) >= MAX_KNOWN:
for old in sorted(self._known, key=lambda k: self._known[k][1])[: MAX_KNOWN // 10]:
del self._known[old]
self._known[key] = (answer, now)
return answer
6 changes: 6 additions & 0 deletions krater/worker/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from krater.compute import reconcile as compute_reconciler
from krater.compute import scheduler as compute_scheduler
from krater.compute import search_quota as compute_search_quota
from krater.compute import ssh_reach as compute_ssh_reach
from krater.compute import storage_cleanup as compute_storage
from krater.compute.search_pacing import SearchPacer
from krater.config import get_settings
Expand Down Expand Up @@ -265,6 +266,10 @@ def price_history_record(timestamp: int) -> None:
#: for the process: it remembers whether its outbound test has ever passed here.
NETWORK_CHECK = network_watch.LiveNetworkCheck(edge_ping_expected=get_settings().edge_ping_expected)

#: Whether each box's direct SSH port takes connections (`krater.compute.ssh_reach`). One for the process: it
#: remembers each answer, so a box is tested once.
SSH_CHECK = compute_ssh_reach.LiveSshCheck()

#: Only one scheduler pass runs at a time, so a slow pass can't overlap the next minute's and rent twice.
COMPUTE_SCHEDULER_LOCK = "compute_scheduler"

Expand All @@ -289,6 +294,7 @@ def compute_schedule(timestamp: int) -> None:
weave_client=get_weave_client(),
pacer=SEARCH_PACER,
network=NETWORK_CHECK,
ssh_check=SSH_CHECK,
registry=get_registry(),
)
if result.errors:
Expand Down
Loading
Loading