Skip to content

fix(ep): never drive a factor search through a multiprocessing pool; fail fast on a dead Nautilus worker #1608

Closed

Description

@Jammy2211

Overview

Expectation propagation (EP) must never drive a per-factor Nautilus search through a Python multiprocessing pool. RAL job 342351_0 (the slope_hierarchy_scale EP arm, submitted --use_cpu) hung for 27 h on a 10-core allocation with 16 s of CPU and zero samples: two forked likelihood workers segfaulted in _ctypes seconds after the fork, Pool._maintain_pool silently replaced them, and because multiprocessing never re-issues a dead worker's in-flight task the Pool.map inside nautilus.Sampler.add_samples could never return. Nothing reached stderr. Human ruling (2026-09-09): EP is not combined with Python multiprocessing at all — per-factor searches run serially (pool=None), and parallelism comes from a vectorised JAX likelihood.

Two defects, both in PyAutoFit, one PR (the prompt's witness needs both):

  1. EP silently forks. AbstractSearch.optimise (the EP factor-optimiser entry) calls the search's ordinary fit, so a search built with number_of_cores>1 and a non-JAX analysis takes Nautilus.fit_multiprocessing and forks a pool per factor step.
  2. A dead pool worker hangs every multi-core Nautilus fit, not just EP. fix(nautilus): serial bound training + no per-task Fitness pickling (#1547) #1548 made bound training serial but left likelihood evaluation (_LikelihoodWorkerPool.map) unguarded: a vanished worker is replaced, its task is lost, and map blocks to the wall clock.

Plan

  • Make the EP factor-optimiser path refuse a multiprocessing search loudly: AbstractSearch.optimise raises a clear SearchException when number_of_cores > 1, naming the ruling and the two supported alternatives (number_of_cores=1, or a use_jax=True analysis for vectorised parallelism). No pool is ever forked under EP.
  • Log, at EP factor-step time, which likelihood path the factor search takes (serial vs JAX-vectorised), so a run's log shows where its parallelism comes from.
  • Give _LikelihoodWorkerPool.map a dead-worker watchdog: dispatch with map_async, poll with a short timeout, and on each poll compare the pool's live worker PIDs against the set captured at construction. A PID that has vanished means a worker died and its task was lost, so terminate the pool and raise a diagnosable SearchException within seconds instead of blocking forever.
  • Regression tests: EP with a multi-core search raises (and forks nothing); EP with number_of_cores=1 runs unchanged; a real fork pool whose worker is SIGKILLed mid-map raises within seconds; the healthy-pool tests from Nautilus 1-core fits deadlock under JAX: fork Pool(1) bypasses nautilus's serial-pool guard (release-integrate RED) #1442/fix(nautilus): serial bound training + no per-task Fitness pickling (#1547) #1548 still pass.
  • Update the Nautilus number_of_cores docstring and autofit/graphical/README.md with the EP-never-forks rule.
  • File the phase-2 follow-up separately: the slope_hierarchy_scale scripts/ep.py use_jax = not use_cpu conflation (JAX-on-CPU is unreachable through --use_cpu) is that project's script, not PyAutoFit's, and gets its own Mind prompt.
Detailed implementation plan

Affected Repositories

  • PyAutoFit (primary, only)

Work Classification

Library

Branch Survey

Repository Current Branch Dirty?
./PyAutoFit main (e331e33) clean

Remote heads: main, claude/slowest-ci-tests-s81dza, experiment/jax-vmap-jit-ordering — none touch EP or the Nautilus pool.

Suggested branch: feature/ep-no-multiprocessing-pool
Worktree root: ~/Code/PyAutoLabs-wt/ep-no-multiprocessing-pool/ (created by /start_library; a web session works on the clone directly)

Implementation Steps

Step 1 — EP refuses a multiprocessing search (autofit/non_linear/search/abstract_search.py, AbstractSearch.optimise)

  1. At the top of optimise, after the factor-type check, add:
    • if self.number_of_cores > 1: raise exc.SearchException(...) with a message that states the 2026-09-09 ruling (EP never runs a factor search through a Python multiprocessing pool: a forked worker that dies is silently replaced and its task never re-issued, so Pool.map hangs to the wall clock — RAL 342351_0), and the two fixes: build the factor search with number_of_cores=1, and get parallelism from Analysis(use_jax=True) (Nautilus then takes fit_x1_cpu with vectorized=True, no pool).
    • This is deliberately a refusal, not a silent downgrade: number_of_cores is user intent, and the ruling wants the intent corrected at the call site. The check lives in the EP entry point so it covers every search type (Nautilus, dynesty, emcee, zeus, LBFGS), not just Nautilus.
  2. Log one logger.info per factor step naming the path: "EP factor search runs serially (number_of_cores=1); parallelism from JAX vectorisation: <analysis._use_jax>".
  3. ParallelEPOptimiser (graphical/expectation_propagation/optimiser.py:718) is EP's own explicit opt-in pool across factors (fork_context().Pool(n_cores-1)), not the per-factor path that hung. Leave it as-is in this PR; add a docstring note that it is subject to the same dead-worker hang and that the ruling's recommended configuration is EPOptimiser + JAX likelihood. (Deprecation is a separate decision.)

Step 2 — dead-worker watchdog (autofit/non_linear/search/nest/nautilus/search.py, _LikelihoodWorkerPool)

  1. In __init__, capture self._worker_pids = {p.pid for p in pool._pool} and accept a poll_interval: float = 1.0 (module constant, monkeypatchable in tests).
  2. Replace map with:
    result = self._pool.map_async(likelihood_worker, iterable)
    while True:
        try:
            return result.get(timeout=self._poll_interval)
        except multiprocessing.TimeoutError:
            self._check_workers_alive()
  3. _check_workers_alive(): live = {p.pid for p in self._pool._pool if p.exitcode is None}; dead = self._worker_pids - live. If dead is non-empty: self._pool.terminate() and raise exc.SearchException naming the dead PIDs and their exitcodes (a negative exitcode is the signal number — -11 reads as SIGSEGV), explaining that multiprocessing.Pool replaced the worker but never re-issued its task, and pointing at number_of_cores=1 / JAX as the fix. Using the original PID set rather than the worker count is what makes a _repopulate_pool replacement detectable (the count is restored; the PID is not).
  4. Keep __exit__ semantics; terminate() on the error path is idempotent.

Step 3 — tests

  • test_autofit/graphical/test_ep_no_multiprocessing.py (new):
    • test__ep_refuses_multi_core_search: build the two-factor Gaussian graph from test_autofit/graphical/gaussian/conftest.py, optimiser = af.DynestyStatic(maxcall=5, number_of_cores=2); monkeypatch autofit.non_linear.parallel.context.fork_context (and the fork_context names imported into dynesty/search/abstract.py and nautilus/search.py) to raise AssertionError("must not fork"); assert pytest.raises(af.exc.SearchException, match="multiprocessing") from factor.optimise(...) / search.optimise(factor_approx).
    • test__ep_single_core_search_unchanged: same graph with number_of_cores=1 runs to a result (existing behaviour).
  • test_autofit/non_linear/search/nest/test_nautilus.py (extend):
    • test__likelihood_pool_raises_when_worker_dies: real fork Pool(2) built with initialize_worker(likelihood) where the likelihood sleeps ~0.2 s per call; start wrapper.map on a 40-item iterable in a thread, os.kill(pool._pool[0].pid, SIGKILL) after the first results arrive, assert SearchException is raised in under ~5 s and its message names the dead PID and a negative exitcode. Set _LikelihoodWorkerPool poll interval to 0.1 s via monkeypatch. Skip if fork is unavailable.
    • Existing test__likelihood_pool_does_not_pickle_fitness, test__multi_core_passes_serial_sampler_pool, test__single_core_builds_no_pool must still pass (the StubPool in the second gains a _pool = [] attribute).
  • Run: python -m pytest test_autofit/non_linear/search/nest/test_nautilus.py test_autofit/graphical -q serially, then the full test_autofit/. Baseline on clean main (e331e33, 2026-09-11): test_autofit/graphical 279 passed serially; under -n auto 17 of them fail on untouched main (a parallel-runner artefact, not a defect), so the EP suite is judged serially.

Step 4 — docs

  • Nautilus.__init__ docstring, number_of_cores: add "Not used by EP factor searches, which refuse it; see AbstractSearch.optimise."
  • autofit/graphical/README.md: one paragraph under the optimisation section stating the rule and pointing at the JAX path.

Key Files

Key trade-offs

  • Refuse vs force-serial. Forcing number_of_cores=1 in place would mutate a search object the user reuses (the same search instance is re-entered per factor by optimise) and would hide the intent mismatch; a loud refusal is what the ruling asks for and is one line to fix at the call site. The witness accepts either.
  • PID-set watchdog vs stack inspection. The prompt notes a replacement worker is distinguishable only by a _maintain_pool frame in its stack; comparing live PIDs against the construction-time set gives the same signal without py-spy, in pure stdlib, at a 1 s poll.
  • Cost. Under a non-JAX likelihood the EP factor search is now single-core by construction; that is the ruling's accepted price, and the JAX path is where parallelism lives.

Prior art

Original Prompt

Click to expand starting prompt

EP must never drive Nautilus through a Python multiprocessing pool

Type: bug
Target: PyAutoFit
Repos:

  • PyAutoFit
    Difficulty: large
    Autonomy: supervised
    Priority: high
    Status: formalised
    Consequence: judge
    Witness: an EP fit requesting number_of_cores>1 either runs serially or refuses loudly (never silently forks a pool), demonstrated by the slope_hierarchy_scale EP arm getting past its first factor_step; plus a regression test that kills a pool worker mid-map and asserts the search raises a diagnosable error within seconds instead of blocking forever.
    Review-minutes: 25
    Unattended: ready

EP must never drive Nautilus through a Python multiprocessing pool

Witness: an EP fit requesting number_of_cores>1 either runs serially or refuses loudly (never silently forks a pool), demonstrated by the slope_hierarchy_scale EP arm getting past its first factor_step; plus a regression test that kills a pool worker mid-map and asserts the search raises a diagnosable error within seconds instead of blocking forever.

Ruling (human, 2026-09-09): expectation propagation should not be combined with Python multiprocessing at all. EP's per-factor Nautilus searches should run with pool=None / number_of_cores=1, and parallelism should come from a vectorised JAX likelihood, which bypasses Pool.map entirely.

Evidence that forced this. RAL job 342351_0 (slope_hierarchy_scale EP arm) hung for 27 hours consuming 16 seconds of CPU across a 10-core allocation, and was cancelled having produced zero samples. py-spy showed the parent blocked in multiprocessing/pool.py:367 map -> :768 get -> :765 wait, reached via _LikelihoodWorkerPool.map (autofit/non_linear/search/nest/nautilus/search.py:61) <- nautilus/sampler.py:869 evaluate_likelihood <- nautilus/sampler.py:1119 add_samples <- the EP optimiser's factor_step <- ep.py:91. Two of the ten forked workers (PIDs 924667/924668) had segfaulted inside _ctypes.cpython-312 within seconds of the fork ('segfault at 116cd5b08 ... error 4 in _ctypes.cpython-312-x86_64-linux-gnu.so'). Pool._maintain_pool forked replacements and restored the count to ten, but multiprocessing never re-issues a dead worker's in-flight task, so the map() could never return. Nothing reached stderr, because a signal death bypasses Python's exception machinery: every log looked healthy.

Root cause of the path being taken at all: the run was submitted --use_cpu, and scripts/ep.py:58 reads 'use_jax = not use_cpu'. That flag conflates 'run on the CPU partition' with 'disable JAX', so choosing CPU silently disabled the vectorised likelihood and dropped the fit onto the multiprocessing path. JAX-on-CPU, which needs no pool, is unreachable through that flag.

Scope, separable into phased PRs:

  1. Primary: EP never constructs a process pool. Force pool=None on the EP factor-optimiser path, or refuse number_of_cores>1 with a clear error rather than forking silently. Note the cost to weigh: with a non-JAX likelihood this makes each factor's search single-core, so the serial guard only pays off alongside the JAX path.
  2. Confirm EP drives a vectorised JAX likelihood end to end (the machinery exists: use_jax is threaded through make_factor_graph), so parallelism comes from vectorisation rather than processes.
  3. Residual, wider than EP: the dead-worker deadlock affects every multi-core Nautilus fit, not just EP, including per-lens fits and any user running number_of_cores>1. A vanished worker should fail loudly within seconds instead of hanging to the wall clock. Worker count is not a usable health check, because _repopulate_pool refills it; a replacement is distinguishable only by a _maintain_pool frame in its stack. PyAutoFit#1548 is present in the running mirror and does not cover this: it made neural-bound training serial and swapped in likelihood_worker, leaving ordinary likelihood evaluation unguarded. Prior art: PyAutoFit#1439, fix: single-core Nautilus fits build no pool (release-integrate corrective, #1442) #1443, fix(nautilus): serial bound training + no per-task Fitness pickling (#1547) #1548.

Raw py-spy dumps for all eleven processes and the dmesg segfault lines were captured while the job was still live.

Activity

  1. added a commit that references this issue on Sep 11, 2026
  2. Jammy2211 commented on Sep 11, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped

    Summary

    • AbstractSearch.optimise (the EP factor-optimiser entry, so every search type) refuses number_of_cores > 1 with a SearchException naming the search, the value and the two fixes (number_of_cores=1; Analysis(use_jax=True)). A refusal, not a silent downgrade. One log line per factor step says where parallelism comes from.
    • _LikelihoodWorkerPool.map dispatches via map_async and polls; on each poll it checks the exit code of every worker Process captured at construction, so a worker multiprocessing.Pool silently replaced raises a diagnosable SearchException (PID + signal) within seconds instead of hanging every multi-core Nautilus fit.
    • Tests: EP refusal with forking blocked; EP single-core unchanged; SIGKILLed worker raises in < 5 s with -9 in the message; healthy map returns in order. CI green on nojax / 3.12 / 3.13 / docs.

    Follow-ups filed in PyAutoMind

    • Phase 2 (science side): draft/bug/graphical_ep/ep_use_cpu_flag_disables_jax.md — the slope_hierarchy_scale script derives use_jax = not use_cpu.
    • draft/bug/autofit/ep_test_suite_is_not_xdist_safe.md — test_autofit/graphical shares one output directory under -n auto.
    • draft/bug/autofit/dynesty_single_core_path_still_builds_a.md — Dynesty still enters a Pool(1) at one core.
    • ParallelEPOptimiser removal — being filed now as its own refactor.

    Session: web (issue, PR and merge via the GitHub MCP surface; implementation delegated to a subagent).


    Generated by Claude Code

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions