Skip to content

automaton.pool

WARNING

This documentation is almost entirely "vibe coded"; while a helpful resource for humans and agents to understand this codebase, it should not be considered a source of ground truth in the way documentation normally is, and the user is responsible for verifying that all instructions given here are safe.

automaton.pool

Automaton agent pool: coordinate embarrassingly-parallel agent jobs.

An :class:AgentPool runs a batch of caller-defined agent jobs in parallel and gathers their outputs under a single checkpoint root, with crash-safe, definitive per-job completion markers and no resuming of unfinished agents.

Automaton stays content-free about what a job does: the caller supplies a runner callable that performs the work (typically building a :class:~automaton.sandbox.Sandbox run) and writes artifacts into each job's output_dir.

The concrete :class:MPIAgentPool requires mpi4py (the automaton[mpi] extra). It is imported lazily here so that import automaton.pool works even without mpi4py installed; accessing :class:MPIAgentPool in that case raises a clear :class:ImportError.

AgentPool

AgentPool(jobs: Iterable[Any], runner: Runner, *, checkpoint_root: Path, resume: bool = True, done_check: DoneCheck | None = None, clean_job: CleanJob | None = None, write_marker: bool = True, stop_check: 'StopCheck | None' = None)

Bases: ABC

Abstract coordinator for a batch of parallel agent jobs.

Parameters:

Name Type Description Default
jobs Iterable[Any]

Opaque, caller-defined job payloads. They are canonicalized into :class:AgentJob instances immediately, in the given order; identity (index/job_id) is frozen at this point.

required
runner Runner

Callable that executes a single job and writes its artifacts into the job's output_dir. May return a :class:JobResult or None.

required
checkpoint_root Path

Root directory holding per-job subdirectories and the manifest.

required
resume bool

If True (default), jobs with a valid done marker are skipped; any unfinished job directory is wiped and re-run. If False, all job directories are wiped and every job re-run.

True
done_check DoneCheck

Predicate deciding whether a job is already done (and skippable on resume). Defaults to the built-in :data:DONE.json-marker check (:func:checkpoint.is_done). Supply this to drive completion from your own on-disk records instead.

None
clean_job CleanJob

