Skip to content
Open
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
27 changes: 27 additions & 0 deletions docs/SWARM-HOST.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,30 @@ wait.
- `reconciliation_required`: `True` when the durable claim is still `active`
but no local runtime exists. A prior process claimed execution and may
still hold it, so no start may be attempted until the receipt is reconciled.

## Turn concurrency

`start` and the `conversation=ConversationOptions(...)` opt-in accept an
optional host turn-concurrency bound. `max_concurrent=None` (the default)
keeps full member concurrency. A strict `int` in `1..member count` (inclusive)
bounds how many members may be inside an actual engine turn at once, never the
member loops themselves. Bounds are validated **before** the engine factory is
invoked or any durable claim exists. A `bool` is rejected even though it is an
`int` subclass, and an out-of-range value raises `HostError`.

For a conversation start the `ConversationOptions.max_concurrent` field takes
precedence when set (not `None`), otherwise the `start` `max_concurrent`
kwarg is used as the fallback.

The limit is runtime-owned and shared per group across every adapter (one-shot
and reactive). It wraps only `engine.run_turn` via `turn_slot`, never a whole
conversation loop, so every member still starts, keeps its claim and observes
pause/stop between turns. A member waiting for a turn permit reports state
`queued` rather than `running`, a pause requested while queued prevents the turn
until resume, a stop requested while queued prevents it permanently, and
cancellation in the queue or inside the turn releases the permit so peers stay
unblocked.

This is a turn-concurrency bound only. It is not a spend or token limit, not an
OS sandbox, and it does not constrain what happens inside engine tools. The
installed code is unchanged by this documentation-only slice.
40 changes: 27 additions & 13 deletions src/exo/core/group_conversation.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,17 +246,22 @@ async def _turn(self, context: MemberContext, member, messages) -> None:
self._outcomes[profile] = ConversationOutcome(
profile, self._turns[profile], "error")
raise ConversationError("group knowledge snapshot unavailable") from e
try:
result = await self.engines[profile].run_turn(
s.TurnSend(session=member.session, text=prompt))
except asyncio.CancelledError:
self._outcomes[profile] = ConversationOutcome(profile, self._turns[profile], "cancelled")
raise
except BaseException as e:
# Isolate provider failures: leave every input unconsumed, record
# the reason and fail this member without retrying anything.
self._outcomes[profile] = ConversationOutcome(profile, self._turns[profile], "error")
raise ConversationError("member turn raised") from e
# Only the engine turn is bounded, never the publish/consume
# bookkeeping and never the whole reactive loop: the runtime
# re-checks pause/stop after granting the permit, so a pause requested
# while this member queued keeps the turn from starting.
async with context.turn_slot():
try:
result = await self.engines[profile].run_turn(
s.TurnSend(session=member.session, text=prompt))
except asyncio.CancelledError:
self._outcomes[profile] = ConversationOutcome(profile, self._turns[profile], "cancelled")
raise
except BaseException as e:
# Isolate provider failures: leave every input unconsumed, record
# the reason and fail this member without retrying anything.
self._outcomes[profile] = ConversationOutcome(profile, self._turns[profile], "error")
raise ConversationError("member turn raised") from e
if result.stop_reason == "interrupted":
self._outcomes[profile] = ConversationOutcome(profile, self._turns[profile], "cancelled")
raise asyncio.CancelledError
Expand Down Expand Up @@ -297,7 +302,8 @@ async def _turn(self, context: MemberContext, member, messages) -> None:


def start_conversation(messages, group: SavedGroup, *, owner: str, adapters,
wake: ConversationWake, prompt: str | None = None):
wake: ConversationWake, prompt: str | None = None,
max_concurrent: int | None = None):
"""Start a reactive ``GroupRuntime`` for a conversation adapter.

The host supplies the already-validated ``adapters.adapters()`` mapping and
Expand All @@ -307,10 +313,18 @@ def start_conversation(messages, group: SavedGroup, *, owner: str, adapters,
go idle after the budget, so there is no self-trigger loop. The wake is
set once after start so initial mailbox input is picked up immediately;
the host must call ``wake.set()`` after every later accepted send.

``max_concurrent`` is an explicit host turn-concurrency bound passed
through to ``GroupRuntime``: ``None`` (the default) keeps full member
concurrency, otherwise a strict ``int`` in ``1..member count`` bounds how
many members may be inside an actual engine turn at once (every loop
still runs; only ``run_turn`` is serialized). The bound is validated
before the runtime is constructed or any claim is taken.
"""
from exo.core.group_runtime import GroupRuntime

runtime = GroupRuntime(messages, group.id, owner=owner, adapters=adapters)
runtime = GroupRuntime(messages, group.id, owner=owner, adapters=adapters,
max_concurrent=max_concurrent)
if prompt is not None:
if not isinstance(prompt, str) or not prompt.strip():
raise ConversationError("initial prompt must be explicit non-empty host text")
Expand Down
7 changes: 5 additions & 2 deletions src/exo/core/group_engine_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,11 @@ async def _run(self, context: MemberContext) -> None:
prompt = GroupKnowledge.decorate_prompt(prompt, snapshot)
except Exception as e:
raise AdapterError("group knowledge snapshot unavailable") from e
result = await self.engines[member.profile].run_turn(
s.TurnSend(session=member.session, text=prompt))
# Only the engine turn is bounded, never the message/consume bookkeeping;
# the runtime re-checks pause/stop after granting the permit.
async with context.turn_slot():
result = await self.engines[member.profile].run_turn(
s.TurnSend(session=member.session, text=prompt))
if result.stop_reason == "interrupted":
raise asyncio.CancelledError
if result.stop_reason != "end" or result.error:
Expand Down
45 changes: 39 additions & 6 deletions src/exo/core/group_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
from exo.core.group_execution import GroupExecutions
from exo.core.group_messages import GroupMessage, GroupMessages
from exo.core.group_runner import MemberStatus
from exo.core.group_runtime import GroupRuntime
from exo.core.group_runtime import GroupRuntime, validate_max_concurrent
from exo.core.groups import GroupStore, SavedGroup

# Trusted host hook: returns one authorized, distinct engine per member profile.
Expand All @@ -63,12 +63,16 @@ class ConversationOptions:
``max_turns`` is the per-member budget of successful engine turns and
``idle_timeout`` bounds each no-input wait (a missed wake degrades to
this poll, never a lost message). Both are validated before the engine
factory is invoked or any durable claim exists. Instances are immutable
and reusable; each conversation start owns its own ``ConversationWake``.
factory is invoked or any durable claim exists. ``max_concurrent`` is the
optional host turn-concurrency bound forwarded to ``GroupRuntime``:
``None`` keeps full member concurrency; a strict ``int`` in
``1..member count`` bounds engine turns, not member loops. Instances are
immutable and reusable; each conversation start owns its own ``ConversationWake``.
"""

max_turns: int = DEFAULT_MAX_TURNS
idle_timeout: float = DEFAULT_IDLE_TIMEOUT
max_concurrent: int | None = None


class GroupHost:
Expand Down Expand Up @@ -162,7 +166,8 @@ def start(self, group_id: str, *,
conversation: ConversationOptions | None = None,
knowledge: bool = False,
max_items: int = DEFAULT_MAX_ITEMS,
max_chars: int = DEFAULT_MAX_CHARS) -> tuple:
max_chars: int = DEFAULT_MAX_CHARS,
max_concurrent: int | None = None) -> tuple:
"""Bind authorized engines and claim one durable execution. No retry.

Stored membership is re-validated against the injected profile set
Expand All @@ -172,6 +177,14 @@ def start(self, group_id: str, *,
inputs and start once. A partial start failure after the claim still
blocks retry by design (GroupExecutions).

``max_concurrent`` is an explicit host turn-concurrency bound passed to
``GroupRuntime``: ``None`` (the default) preserves full member
concurrency; otherwise a strict ``int`` in ``1..member count`` bounds
how many members may be inside an actual engine turn at once — never
the member loops themselves, which keep observing pause/stop between
turns. The bound is validated before the factory is invoked or any
durable claim exists.

Default (no ``conversation``) is the one-shot ``GroupEngineAdapter``
with caller-supplied ``audiences``. With the explicit
``conversation`` opt-in the fixed authorized audiences are derived
Expand Down Expand Up @@ -234,6 +247,20 @@ def start(self, group_id: str, *,
if audiences is not None:
raise HostError("audiences are derived from the stored group mode "
"for a conversation start; do not pass them")
# Turn bound for a conversation start: the options field is the
# more specific declaration and wins when set; the start-level
# kwarg is the fallback. The effective bound is validated here,
# before the factory, any engine or a claim — with the same strict
# rule GroupRuntime applies — so an invalid bound never reaches
# the factory or is silently ignored.
conversation_bound = (conversation.max_concurrent
if conversation.max_concurrent is not None
else max_concurrent)
try:
conversation_bound = validate_max_concurrent(
conversation_bound, len(group.members))
except ValueError as e:
raise HostError(str(e)) from e
engines = dict(self._factory(group) or {})
wake = ConversationWake()
try:
Expand All @@ -246,7 +273,8 @@ def start(self, group_id: str, *,
knowledge=reader,
max_items=bounds[0], max_chars=bounds[1])
runtime = GroupRuntime(self._messages, group.id, owner=self._owner,
adapters=adapter.adapters())
adapters=adapter.adapters(),
max_concurrent=conversation_bound)
runtime.start()
except ValueError as e:
# Nothing started: close the unregistered wake so no waiter
Expand All @@ -262,13 +290,18 @@ def start(self, group_id: str, *,
return runtime.status()
if audiences is None:
raise HostError("one-shot start requires explicit audiences")
try:
bound = validate_max_concurrent(max_concurrent, len(group.members))
except ValueError as e:
raise HostError(str(e)) from e
engines = dict(self._factory(group) or {})
try:
adapter = GroupEngineAdapter(group, engines, audiences=audiences,
knowledge=reader,
max_items=bounds[0], max_chars=bounds[1])
runtime = GroupRuntime(self._messages, group.id, owner=self._owner,
adapters=adapter.adapters())
adapters=adapter.adapters(),
max_concurrent=bound)
runtime.start()
except ValueError as e:
raise HostError(str(e)) from e
Expand Down
4 changes: 4 additions & 0 deletions src/exo/core/group_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ def stop(self, profile: str | None = None) -> None:
self._states[p] = "stopping"
task.cancel()

def stopping(self, profile: str) -> bool:
"""Whether a host stop has been requested for this member (never clears)."""
return self._states.get(profile) == "stopping"

async def wait(self) -> tuple[MemberStatus, ...]:
if not self._started:
raise ValueError("group execution has not started")
Expand Down
Loading
Loading