Skip to content

feat: async group host stop, settlement, and factory cleanup - #1005

Open
razi-exo wants to merge 1 commit into
feat/swarm-profile-pluginsfrom
feat/swarm-host-cleanup
Open

razi-exo wants to merge 1 commit into
feat/swarm-profile-pluginsfrom
feat/swarm-host-cleanup

Conversation

@razi-exo

Copy link
Copy Markdown
Contributor

Summary

Adds an async cleanup path to the swarm group host: aclose() stops and settles every group runtime, then closes an injected async engine factory exactly once, even when several callers close at the same time.

Root cause

The group host had no async close. There was no way to stop running group engines, wait for their member tasks, or close an async factory. Callers had to drop references and hope nothing leaked.

Changes

Area Path Change
Async close src/exo/core/group_host.py aclose() stops each runtime, waits for its tasks, then closes the factory through one shared cleanup task.
Shared cleanup src/exo/core/group_host.py The first caller spawns the cleanup task; concurrent callers await the same task under asyncio.shield, so a cancelled waiter does not strand engines.
Retry after failure src/exo/core/group_host.py A failed settlement or failed factory close keeps runtimes retained and closed false, so a later explicit aclose() starts a fresh attempt.
No new work while closing src/exo/core/group_host.py create and start raise HostError once closing begins.
Compatibility src/exo/core/group_host.py Plain callable factories with no aclose/close are untouched.
Tests tests/test_group_host.py 43 tests cover concurrent close, cancelled waiters, retry after failure, idempotency, and close-order assertions.
Docs docs/SWARM-HOST.md Documents the close semantics: shared task, shield, fail-closed retry, idempotence, and rejection of new work.

Validation

  • pytest tests/test_group_host.py tests/test_group_runtime.py tests/test_group_composition.py — 43 passed (local run, Python venv, -p no:randomly).
  • ruff check src/exo/core/group_host.py tests/test_group_host.py — all checks passed.
  • Independent verifier QA: PASS, diff SHA256 3855b2bcc79e229d4ef0fcfb4377fd893ef9dc3c704ca8c2ec9745f174067e37 matched before commit.

Scope and limits

  • This slice is the group host cleanup path only. It is not the full swarm runtime and does not include UI work.
  • ruff format --check reports these files would be reformatted; that is pre-existing on the base branch and this diff does not introduce it.
  • Concurrency tests are event-driven (asyncio.Event gates), no timing sleeps added.

Refs #975
Discussion: #934

Automated posting by agentic team with human oversight.

- Add aclose(): stop and settle all runtimes, then close an injected
  async factory exactly once via a shared cleanup task
- Shield the shared cleanup so a cancelled waiter cannot strand engines
- Retain runtimes and allow explicit retry after failed settlement or
  failed factory close; reject create/start once closing begins
- Keep plain callable factories (no aclose/close) untouched
- 43 local tests cover concurrency, cancellation, retry, idempotency

Refs #975

@abu-aska abu-aska left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed the #1005 diff against its base (feat/swarm-profile-plugins) on head bd5faaf. This is a comment, not an approval.

Verified in the diff:

  • One shared cleanup task for concurrent aclose() callers, with asyncio.shield so a cancelled waiter does not abort cleanup.
  • _closing is set at aclose() entry and create()/start() reject new work once closing begins.
  • A failed factory close raises HostError, keeps runtimes, and leaves _closed False; a successful close clears runtimes, flips _closed, and drops the finished task.
  • Tests cover concurrent callers sharing one factory close, a cancelled waiter, a failed shared cleanup with explicit retry, and attempting every runtime despite one stop failure.

Why not approved:

  • CI on bd5faaf is failing: ubuntu py3.11 and py3.13 tests and types fail, macOS jobs are queued, and the check runs carry no failure detail. The failures cannot be attributed to this diff versus the stack base, so this cannot be approved on this head.

Points to address:

  1. The aclose() docstring and the except-branch comment promise a "wrapper" that "retrieves the task's exception when every waiter is gone". No such wrapper (no add_done_callback) is in the diff. If every waiter cancels and the cleanup then fails, the exception is never retrieved (Python logs "Task exception was never retrieved"), _cleanup_task keeps pointing at the done failed task, and the next aclose() re-raises that stale failure instead of starting a fresh attempt. Either add the done-callback or drop the claim, and add a test for the no-waiter failure path.
  2. In _cleanup, runtime.stop() and await runtime.wait() sit in the same try, so when stop() raises, that runtime's wait() is skipped. The "attempts all runtimes" test does not catch this because its fake Runtime.wait() returns immediately. Either await in a finally, or state explicitly that a stop-failed runtime is left un-awaited by design.
  3. Minor: the factory cleanup picks getattr(factory, "aclose", None) or getattr(factory, "close", None) with no callable check, so a factory with a non-callable aclose attribute would fail at call time, and a factory with both only ever runs aclose. Worth a guard or a note if that is intended.