Callable that prepares a clean slate for a job that is about to run. Defaults to :func:checkpoint.ensure_clean_job_dir (wipe + recreate the job's output_dir). Supply this to match a custom layout.

None
write_marker bool

If True (default), a :data:DONE.json marker is written on success by :meth:execute_job. Set False when the caller's own done_check records completion elsewhere and the built-in marker is unwanted.

True
stop_check StopCheck

Predicate polled by the scheduler between dispatches. When it returns True, no further new jobs are dispatched; jobs already running are left to finish. Defaults to None (never stop), so a pool with no stop check schedules exactly as before.

None
Source code in automaton/pool/base.py
def __init__(
    self,
    jobs: Iterable[Any],
    runner: Runner,
    *,
    checkpoint_root: Path,
    resume: bool = True,
    done_check: DoneCheck | None = None,
    clean_job: CleanJob | None = None,
    write_marker: bool = True,
    stop_check: "StopCheck | None" = None,
):
    self.runner = runner
    self.checkpoint_root = Path(checkpoint_root)
    self.resume = resume
    self._done_check = done_check
    self._clean_job = clean_job
    self._write_marker = write_marker
    self._stop_check = stop_check

    payloads = list(jobs)
    total = len(payloads)
    self._jobs: list[AgentJob] = [
        AgentJob(
            index=index,
            job_id=_canonical_job_id(index, total),
            payload=payload,
            output_dir=checkpoint.job_dir(
                self.checkpoint_root, _canonical_job_id(index, total)
            ),
        )
        for index, payload in enumerate(payloads)
    ]

jobs property

jobs: list[AgentJob]

The canonical, frozen list of jobs (insertion order).

pending_jobs

pending_jobs() -> list[AgentJob]

Return jobs still needing execution, honoring the checkpoint store.

With resume=True, jobs judged done (by :meth:_is_done) are skipped and any unfinished remnant is cleaned. With resume=False, every job is cleaned and returned. Never resume an unfinished agent — clean and start fresh.

Source code in automaton/pool/base.py
def pending_jobs(self) -> list[AgentJob]:
    """Return jobs still needing execution, honoring the checkpoint store.

    With ``resume=True``, jobs judged done (by :meth:`_is_done`) are skipped
    and any unfinished remnant is cleaned. With ``resume=False``, every job
    is cleaned and returned. Never resume an unfinished agent — clean and
    start fresh.
    """
    pending: list[AgentJob] = []
    for job in self._jobs:
        if self.resume and self._is_done(job):
            continue
        self._clean(job)
        pending.append(job)
    return pending

completed_results

completed_results() -> list[JobResult]

Load recorded results for all already-done jobs.

When the built-in marker is used, the recorded :class:JobResult is loaded from it. When a custom done_check reports done but no marker is present (e.g. write_marker=False), a minimal success result is synthesized so the returned batch still covers every done job.

Source code in automaton/pool/base.py
def completed_results(self) -> list[JobResult]:
    """Load recorded results for all already-done jobs.

    When the built-in marker is used, the recorded :class:`JobResult` is
    loaded from it. When a custom ``done_check`` reports done but no marker
    is present (e.g. ``write_marker=False``), a minimal success result is
    synthesized so the returned batch still covers every done job.
    """
    results: list[JobResult] = []
    for job in self._jobs:
        if not self._is_done(job):
            continue
        recorded = checkpoint.load_result(job.output_dir)
        if recorded is None:
            recorded = JobResult(
                job_id=job.job_id,
                success=True,
                output_dir=str(job.output_dir),
            )
        results.append(recorded)
    return results

execute_job

execute_job(job: AgentJob) -> JobResult

Run one job via the runner, writing a done marker on success only.

A runner exception is caught and reported as a failed :class:JobResult; no done marker is written, so the job is retried on a subsequent resume.

Source code in automaton/pool/base.py
def execute_job(self, job: AgentJob) -> JobResult:
    """Run one job via the runner, writing a done marker on success only.

    A runner exception is caught and reported as a failed
    :class:`JobResult`; no done marker is written, so the job is retried on
    a subsequent resume.
    """
    job.output_dir.mkdir(parents=True, exist_ok=True)
    try:
        result = self.runner(job)
    except Exception as exc:  # noqa: BLE001 - report any runner failure
        return JobResult(
            job_id=job.job_id,
            success=False,
            output_dir=str(job.output_dir),
            error=f"{type(exc).__name__}: {exc}",
        )

    if result is None:
        result = JobResult(
            job_id=job.job_id,
            success=True,
            output_dir=str(job.output_dir),
        )
    elif result.job_id != job.job_id:
        # Normalize identity/paths so the runner can't misroute a result.
        result = JobResult(
            job_id=job.job_id,
            success=result.success,
            output_dir=result.output_dir or str(job.output_dir),
            returncode=result.returncode,
            summary=result.summary,
            error=result.error,
        )

    if result.success and self._write_marker:
        checkpoint.write_done(job.output_dir, result)
    return result

run abstractmethod

run() -> list[JobResult]

Execute all pending jobs and return results for the full batch.

Implementations must include results for jobs already completed in a prior run (via :meth:completed_results) so the return value covers the entire job set, not just the ones run this invocation.

Source code in automaton/pool/base.py
@abc.abstractmethod
def run(self) -> list[JobResult]:
    """Execute all pending jobs and return results for the full batch.

    Implementations must include results for jobs already completed in a
    prior run (via :meth:`completed_results`) so the return value covers the
    entire job set, not just the ones run this invocation.
    """
    raise NotImplementedError

AgentJob dataclass

AgentJob(index: int, job_id: str, payload: Any, output_dir: Path)

A single unit of work handed to an :class:AgentPool.

Job identity is canonical and assigned by the pool at ingest time from the job's position in the input sequence; it is stable across resumes.

Attributes:

Name Type Description
index int

Canonical ordinal assigned by insertion order into the pool.

job_id str

Canonical, filesystem-safe identifier derived from :attr:index (zero-padded), used for checkpoint directories, result routing, and skip-on-resume.

payload Any

Opaque, caller-defined description of the work. The pool never inspects this; it is passed verbatim to the runner callable.

output_dir Path

Per-job directory (<checkpoint_root>/<job_id>/) the runner must write all artifacts (workspace, logs, deliverable) into.

JobResult dataclass

JobResult(job_id: str, success: bool, output_dir: str, returncode: int | None = None, summary: dict[str, Any] = dict(), error: str | None = None)

Lightweight, JSON-serializable result of a finished job.

This is the only thing that crosses the MPI boundary from a worker back to the coordinator. Heavy artifacts stay on the (shared) filesystem in the job's :attr:AgentJob.output_dir; here we carry paths as strings and keep summary small.

Attributes:

Name Type Description
job_id str

Canonical job identifier this result corresponds to.

success bool

Whether the runner completed the job cleanly.

output_dir str

String path to the job's output directory (artifacts live here).

returncode int | None

Optional process return code reported by the runner.

summary dict

Small, caller-defined, JSON-serializable summary (e.g. usage totals).

error str | None

Failure detail when success is False.

to_dict

to_dict() -> dict[str, Any]

Return a plain JSON-serializable dict representation.

Source code in automaton/pool/job.py
def to_dict(self) -> dict[str, Any]:
    """Return a plain JSON-serializable dict representation."""
    return {
        "job_id": self.job_id,
        "success": self.success,
        "output_dir": self.output_dir,
        "returncode": self.returncode,
        "summary": self.summary,
        "error": self.error,
    }

from_dict classmethod

from_dict(data: dict[str, Any]) -> JobResult

Reconstruct a :class:JobResult from :meth:to_dict output.

Source code in automaton/pool/job.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> JobResult:
    """Reconstruct a :class:`JobResult` from :meth:`to_dict` output."""
    return cls(
        job_id=str(data["job_id"]),
        success=bool(data["success"]),
        output_dir=str(data["output_dir"]),
        returncode=data.get("returncode"),
        summary=dict(data.get("summary", {}) or {}),
        error=data.get("error"),
    )

JobStatus

Bases: str, Enum

Lifecycle status of a job within a pool run.

SerialAgentPool

SerialAgentPool(jobs: Iterable[Any], runner: Runner, *, checkpoint_root: Path, resume: bool = True, done_check: DoneCheck | None = None, clean_job: CleanJob | None = None, write_marker: bool = True, stop_check: 'StopCheck | None' = None)

Bases: AgentPool

Run all pending jobs sequentially in the current process.

The returned list covers the full job batch (previously-completed plus freshly-run), ordered by canonical job index.

Source code in automaton/pool/base.py
def __init__(
    self,
    jobs: Iterable[Any],
    runner: Runner,
    *,
    checkpoint_root: Path,
    resume: bool = True,
    done_check: DoneCheck | None = None,
    clean_job: CleanJob | None = None,
    write_marker: bool = True,
    stop_check: "StopCheck | None" = None,
):
    self.runner = runner
    self.checkpoint_root = Path(checkpoint_root)
    self.resume = resume
    self._done_check = done_check
    self._clean_job = clean_job
    self._write_marker = write_marker
    self._stop_check = stop_check

    payloads = list(jobs)
    total = len(payloads)
    self._jobs: list[AgentJob] = [
        AgentJob(
            index=index,
            job_id=_canonical_job_id(index, total),
            payload=payload,
            output_dir=checkpoint.job_dir(
                self.checkpoint_root, _canonical_job_id(index, total)
            ),
        )
        for index, payload in enumerate(payloads)
    ]