Schedule a node across every machine, not just this one
The engine answered "where does this node run" twice, in two ways that could not see each other: a device sent it to a worker carrying that label, and resources were counted against the engine's own cores. Declaring both meant the second answer won and nothing was counted at all — which the data-science getting-started page and the worked example both do. One question now, in flow/placement.py: of every machine attached, which could grant what this node asked for, and which of those has it free. The books move onto each machine — one accountant per worker, built from the inventory it reported — and the waiting moves above them, where one condition variable can be woken by a release anywhere or by a worker attaching. Locks go one way: placer, then a machine's books, never back. So a node asking for a card now finds the box that has one, rather than being clamped down to none and run here. When nothing can grant the ask at all it is still cut down and run — a flow written on a cluster has to work on a laptop — but the ceiling is one real machine now, since taking the largest of each dimension separately can describe a machine nobody has. Two things fixed on the way. A device on a connector node held every batch run of its flow forever, waiting for a worker that could never run an entry point. And `prefer` falling back to the engine skipped the books, so the fallback held nothing. The bench flow's node has taken a `params` argument that with_settings has not forwarded for some time, so the benchmark could not run at all: 62 ms median submit-to-result with this, against the 61 ms on record. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01A6HeySA27EkGANZN95QySW
This commit is contained in:
@@ -62,6 +62,7 @@ from fluksio.flow.pipeline import (
|
||||
ValidationIssue,
|
||||
ValueSource,
|
||||
)
|
||||
from fluksio.flow.placement import Placer
|
||||
from fluksio.flow.remote import RemoteWorkerHub
|
||||
from fluksio.flow.resources import ResourceAccountant, derive_env
|
||||
from fluksio.flow.schemas import (
|
||||
@@ -413,6 +414,7 @@ class FlowController:
|
||||
workers: PythonWorkerPool | None = None,
|
||||
remote: RemoteWorkerHub | None = None,
|
||||
resources: ResourceAccountant | None = None,
|
||||
placer: Placer | None = None,
|
||||
) -> None:
|
||||
self.store = store
|
||||
# Without a pool, python nodes are compiled and run in this process —
|
||||
@@ -420,9 +422,11 @@ class FlowController:
|
||||
self.workers = workers
|
||||
# Workers on other hosts. A node without a device never touches it.
|
||||
self.remote = remote
|
||||
# What the machine has, for the nodes that say what they need. Without
|
||||
# one, a declaration is recorded and nothing is held against it.
|
||||
# This machine's own books. The pool sizes its fair share off them.
|
||||
self.resources = resources
|
||||
# Every machine there is, for the nodes that say what they need.
|
||||
# Without one, a declaration is recorded and nothing is held against it.
|
||||
self.placer = placer
|
||||
self.state = state if state is not None else MemoryState()
|
||||
self.events = events
|
||||
self.max_workers = max_workers
|
||||
@@ -865,9 +869,18 @@ class FlowController:
|
||||
# Building
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
def _allocated(
|
||||
def _runs_elsewhere(self, node_def: NodeDef) -> bool:
|
||||
"""Whether this node asks for more than this machine could ever give."""
|
||||
if node_def.resources is None or self.placer is None:
|
||||
return False
|
||||
wanted = node_def.resources
|
||||
return not self.placer.local.fits(wanted.cpus, wanted.gpus, wanted.ram or 0)
|
||||
|
||||
def _placed(
|
||||
self,
|
||||
wanted: Resources,
|
||||
device: str | None,
|
||||
policy: str,
|
||||
owner: str,
|
||||
local: str,
|
||||
code: str,
|
||||
@@ -877,32 +890,40 @@ class FlowController:
|
||||
run_id: str,
|
||||
on_event: Callable[[dict[str, Any]], None],
|
||||
) -> Callable[..., Any]:
|
||||
"""A call that holds its share of the machine while it runs.
|
||||
"""A call that picks a machine and holds its share while it runs.
|
||||
|
||||
Which machine is decided per call rather than when the flow was built,
|
||||
so a worker that attaches later is used without anything being rebuilt.
|
||||
|
||||
The order is load-bearing: the resources are claimed first, and only
|
||||
then is a worker slot taken. The other way round, a node holding a slot
|
||||
could sit waiting for cores that a node holding the cores cannot get a
|
||||
slot to release.
|
||||
|
||||
The worker comes from the pool whose environment this allocation
|
||||
derives, so what the node is told about its share is what the library
|
||||
inside it reads at import — the only moment those variables are read.
|
||||
What the allocation implies is handed to the process the node runs in,
|
||||
here or on the worker, because a library reads those variables when it
|
||||
is imported and never again.
|
||||
"""
|
||||
if self.workers is None or self.resources is None:
|
||||
return self.workers.proxy( # type: ignore[union-attr]
|
||||
owner,
|
||||
local,
|
||||
code,
|
||||
node_id=node_id,
|
||||
timeout=timeout,
|
||||
run_id=run_id,
|
||||
on_event=on_event,
|
||||
)
|
||||
accountant, pool = self.resources, self.workers
|
||||
placer, pool = self.placer, self.workers
|
||||
|
||||
def call(**kwargs: Any) -> Any:
|
||||
with accountant.claim(wanted, node=node_id, run=run_id) as allocation:
|
||||
return pool.for_env(derive_env(wanted, allocation)).run(
|
||||
with placer.claim(
|
||||
wanted, device=device, policy=policy, node=node_id, run=run_id
|
||||
) as (target, allocation):
|
||||
env = derive_env(wanted, allocation)
|
||||
if target.worker is None:
|
||||
return pool.for_env(env).run(
|
||||
owner,
|
||||
local,
|
||||
code,
|
||||
kwargs,
|
||||
node_id,
|
||||
timeout,
|
||||
run_id=run_id,
|
||||
on_event=on_event,
|
||||
)
|
||||
return self.remote.run_on( # type: ignore[union-attr]
|
||||
target.worker,
|
||||
owner,
|
||||
local,
|
||||
code,
|
||||
@@ -911,6 +932,7 @@ class FlowController:
|
||||
timeout,
|
||||
run_id=run_id,
|
||||
on_event=on_event,
|
||||
env=env,
|
||||
)
|
||||
|
||||
return call
|
||||
@@ -1003,6 +1025,11 @@ class FlowController:
|
||||
problem = self.remote.compile(
|
||||
node_def.device or "", owner, local, code
|
||||
)
|
||||
elif self._runs_elsewhere(node_def):
|
||||
# Asks for more than this machine has, so it will run on
|
||||
# one that has it. Same reason as a device: checking the
|
||||
# import here would fail a node that is fine there.
|
||||
problem = None
|
||||
else:
|
||||
problem = self.workers.compile(owner, local, code)
|
||||
if problem:
|
||||
@@ -1016,18 +1043,15 @@ class FlowController:
|
||||
if node_def.timeout is not None
|
||||
else settings.FLOW_NODE_TIMEOUT
|
||||
)
|
||||
function = self.workers.proxy(
|
||||
owner,
|
||||
local,
|
||||
code,
|
||||
node_id=node_id,
|
||||
timeout=timeout,
|
||||
run_id=run.run_id if run else "",
|
||||
on_event=emissions.handle,
|
||||
)
|
||||
if node_def.resources is not None and not node_def.device:
|
||||
function = self._allocated(
|
||||
if node_def.resources is not None and self.placer is not None:
|
||||
# Says how much of a machine it takes, so which machine
|
||||
# and how much of it are one decision — including when
|
||||
# it also names a device, which used to mean the two
|
||||
# answers disagreed and nothing was accounted at all.
|
||||
function = self._placed(
|
||||
node_def.resources,
|
||||
node_def.device,
|
||||
node_def.device_policy,
|
||||
owner,
|
||||
local,
|
||||
code,
|
||||
@@ -1036,11 +1060,9 @@ class FlowController:
|
||||
run_id=run.run_id if run else "",
|
||||
on_event=emissions.handle,
|
||||
)
|
||||
if node_def.device and self.remote is not None:
|
||||
# A node with a device runs on a worker carrying that
|
||||
# label. Which worker is decided per call, so one that
|
||||
# attaches after this flow was built is used without
|
||||
# anything being rebuilt.
|
||||
elif node_def.device and self.remote is not None:
|
||||
# A device and nothing about size: the label alone
|
||||
# decides, least busy first, as it always has.
|
||||
function = self.remote.proxy(
|
||||
node_def.device,
|
||||
owner,
|
||||
@@ -1051,9 +1073,30 @@ class FlowController:
|
||||
run_id=run.run_id if run else "",
|
||||
on_event=emissions.handle,
|
||||
fallback=(
|
||||
function if node_def.device_policy == "prefer" else None
|
||||
self.workers.proxy(
|
||||
owner,
|
||||
local,
|
||||
code,
|
||||
node_id=node_id,
|
||||
timeout=timeout,
|
||||
run_id=run.run_id if run else "",
|
||||
on_event=emissions.handle,
|
||||
)
|
||||
if node_def.device_policy == "prefer"
|
||||
else None
|
||||
),
|
||||
)
|
||||
else:
|
||||
# Declares nothing: the shared pool, at no extra cost.
|
||||
function = self.workers.proxy(
|
||||
owner,
|
||||
local,
|
||||
code,
|
||||
node_id=node_id,
|
||||
timeout=timeout,
|
||||
run_id=run.run_id if run else "",
|
||||
on_event=emissions.handle,
|
||||
)
|
||||
# Outermost, so it sees the result whichever of the three
|
||||
# above answered the call.
|
||||
function = emissions.wrap(function)
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
"""Which machine a node runs on, and the waiting when none of them has room.
|
||||
|
||||
The engine used to answer this twice, in two ways that could not see each
|
||||
other. A node with a ``device`` went to a worker carrying that label, chosen by
|
||||
which of them had least in flight — a machine's *name*, never its size. A node
|
||||
with ``resources`` was accounted against the engine's own cores, and only the
|
||||
engine's: declaring both meant the second answer silently won and nothing was
|
||||
counted at all.
|
||||
|
||||
One question, then, asked once here: of every machine attached — this one and
|
||||
each worker — which could grant what this node asked for, and which of those
|
||||
has it free right now. A worker reports its inventory when it attaches, so the
|
||||
answer covers the whole installation rather than the host the engine happens to
|
||||
be on.
|
||||
|
||||
Two properties are worth stating because they are what make the waiting safe:
|
||||
|
||||
*Waiting is central.* One condition variable, woken by a release on any machine
|
||||
and by a worker attaching. A node waiting inside one machine's books could not
|
||||
be woken by a second machine appearing, which is exactly the case a cluster is
|
||||
for.
|
||||
|
||||
*Locks go one way.* This condition, then a machine's books, never the reverse —
|
||||
:meth:`ResourceAccountant.try_take` does not block and
|
||||
:meth:`ResourceAccountant.give_back` calls back out after dropping its own
|
||||
lock. The other invariant the engine already had still holds too: the claim is
|
||||
taken before a worker slot, so a node holding a slot can never be waiting on
|
||||
resources that a node holding those resources cannot get a slot to release.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from fluksio.flow.events import EventBus
|
||||
from fluksio.flow.resources import Allocation, ResourceAccountant
|
||||
from fluksio.flow.schemas import Resources
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - imported for types only
|
||||
from fluksio.flow.provision import Provisioner
|
||||
from fluksio.flow.remote import RemoteWorker, RemoteWorkerHub
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: How long a waiting node sleeps before looking again without being woken.
|
||||
#: Everything that frees a machine wakes it, so this only catches a wakeup lost
|
||||
#: to a race and gives a provisioned machine's timeout somewhere to be noticed.
|
||||
WAKE_S = 5.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Target:
|
||||
"""One machine a node could run on: this engine, or an attached worker."""
|
||||
|
||||
name: str
|
||||
accountant: ResourceAccountant
|
||||
#: None is the engine itself, which runs nodes in its own worker pool.
|
||||
worker: RemoteWorker | None = None
|
||||
|
||||
def carries(self, device: str) -> bool:
|
||||
"""Whether a node asking for this device may run here.
|
||||
|
||||
The engine carries no label: a label names a machine somebody attached
|
||||
for the purpose, and the engine is where the node would have run anyway.
|
||||
"""
|
||||
if self.worker is None:
|
||||
return False
|
||||
return device == self.name or device in self.worker.labels
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Waiting:
|
||||
node: str
|
||||
since: float
|
||||
reason: str
|
||||
|
||||
|
||||
class Placer:
|
||||
"""Every machine the engine can reach, and who is queued for one."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
local: ResourceAccountant,
|
||||
hub: RemoteWorkerHub | None = None,
|
||||
events: EventBus | None = None,
|
||||
) -> None:
|
||||
self.local = local
|
||||
self.hub = hub
|
||||
self.events = events
|
||||
self.provisioners: list[Provisioner] = []
|
||||
self._condition = threading.Condition()
|
||||
self._waiting: dict[int, _Waiting] = {}
|
||||
self._ticket = 0
|
||||
local.on_release = self.wake
|
||||
|
||||
# -- the machines ----------------------------------------------------------
|
||||
|
||||
def wake(self) -> None:
|
||||
"""Something changed: a machine freed up, or one attached or left."""
|
||||
for provisioner in self.provisioners:
|
||||
provisioner.reconcile(self._attached_names())
|
||||
with self._condition:
|
||||
self._condition.notify_all()
|
||||
|
||||
def _attached_names(self) -> set[str]:
|
||||
if self.hub is None:
|
||||
return set()
|
||||
return {worker.name for worker in self.hub.workers() if not worker.gone}
|
||||
|
||||
def targets(self) -> list[Target]:
|
||||
"""This engine, and every worker attached right now."""
|
||||
found = [Target(name="engine", accountant=self.local)]
|
||||
if self.hub is not None:
|
||||
for worker in self.hub.workers():
|
||||
if worker.gone:
|
||||
continue
|
||||
# Assigned here rather than at attach so a worker that
|
||||
# reconnects — a new object, with fresh books — is wired up
|
||||
# without the hub having to know about placement at all.
|
||||
worker.accountant.on_release = self.wake
|
||||
found.append(
|
||||
Target(
|
||||
name=worker.name,
|
||||
accountant=worker.accountant,
|
||||
worker=worker,
|
||||
)
|
||||
)
|
||||
return found
|
||||
|
||||
def _candidates(
|
||||
self,
|
||||
cpus: int,
|
||||
gpus: int,
|
||||
ram_mb: int,
|
||||
device: str | None,
|
||||
policy: str,
|
||||
) -> list[Target]:
|
||||
"""The machines that could run this node, best first."""
|
||||
targets = self.targets()
|
||||
remote = [target for target in targets if target.worker is not None]
|
||||
engine = [target for target in targets if target.worker is None]
|
||||
|
||||
if device:
|
||||
labelled = [target for target in remote if target.carries(device)]
|
||||
fitting = self._fitting(labelled, cpus, gpus, ram_mb)
|
||||
if fitting or policy != "prefer":
|
||||
# `require` waits for the labelled machine even when the engine
|
||||
# could take the node: the label is a statement about where
|
||||
# this node is correct, not a preference.
|
||||
return fitting
|
||||
# `prefer` is what makes a flow work before the GPU box exists. It
|
||||
# falls back only when nothing labelled could ever take the node —
|
||||
# one that is merely busy is worth queueing for.
|
||||
return self._fitting(engine, cpus, gpus, ram_mb)
|
||||
|
||||
# No label: the engine first when it fits, because a node that runs
|
||||
# here costs no network and reuses a warm worker.
|
||||
ordered = engine + sorted(
|
||||
remote, key=lambda target: target.worker.in_flight if target.worker else 0
|
||||
)
|
||||
return self._fitting(ordered, cpus, gpus, ram_mb)
|
||||
|
||||
@staticmethod
|
||||
def _fitting(
|
||||
targets: list[Target], cpus: int, gpus: int, ram_mb: int
|
||||
) -> list[Target]:
|
||||
return [t for t in targets if t.accountant.fits(cpus, gpus, ram_mb)]
|
||||
|
||||
# -- what can actually be granted ------------------------------------------
|
||||
|
||||
def _shapes(self, device: str | None, policy: str) -> list[tuple[int, int, int]]:
|
||||
"""Every machine's size, as something to measure a request against.
|
||||
|
||||
A provisioner's job shapes count: a machine it can start on demand is
|
||||
one this installation has, even when nothing is attached yet.
|
||||
"""
|
||||
shapes = []
|
||||
for target in self.targets():
|
||||
if device and not target.carries(device):
|
||||
# A `prefer` node may end up here, so the engine still counts.
|
||||
if policy == "require" or target.worker is not None:
|
||||
continue
|
||||
books = target.accountant
|
||||
shapes.append((books.cpus, books.gpus, books.ram_mb or 0))
|
||||
for provisioner in self.provisioners:
|
||||
shapes.extend(provisioner.shapes(device))
|
||||
return shapes or [(self.local.cpus, self.local.gpus, self.local.ram_mb or 0)]
|
||||
|
||||
def _clamp(
|
||||
self, wanted: Resources, node: str, device: str | None, policy: str
|
||||
) -> tuple[int, int, int]:
|
||||
"""What can be granted somewhere, which may be less than was asked.
|
||||
|
||||
A flow written against a sixty-four core box should still run on a
|
||||
laptop — waiting forever for cores that do not exist is not a smaller
|
||||
machine, it is a hung run. What it must not become is an ask no single
|
||||
machine can grant: taking the largest of each dimension separately can
|
||||
describe a machine that is not there, and waiting on *that* is the hung
|
||||
run this exists to avoid. So the GPUs are settled first, and the rest is
|
||||
measured only against machines that carry that many.
|
||||
"""
|
||||
ram = wanted.ram or 0
|
||||
shapes = self._shapes(device, policy)
|
||||
gpus = min(wanted.gpus, max(shape[1] for shape in shapes))
|
||||
capable = [shape for shape in shapes if shape[1] >= gpus]
|
||||
cpus = min(wanted.cpus, max(shape[0] for shape in capable))
|
||||
# A machine that reported no memory is not a memory limit; only those
|
||||
# that did have anything to say about it.
|
||||
said = [shape[2] for shape in capable if shape[2]]
|
||||
ram = min(ram, max(said)) if said and ram else ram
|
||||
if (cpus, gpus, ram) != (wanted.cpus, wanted.gpus, wanted.ram or 0):
|
||||
logger.warning(
|
||||
"%s asked for %d cpu(s), %d gpu(s) and %s MB; "
|
||||
"the largest machine here can give %d, %d and %s",
|
||||
node or "a node",
|
||||
wanted.cpus,
|
||||
wanted.gpus,
|
||||
wanted.ram or "no stated",
|
||||
cpus,
|
||||
gpus,
|
||||
ram or "no stated",
|
||||
)
|
||||
return cpus, gpus, ram
|
||||
|
||||
# -- holding a machine for the length of a call ----------------------------
|
||||
|
||||
@contextmanager
|
||||
def claim(
|
||||
self,
|
||||
wanted: Resources,
|
||||
*,
|
||||
device: str | None = None,
|
||||
policy: str = "require",
|
||||
node: str = "",
|
||||
run: str = "",
|
||||
) -> Iterator[tuple[Target, Allocation]]:
|
||||
"""Hold a machine's share of itself for as long as this node runs."""
|
||||
waited_from = time.monotonic()
|
||||
ticket = 0
|
||||
chosen: Target | None = None
|
||||
allocation: Allocation | None = None
|
||||
|
||||
with self._condition:
|
||||
while chosen is None:
|
||||
cpus, gpus, ram = self._clamp(wanted, node, device, policy)
|
||||
for target in self._candidates(cpus, gpus, ram, device, policy):
|
||||
got = target.accountant.try_take(cpus, gpus, ram)
|
||||
if got is not None:
|
||||
chosen, allocation = target, got
|
||||
break
|
||||
if chosen is not None:
|
||||
break
|
||||
if not ticket:
|
||||
ticket = self._announce(
|
||||
node, run, waited_from, self._reason(cpus, gpus, device)
|
||||
)
|
||||
self._provision(cpus, gpus, ram, device)
|
||||
self._condition.wait(timeout=WAKE_S)
|
||||
if ticket:
|
||||
self._waiting.pop(ticket, None)
|
||||
|
||||
if ticket:
|
||||
logger.info(
|
||||
"%s waited %.1fs and runs on '%s'",
|
||||
node or "a node",
|
||||
time.monotonic() - waited_from,
|
||||
chosen.name,
|
||||
)
|
||||
assert allocation is not None
|
||||
try:
|
||||
yield chosen, allocation
|
||||
finally:
|
||||
# Every way a call can end comes through here: an answer, a
|
||||
# timeout, a cancellation, or the worker going away mid-call.
|
||||
chosen.accountant.give_back(allocation)
|
||||
|
||||
def _reason(self, cpus: int, gpus: int, device: str | None) -> str:
|
||||
parts = []
|
||||
if gpus:
|
||||
parts.append(f"{gpus} gpu(s)")
|
||||
parts.append(f"{cpus} cpu(s)")
|
||||
wants = " and ".join(parts)
|
||||
if device:
|
||||
return f"waiting for a worker labelled '{device}' with {wants} free"
|
||||
return f"waiting for {wants}"
|
||||
|
||||
def _provision(self, cpus: int, gpus: int, ram_mb: int, device: str | None) -> None:
|
||||
"""Ask for a machine, if something here can start one."""
|
||||
for provisioner in self.provisioners:
|
||||
if provisioner.covers(cpus, gpus, ram_mb, device):
|
||||
provisioner.provision(cpus, gpus, ram_mb, device)
|
||||
return
|
||||
|
||||
def _announce(self, node: str, run: str, since: float, reason: str) -> int:
|
||||
"""Say a node is queued, not stuck.
|
||||
|
||||
The failure this exists for looked identical to a hang: a run sitting
|
||||
at `running` for twenty minutes with no error and no output. A node
|
||||
waiting its turn has to say so somewhere a person will look.
|
||||
"""
|
||||
self._ticket += 1
|
||||
ticket = self._ticket
|
||||
self._waiting[ticket] = _Waiting(node=node, since=since, reason=reason)
|
||||
logger.info("%s is %s", node or "a node", reason)
|
||||
if self.events is not None:
|
||||
self.events.publish(
|
||||
{
|
||||
"type": "node_queued",
|
||||
"flow": node.split(".", 1)[0] if node else "",
|
||||
"node": node,
|
||||
"run": run,
|
||||
"detail": reason,
|
||||
"ts": time.time(),
|
||||
}
|
||||
)
|
||||
return ticket
|
||||
|
||||
# -- what it looks like from outside ---------------------------------------
|
||||
|
||||
def satisfiable(self, needs: dict[str, Any] | None) -> str | None:
|
||||
"""What a run would have to wait for, or None if it would not wait.
|
||||
|
||||
Only a genuine wait is worth holding a run for. A request nothing can
|
||||
grant is cut down to what is here and runs anyway, so answering "no
|
||||
machine has 64 cores" would hold a run that was about to work.
|
||||
"""
|
||||
if not needs:
|
||||
return None
|
||||
cpus = int(needs.get("cpus") or 1)
|
||||
gpus = int(needs.get("gpus") or 0)
|
||||
ram = int(needs.get("ram_mb") or 0)
|
||||
device = needs.get("device") or None
|
||||
for target in self.targets():
|
||||
if device and not target.carries(device):
|
||||
continue
|
||||
if target.accountant.fits(cpus, gpus, ram):
|
||||
# Something here could take it. Busy is queueing, not waiting.
|
||||
return None
|
||||
if not any(
|
||||
provisioner.covers(cpus, gpus, ram, device)
|
||||
for provisioner in self.provisioners
|
||||
):
|
||||
# Nothing attached fits and nothing can be started, so the node
|
||||
# will be clamped onto what is here and run. Holding the run would
|
||||
# be holding it for something that is not going to happen — and
|
||||
# where the wait is a missing *label*, `required_labels` says so
|
||||
# already.
|
||||
return None
|
||||
return f"{gpus} gpu(s) and {cpus} cpu(s)" if gpus else f"{cpus} cpu(s)"
|
||||
|
||||
def snapshot(self) -> dict[str, Any]:
|
||||
"""Every machine, what is free of it, and who is queued.
|
||||
|
||||
A node waiting its turn looks exactly like a node that has hung — the
|
||||
run sits at `running` and says nothing — so what is waiting, and for
|
||||
what, has to be readable somewhere.
|
||||
"""
|
||||
targets = []
|
||||
for target in self.targets():
|
||||
entry: dict[str, Any] = {"target": target.name}
|
||||
entry.update(target.accountant.snapshot())
|
||||
if target.worker is not None:
|
||||
entry["labels"] = sorted(target.worker.labels)
|
||||
entry["in_flight"] = target.worker.in_flight
|
||||
targets.append(entry)
|
||||
with self._condition:
|
||||
waiting = list(self._waiting.values())
|
||||
local = self.local.snapshot()
|
||||
return {
|
||||
# The engine's own figures stay where they were, so a reader that
|
||||
# only ever knew about one machine still finds them.
|
||||
"cpus": local["cpus"],
|
||||
"gpus": local["gpus"],
|
||||
"waiting": [
|
||||
{
|
||||
"node": entry.node,
|
||||
"reason": entry.reason,
|
||||
"seconds": round(time.monotonic() - entry.since, 1),
|
||||
}
|
||||
for entry in waiting
|
||||
],
|
||||
"targets": targets,
|
||||
"provisioners": [p.status() for p in self.provisioners],
|
||||
}
|
||||
@@ -32,6 +32,7 @@ from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from fluksio.flow.nodes.base import NodeOutputError
|
||||
from fluksio.flow.resources import ResourceAccountant
|
||||
from fluksio.flow.workers import NodeTimeout, RemoteError, _remote_class
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -106,6 +107,14 @@ class RemoteWorker:
|
||||
self.labels = set(labels)
|
||||
self.info = info or {}
|
||||
self.inventory = inventory or WorkerInventory()
|
||||
# This machine's books, held here so that a worker reconnecting — which
|
||||
# is a new object — starts from a clean set rather than from counters
|
||||
# the engine kept for a socket that is gone.
|
||||
self.accountant = ResourceAccountant(
|
||||
cpus=self.inventory.cpus,
|
||||
gpus=self.inventory.gpus,
|
||||
ram_mb=self.inventory.ram_mb,
|
||||
)
|
||||
self.attached_at = time.time()
|
||||
self.last_seen = time.time()
|
||||
self._send = send
|
||||
@@ -251,9 +260,13 @@ class RemoteWorker:
|
||||
class RemoteWorkerHub:
|
||||
"""Every attached worker, and which of them a node may run on."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
def __init__(self, on_change: Callable[[], None] | None = None) -> None:
|
||||
self._workers: dict[str, RemoteWorker] = {}
|
||||
self._lock = threading.Lock()
|
||||
#: Told when the set of attached workers changes, so whoever is waiting
|
||||
#: for a machine can look again. Called outside the lock: it takes one
|
||||
#: of its own, and the two are only ever taken in that order.
|
||||
self.on_change = on_change
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Attachment
|
||||
@@ -270,6 +283,7 @@ class RemoteWorkerHub:
|
||||
logger.info(
|
||||
"Worker '%s' attached with labels %s", worker.name, sorted(worker.labels)
|
||||
)
|
||||
self._changed()
|
||||
|
||||
def detach(self, name: str) -> None:
|
||||
with self._lock:
|
||||
@@ -277,6 +291,11 @@ class RemoteWorkerHub:
|
||||
if worker is not None:
|
||||
worker.detach()
|
||||
logger.info("Worker '%s' detached", name)
|
||||
self._changed()
|
||||
|
||||
def _changed(self) -> None:
|
||||
if self.on_change is not None:
|
||||
self.on_change()
|
||||
|
||||
def workers(self) -> list[RemoteWorker]:
|
||||
with self._lock:
|
||||
@@ -326,6 +345,38 @@ class RemoteWorkerHub:
|
||||
worker = self.pick(label)
|
||||
if worker is None:
|
||||
raise NoWorker(f"no worker labelled '{label}' is attached")
|
||||
return self.run_on(
|
||||
worker,
|
||||
flow,
|
||||
node,
|
||||
source,
|
||||
kwargs,
|
||||
node_id,
|
||||
timeout,
|
||||
run_id=run_id,
|
||||
on_event=on_event,
|
||||
env=env,
|
||||
)
|
||||
|
||||
def run_on(
|
||||
self,
|
||||
worker: RemoteWorker,
|
||||
flow: str,
|
||||
node: str,
|
||||
source: str,
|
||||
kwargs: dict[str, Any],
|
||||
node_id: str,
|
||||
timeout: float,
|
||||
run_id: str = "",
|
||||
on_event: Callable[[dict[str, Any]], None] | None = None,
|
||||
env: dict[str, str] | None = None,
|
||||
) -> Any:
|
||||
"""Run this node on the worker the caller has already settled on.
|
||||
|
||||
The placer holds that machine's cores for the length of the call, so
|
||||
resolving the label a second time here could send the work somewhere
|
||||
else and leave the claim on a machine doing nothing.
|
||||
"""
|
||||
payload = {
|
||||
"op": "run",
|
||||
"call_id": f"{run_id}:{node_id}" if run_id else node_id,
|
||||
|
||||
@@ -8,16 +8,18 @@ seconds. On a GPU the same shape is worse: three processes each preallocating
|
||||
most of the card deadlock at zero utilisation, with nothing failing and nothing
|
||||
to read.
|
||||
|
||||
:class:`ResourceAccountant` is the first half: a node that declares what it
|
||||
needs waits until that much is free, the way it already waits for a worker
|
||||
slot. :func:`derive_env` is the second: what it got is handed to the library as
|
||||
the environment it reads at import, because that is the only moment those knobs
|
||||
are read.
|
||||
:class:`ResourceAccountant` is the first half: the books for one machine, which
|
||||
hand out what is free and take it back. :func:`derive_env` is the second: what
|
||||
a node got is handed to the library as the environment it reads at import,
|
||||
because that is the only moment those knobs are read.
|
||||
|
||||
One accountant is one machine. Which machine a node goes to, and the waiting
|
||||
when none of them has room, is :mod:`fluksio.flow.placement` — the books here
|
||||
never block, so a caller holding several of them can ask each in turn.
|
||||
|
||||
Deliberately cooperative — nothing here is enforced with cgroups or rlimits, so
|
||||
a node that ignores its share is only accounted for, not stopped. That is the
|
||||
same trust the worker pool already extends to node code, and the enforcement
|
||||
half belongs with the scheduler work this is the first step of.
|
||||
same trust the worker pool already extends to node code.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -25,12 +27,9 @@ from __future__ import annotations
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
|
||||
from fluksio.flow.events import EventBus
|
||||
from fluksio.flow.schemas import Resources
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -63,146 +62,92 @@ class Allocation:
|
||||
|
||||
cpus: int = 1
|
||||
gpus: tuple[int, ...] = ()
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Waiting:
|
||||
node: str
|
||||
since: float
|
||||
reason: str
|
||||
ram_mb: int = 0
|
||||
|
||||
|
||||
class ResourceAccountant:
|
||||
"""What is free on this machine, and who is waiting for it.
|
||||
"""The books for one machine: what it holds, and what is free of it.
|
||||
|
||||
A plain condition variable over two counters. Blocking is the whole
|
||||
mechanism: the caller is a node thread that would otherwise be executing,
|
||||
and making it wait is the same backpressure that the worker pool's slot
|
||||
queue already applies — one reason the two must always be taken in the same
|
||||
order, resources first, so neither can be held while waiting for the other.
|
||||
Nothing here blocks. A node that has to wait waits in the placer, which
|
||||
holds one of these per machine and tries each in turn — a lock per machine
|
||||
could not answer "is there room anywhere", and a node waiting inside one
|
||||
machine's books could not be woken by another machine attaching.
|
||||
|
||||
``on_release`` is how it tells the placer something came free. It is called
|
||||
outside this object's lock, deliberately: the placer takes its own lock
|
||||
there, and the two are only ever taken in that one order.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, cpus: int = 0, gpus: int = 0, events: EventBus | None = None
|
||||
self,
|
||||
cpus: int = 0,
|
||||
gpus: int = 0,
|
||||
ram_mb: int | None = None,
|
||||
on_release: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
self.cpus = cpus or machine_cpus()
|
||||
self.gpus = max(0, gpus)
|
||||
self.events = events
|
||||
#: None is memory this machine did not report, which is allowed: it is
|
||||
#: then not accounted rather than accounted as zero, since zero would
|
||||
#: refuse every node that asks for any.
|
||||
self.ram_mb = ram_mb
|
||||
self.on_release = on_release
|
||||
self._free_cpus = self.cpus
|
||||
self._free_gpus = list(range(self.gpus))
|
||||
self._waiting: dict[int, _Waiting] = {}
|
||||
self._ticket = 0
|
||||
self._condition = threading.Condition()
|
||||
self._free_ram = ram_mb or 0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# -- what a caller asks for ------------------------------------------------
|
||||
def fits(self, cpus: int, gpus: int, ram_mb: int = 0) -> bool:
|
||||
"""Whether this machine could ever grant that much, busy or not.
|
||||
|
||||
def _clamp(self, wanted: Resources, node: str) -> tuple[int, int]:
|
||||
"""What can be granted here, which may be less than what was asked.
|
||||
|
||||
A flow written against a sixty-four core box should still run on a
|
||||
laptop. Waiting forever for cores that do not exist is not a smaller
|
||||
machine, it is a hung run.
|
||||
The question a placer asks before it decides to wait: waiting for a
|
||||
card that is merely busy is queueing, and waiting for one the machine
|
||||
does not have is a hung run.
|
||||
"""
|
||||
cpus = min(wanted.cpus, self.cpus)
|
||||
gpus = min(wanted.gpus, self.gpus)
|
||||
if cpus != wanted.cpus or gpus != wanted.gpus:
|
||||
logger.warning(
|
||||
"%s asked for %d cpu(s) and %d gpu(s); this engine has %d and %d",
|
||||
node or "a node",
|
||||
wanted.cpus,
|
||||
wanted.gpus,
|
||||
self.cpus,
|
||||
self.gpus,
|
||||
)
|
||||
return cpus, gpus
|
||||
if cpus > self.cpus or gpus > self.gpus:
|
||||
return False
|
||||
return self.ram_mb is None or ram_mb <= self.ram_mb
|
||||
|
||||
@contextmanager
|
||||
def claim(
|
||||
self, wanted: Resources, node: str = "", run: str = ""
|
||||
) -> Iterator[Allocation]:
|
||||
"""Hold this node's share for as long as it runs."""
|
||||
cpus, gpus = self._clamp(wanted, node)
|
||||
allocation = self._take(cpus, gpus, node, run)
|
||||
try:
|
||||
yield allocation
|
||||
finally:
|
||||
self._give_back(allocation)
|
||||
|
||||
def _take(self, cpus: int, gpus: int, node: str, run: str) -> Allocation:
|
||||
waited_from = time.monotonic()
|
||||
ticket = 0
|
||||
with self._condition:
|
||||
while self._free_cpus < cpus or len(self._free_gpus) < gpus:
|
||||
if not ticket:
|
||||
reason = (
|
||||
f"waiting for {cpus} cpu(s) ({self._free_cpus} free)"
|
||||
if self._free_cpus < cpus
|
||||
else f"waiting for {gpus} gpu(s) ({len(self._free_gpus)} free)"
|
||||
)
|
||||
ticket = self._announce(node, run, waited_from, reason)
|
||||
self._condition.wait()
|
||||
def try_take(self, cpus: int, gpus: int, ram_mb: int = 0) -> Allocation | None:
|
||||
"""Take this much if it is free right now, or answer that it is not."""
|
||||
with self._lock:
|
||||
if self._free_cpus < cpus or len(self._free_gpus) < gpus:
|
||||
return None
|
||||
if self.ram_mb is not None and self._free_ram < ram_mb:
|
||||
return None
|
||||
self._free_cpus -= cpus
|
||||
taken = tuple(self._free_gpus.pop(0) for _ in range(gpus))
|
||||
if ticket:
|
||||
self._waiting.pop(ticket, None)
|
||||
if ticket:
|
||||
logger.info(
|
||||
"%s waited %.1fs for %d cpu(s) and %d gpu(s)",
|
||||
node or "a node",
|
||||
time.monotonic() - waited_from,
|
||||
cpus,
|
||||
gpus,
|
||||
)
|
||||
return Allocation(cpus=cpus, gpus=taken)
|
||||
if self.ram_mb is not None:
|
||||
self._free_ram -= ram_mb
|
||||
return Allocation(cpus=cpus, gpus=taken, ram_mb=ram_mb)
|
||||
|
||||
def _give_back(self, allocation: Allocation) -> None:
|
||||
with self._condition:
|
||||
def give_back(self, allocation: Allocation) -> None:
|
||||
"""Return what an execution held, however it ended."""
|
||||
with self._lock:
|
||||
self._free_cpus += allocation.cpus
|
||||
self._free_gpus.extend(allocation.gpus)
|
||||
self._free_gpus.sort()
|
||||
self._condition.notify_all()
|
||||
|
||||
# -- what it looks like from outside ---------------------------------------
|
||||
|
||||
def _announce(self, node: str, run: str, since: float, reason: str) -> int:
|
||||
"""Say a node is queued, not stuck.
|
||||
|
||||
The failure this exists for looked identical to a hang: a run sitting
|
||||
at `running` for twenty minutes with no error and no output. A node
|
||||
waiting its turn has to say so somewhere a person will look.
|
||||
"""
|
||||
self._ticket += 1
|
||||
ticket = self._ticket
|
||||
self._waiting[ticket] = _Waiting(node=node, since=since, reason=reason)
|
||||
logger.info("%s is %s", node or "a node", reason)
|
||||
if self.events is not None:
|
||||
self.events.publish(
|
||||
{
|
||||
"type": "node_queued",
|
||||
"flow": node.split(".", 1)[0] if node else "",
|
||||
"node": node,
|
||||
"run": run,
|
||||
"detail": reason,
|
||||
"ts": time.time(),
|
||||
}
|
||||
)
|
||||
return ticket
|
||||
if self.ram_mb is not None:
|
||||
self._free_ram += allocation.ram_mb
|
||||
if self.on_release is not None:
|
||||
self.on_release()
|
||||
|
||||
def snapshot(self) -> dict[str, object]:
|
||||
"""What is free and who is waiting, for the workers screen."""
|
||||
with self._condition:
|
||||
free_cpus, free_gpus = self._free_cpus, len(self._free_gpus)
|
||||
"""What this machine holds and what is free of it."""
|
||||
with self._lock:
|
||||
free_cpus, free_gpus, free_ram = (
|
||||
self._free_cpus,
|
||||
len(self._free_gpus),
|
||||
self._free_ram,
|
||||
)
|
||||
return {
|
||||
"cpus": {"total": self.cpus, "free": free_cpus},
|
||||
"gpus": {"total": self.gpus, "free": free_gpus},
|
||||
"waiting": [
|
||||
{
|
||||
"node": entry.node,
|
||||
"reason": entry.reason,
|
||||
"seconds": round(time.monotonic() - entry.since, 1),
|
||||
}
|
||||
for entry in list(self._waiting.values())
|
||||
],
|
||||
"ram_mb": (
|
||||
None
|
||||
if self.ram_mb is None
|
||||
else {"total": self.ram_mb, "free": free_ram}
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -160,6 +160,17 @@ def _has_no_body(
|
||||
return not store.has_node_source(flow, node.id, draft=draft)
|
||||
|
||||
|
||||
def _runs_on_a_worker(node: NodeDef) -> bool:
|
||||
"""Whether this node's body could go to a worker at all.
|
||||
|
||||
Only a node whose source travels can: a connector is an entry point loaded
|
||||
in this process, so a device on one is a field nothing reads. Holding a run
|
||||
for a worker that could never take that node is a run that never starts.
|
||||
"""
|
||||
node_type = NODE_TYPES.get(node.type)
|
||||
return node_type is not None and node_type.has_source
|
||||
|
||||
|
||||
def required_labels(flow: FlowDef) -> list[str]:
|
||||
"""Worker labels this flow cannot run without.
|
||||
|
||||
@@ -171,11 +182,38 @@ def required_labels(flow: FlowDef) -> list[str]:
|
||||
{
|
||||
node.device
|
||||
for node in flow.nodes
|
||||
if node.device and node.device.strip() and node.device_policy == "require"
|
||||
if node.device
|
||||
and node.device.strip()
|
||||
and node.device_policy == "require"
|
||||
and _runs_on_a_worker(node)
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def required_resources(flow: FlowDef) -> dict[str, Any] | None:
|
||||
"""The largest single thing this flow needs a machine to have.
|
||||
|
||||
Dimension by dimension rather than per node, which is deliberately blunt:
|
||||
it answers "could this run start at all", not "in what order". A node that
|
||||
only *prefers* its device is left out — it runs here when nothing carries
|
||||
the label, so it is never what a run is waiting for.
|
||||
"""
|
||||
cpus, gpus, ram = 0, 0, 0
|
||||
device = ""
|
||||
for node in flow.nodes:
|
||||
wanted = node.resources
|
||||
if wanted is None or not _runs_on_a_worker(node):
|
||||
continue
|
||||
cpus = max(cpus, wanted.cpus)
|
||||
gpus = max(gpus, wanted.gpus)
|
||||
ram = max(ram, wanted.ram or 0)
|
||||
if node.device and node.device_policy == "require":
|
||||
device = node.device
|
||||
if not (cpus or gpus or ram):
|
||||
return None
|
||||
return {"cpus": cpus, "gpus": gpus, "ram_mb": ram, "device": device}
|
||||
|
||||
|
||||
#: What a run's output is called from outside it: ``@run:<id>.<output>``.
|
||||
RUN_REF_PREFIX = "@run:"
|
||||
|
||||
@@ -759,6 +797,7 @@ class RunService:
|
||||
no_cache=no_cache,
|
||||
status="queued",
|
||||
labels=required_labels(flow),
|
||||
needs=required_resources(flow),
|
||||
created_at=datetime.now(UTC),
|
||||
actor=actor,
|
||||
idempotency_key=idempotency_key,
|
||||
@@ -854,7 +893,7 @@ class RunService:
|
||||
if not item.run_id:
|
||||
self.queue.ack(item)
|
||||
continue
|
||||
missing = self._missing_labels(item.run_id)
|
||||
missing = self._missing_requirements(item.run_id)
|
||||
if missing:
|
||||
# Left in the queue rather than failed: submitting a run
|
||||
# before turning the GPU box on is a normal way to work, and
|
||||
@@ -870,21 +909,30 @@ class RunService:
|
||||
except RuntimeError:
|
||||
logger.warning("Run %s not started: shutting down", item.run_id)
|
||||
|
||||
def _missing_labels(self, run_id: str) -> list[str]:
|
||||
"""Worker labels this run needs that nothing attached carries."""
|
||||
def _missing_requirements(self, run_id: str) -> list[str]:
|
||||
"""What this run needs that nothing attached can give it yet."""
|
||||
with Session(db_engine) as session:
|
||||
run = session.get(Run, run_id)
|
||||
needed = list(run.labels) if run else []
|
||||
if not needed:
|
||||
return []
|
||||
needs = dict(run.needs) if run and run.needs else None
|
||||
hub = self.controller.remote
|
||||
available = hub.labels() | {w.name for w in hub.workers()} if hub else set()
|
||||
# A node that only prefers its label runs locally instead, so it is not
|
||||
# a reason to hold the run back; that is decided per node at call time.
|
||||
return sorted(set(needed) - available)
|
||||
missing = [f"labelled {label}" for label in sorted(set(needed) - available)]
|
||||
placer = self.controller.placer
|
||||
if placer is not None:
|
||||
# Only a wait something is going to end — a machine that could take
|
||||
# this is being started for it. An ask nothing can grant is cut down
|
||||
# to what is here and runs, so holding the run would be holding it
|
||||
# for something that is not coming.
|
||||
short = placer.satisfiable(needs)
|
||||
if short:
|
||||
missing.append(f"with {short}")
|
||||
return missing
|
||||
|
||||
def _waiting(self, run_id: str, missing: list[str]) -> None:
|
||||
reason = f"Waiting for a worker labelled {', '.join(missing)}"
|
||||
reason = f"Waiting for a worker {' and '.join(missing)}"
|
||||
try:
|
||||
with Session(db_engine) as session:
|
||||
session.exec(
|
||||
|
||||
@@ -60,6 +60,16 @@ class Resources(BaseModel):
|
||||
"runs, which is what keeps two preallocating processes apart."
|
||||
),
|
||||
)
|
||||
ram: int | None = Field(
|
||||
default=None,
|
||||
ge=1,
|
||||
description=(
|
||||
"Megabytes held for the whole execution. Counted against machines "
|
||||
"that said how much they have, and ignored by those that did not — "
|
||||
"which is a machine with nothing to say about memory, not one with "
|
||||
"none."
|
||||
),
|
||||
)
|
||||
env: dict[str, str] = Field(
|
||||
default_factory=dict,
|
||||
description=(
|
||||
|
||||
Reference in New Issue
Block a user