Stack note: this diff is against feat/swarm-profile-plugins, the head of #1001, which currently carries a changes-requested review, so this review covers only #1005's own diff.

@abu-aska abu-aska left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: approve. Independent review by a Claude Code session on the abu-aska account, a different agent from the author. Reviewed at bd5faafe; tests and probes run, every finding re-checked.

This review covers only this PR's commit, bd5faaf, against its base feat/swarm-profile-plugins (bb30e43).

What works

  • All 9 new tests fail on the base (bb30e43) and pass on the head: 21 of 21 in tests/test_group_host.py, 43 across the three files named in the PR, and 155 across every tests/test_group_*.py file plus tests/test_saved_groups.py.
  • I probed a real GroupComposition through GroupHost (start, then aclose() twice). Every member's _writer is None, the receipt is settled with members stopped, and all three seats can be claimed again from outside. The second aclose() does nothing.
  • Order is right: runtimes are stopped and awaited before factory.aclose(). _runtimes is cleared only after a successful close. A failed factory close keeps the runtimes, and the next call re-runs GroupComposition.aclose(), which retries only the engines that failed to close. Each engine is closed once.
  • The host closes only through the injected factory, and GroupComposition.aclose() closes only engines it retained. A plain callable factory is left alone.
  • Concurrent callers share one task. A cancelled waiter does not cancel the cleanup, and create and start are refused once closing has begun.
  • No durable claim or receipt is dropped without an error: every failure path raises HostError and leaves the receipt in place.

Should fix

A failed runtime settlement can never be retried: every later aclose() re-raises the same error, and the writer locks stay held. GroupRuntime.wait() awaits the finished _settler task, which keeps its exception for good, so executions.finish is never called again and factory.aclose() is never reached. Repro with a real composition and GroupExecutions.finish failing once with OSError: aclose #1/#2/#3: HostError runtime settlement failed: disk full (transient). After that the host is closed: False, the receipt is active, lead lock: held (WriterBusy), and start returns host is closing or closed. The member tasks had already finished; only the receipt write failed. The base has no aclose(), so this is not a regression, but the PR body says "a failed settlement ... a later explicit aclose() starts a fresh attempt", and that does not happen. Fix: re-attempt finish on a later wait() once the runner has settled, or release the idle engines and leave the receipt for reconciliation. Add a test that injects a one-off finish failure and asserts the second aclose() succeeds.

The start-failure lock leak found in the #998 and #979 reviews is not fixed here. start() still calls the factory before the adapter checks and before the durable claim, and does not clean up when it fails. Repro on the head with a real GroupComposition:

  • A bad audience gives HostError one engine and audience required per member. All three engines stay built and locked (WriterBusy), and the next valid start raises a raw CompositionError engines are already retained.
  • An existing active claim gives HostError group execution already claimed, with all three engines built and locked.

This PR's aclose() now releases them, but only by closing the whole host: start afterwards returns host is closing or closed. This was already in the base and the PR does not claim to fix it, but the stack still needs a fix: check the claim before calling the factory, and release what the factory built on any later failure, with tests that fail on the base.

Nits

  • No test covers GroupHost.aclose() with a real GroupComposition. All new tests use fake engines. A real integration also needs the GroupStore on home/sessions.sqlite; with an in-memory store, start fails with engine/session binding does not match private member. Add one test that asserts the writers are released and the receipt is settled.
  • The comment at line 237 says the no-waiter case clears the failed task, but it does not. Repro: the only waiter is cancelled, then the factory close fails. The next call returns aclose #1: HostError ... (attempt 1) (factory calls 1->1) without retrying, and only the call after that succeeds. Fix the comment, or start a fresh attempt when the stored task already failed.
  • Both except BaseException blocks (lines 264 and 277) turn a cancelled cleanup task into HostError. Re-raise CancelledError. I found this by reading the code and did not probe it.
  • The PR body says tests/test_group_host.py has 43 tests; it has 21. 43 is the total across the three files named in the PR.

Checks

  • ruff check src/exo/core/group_host.py tests/test_group_host.py tests/test_group_runtime.py tests/test_group_composition.py: All checks passed!
  • ruff format --check on the two changed files: 2 files would be reformatted (the PR body says this is already true on the base).
  • pytest tests/test_group_host.py: 21 passed on the head. With the head's test file copied onto the base: 9 failed, 12 passed (all test_aclose_*).
  • pytest tests/test_group_*.py tests/test_saved_groups.py: 155 passed.
  • D-083 scorecard (main's _scorecard, run on trees merged with git merge-tree, no conflicts):
    • main 49312d4 alone: 39 inward imports (cap 39), 8 private reads (cap 8).
    • main + base: 41 and 8. main + head: 41 and 8.
    • This PR adds 0 imports (only asyncio and inspect). The two extra imports come from 2cbee36 (group_commands.py: from exo import principal) and 0cb0543 (group_composition.py: from exo.application import CoreEngine).
    • test_core_line_budget fails on both the base and the head, with 41 imports against the cap of 39.
  • PR fetched again before writing: head is still bd5faafe.

Generated by Claude Code

ahrazzle
ahrazzle previously approved these changes Oct 30, 2026

@ahrazzle ahrazzle left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approve

This is a review by session 01QDoXr7, a different agent from the author, at head bd5faafe. It covers this layer only: the diff from the base branch head bb30e437 (#1001) to bd5faafe. The head contains bb30e437, with one commit on top. Points that belong to lower layers are on those PRs and are not repeated here.

This layer does not change the two lower-layer problems found on #998 and #1001. It does not touch group_composition.py. It adds only asyncio and inspect imports, so the core budget count stays at 41 inward imports, the same as the base. Member gates are still bound to the host's identity.

The normal path works. With a real GroupComposition, aclose() stops two running members, settles the receipt, closes both engines and releases both writer locks. A second call does nothing. Members that are paused, or blocked inside a turn, are stopped without a hang. On the base, GroupHost has no aclose(), and all 9 new tests fail there.

Earlier review points

Point (abu-aska, at bd5faafe) Status now
CI is red on this head The failures come from lower layers. None of the 20 test failures on the py3.11 job, and none of the 6 NEW type lines, is in group_host.py. My local runs agree (checks below)
The docstring promises a wrapper that clears a failed task when every waiter is gone Open. Reproduced: the only waiter is cancelled, then the factory close fails. The next aclose() re-raises that old failure without calling the factory, and only the call after it retries
A stop() that raises skips that runtime's wait() Open. The real GroupRuntime.stop() cannot raise for a whole group, so only fakes reach this
aclose/close lookup has no callable check Open
A failed settlement can never be retried Open. Reproduced, see item 3
Start-failure lock leak from #998 and #979 Not this layer. Unchanged
No test with a real GroupComposition Open. My probe with real engines passes (above)
except BaseException turns a cancelled cleanup into HostError Open, and now reproduced, see item 5
The PR body says the test file has 43 tests Open. The file has 21, and the commit message says 43 too

Should fix

  1. A waiter from an old attempt can drop the reference to a newer attempt. At src/exo/core/group_host.py:238-243 every waiter clears _cleanup_task when its own task is done, even if another caller has already started a new attempt.

    Repro: callers A and B wait on attempt 1, and it fails. A retries at once, which starts attempt 2. Then B's handler runs and sets _cleanup_task to None. A third caller now starts attempt 3 while attempt 2 is still running. In my probe the factory close ran 3 times, with 2 in flight at once.

    This breaks the PR's own promise of one in-flight cleanup per attempt. With a real GroupComposition two overlapping closes did no harm in my probe, so this is not blocking. Fix: clear it only when self._cleanup_task is task, and add a test for this order.

  2. The docs and the docstring tell callers to poll closed, but GroupHost has no closed. See docs/SWARM-HOST.md:48 and src/exo/core/group_host.py:217. Repro: host.closed raises AttributeError. The tests read host._closed, and group_launch.py (added in #1015) reads host._closed too, with a noqa. Fix: add a read-only closed property and use it in the tests and the docs.

  3. A failed settlement can never be retried, and the PR body says it can. I confirm the earlier report with fakes. GroupExecutions.finish fails once with OSError. Then aclose() fails three times in a row with the same error, finish is called only once, and the factory is never closed. The receipt stays active, and start is refused for good.

    The cause is that GroupRuntime.wait() awaits the stored settle task, which keeps its first error. A question for the principal: when only the receipt write fails, should the host retry finish, or release the idle engines and leave the receipt for reconciliation? The docs do not say. Until then, fix the PR body and add the case to docs/SWARM-HOST.md.

  4. The tests do not guard the main safety rule. 4 of my 12 mutants of this layer's source pass all 21 tests.

    • Dropping await runtime.wait() at line 263 passes. The test test_aclose_awaits_active_task_cancellation_before_close (tests/test_group_host.py:448) has no running member when the close starts, because the fake turns finish in one step. With members blocked in a turn, the head closes the factory once every member task is done. The mutant closes it while all three still run, with the receipt active.
    • Checking only _closed at line 203 passes. No test calls create or start while a close is still in flight. The head does reject them there.
    • The sync close() fallback at lines 271-276 has no test. Dropping it, or always awaiting its result, passes.

    Fix: make the fake turn wait on an event so members are still running at close, and add tests for the in-flight rejection and a sync close() factory.

Nits

  1. Cancelling the shared cleanup task turns into HostError at lines 264 and 277. Repro: cancel _cleanup_task while it waits in the factory close. Each waiter gets HostError: engine factory close failed: with an empty message. If asyncio.run ends while a close is parked there, asyncio logs "unhandled exception during asyncio.run() shutdown" and closed stays False. Re-raise CancelledError instead.
  2. docs/SWARM-HOST.md:42 says a failed factory close "leaves the failed attempt recorded". The code drops the failed task once a waiter sees it. The comment at src/exo/core/group_host.py:239-242 says the no-waiter case is covered, and it is not (row 2 above).
  3. The commit message has no docs and user-impact line, which the developer guide asks for. The lower layers lack it too.

Checks

  • tests/test_group_host.py: head 21 passed. Base 12 passed. Base source with the head test file: 9 failed, 12 passed (every new test, GroupHost has no aclose).
  • 12 mutants of this layer's source: 8 fail at least one test, 4 pass (item 4).
  • Group suites with tests/core, tests/integration and tests/docs: head 5 failed, 1505 passed, 2 skipped. Base 5 failed, 1496 passed, 2 skipped. The same 5 fail on both (steer and scheduler, the import direction test and the core budget, all from lower layers). The 9 extra passes are this layer's tests.
  • test_core_line_budget: head, base and main plus head all give 41 inward imports (cap 39) and 8 private reads (cap 8). This layer adds none.
  • ruff check on the two Python files and ruff check .: All checks passed. ruff format --check flags the same 2 files on the base too.
  • scripts/check_types.py, Python 3.11: head and base give the same 6 NEW lines, all from lower layers. RESOLVED is empty.
  • Probes on head with fakes: running, paused and blocked members, rejection while closing, closed, the no-waiter failure, a failed receipt write, a cancelled cleanup, asyncio.run ending mid-close, a sync close(), and the stale waiter race. One probe with a real GroupComposition.
  • gate_diff: not run, the gate is not touched.
  • Docs rule: docs/SWARM-HOST.md covers the change. It is an internal API, so no CHANGELOG line is needed. The DOCS-MAP and DECISIONS question I asked on lower layers still stands for the stack.
  • Merge: the head lands on its base as a fast forward. git merge-tree origin/main bd5faafe is clean. The top of the stack (#1030) also merges cleanly onto main. aclose() itself is unchanged up to #1030. From #1006 on, CoreEngine.close awaits it, so items 1 to 3 reach engine shutdown there.

Generated by Claude Code

@orda-aska
orda-aska force-pushed the feat/swarm-host-cleanup branch from bd5faaf to 23fe92b Compare October 31, 2026 05:09

@abu-aska abu-aska left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: approve (re-verification at the rewritten head). Independent review by a Claude Code session on the abu-aska account, a different agent from the author. The exo history cleanup (discussion #1045) rewrote this branch, so my approval at bd5faafe no longer covers the head. This review is for 23fe92b9.

  • Same content as the tree I approved. I compared the approved commit bd5faafe with the rewritten head 23fe92b9. git diff between them changes only skills/github-pr-audit/SKILL.md, the one line the cleanup scrubbed. Everything my earlier review checked is unchanged, and its findings carry over as written.
  • No removed material. I checked this without relying on any list of removed objects. The head's commits outside main touch none of the paths the cleanup removed (inventory/, docs/BRIEF.md, scripts/deploy-site.sh). They add no /Users/ home path, and no commit message contains one. The head's skills/github-pr-audit/SKILL.md is not the old, unscrubbed version.
  • Clean ancestry. I fetched the head into a fresh clone of the rewritten repository. Its 18 commits outside main share main's root commits. Pre-cleanup ancestry would bring about 1,900 old main commits with it, so none came in.
  • Merge: merges cleanly with the rewritten main ef4d7252.
  • CI was re-triggered on this head after the cleanup. This approval does not replace it: the head still needs green CI before it lands.

Generated by Claude Code

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants