Skip to content

Execution Backends#

oxo-flow computes a fully determined static plan — topological order, parallel groups, per-rule resource declarations — before any execution begins. Execution backends do not re-understand the DAG: they map that single plan onto a scheduler API. Because plan computation, invalidation, and the checkpoint format stay single-implementation, the dry-run preview is valid for every executor, and local and remote execution share the same checkpoint semantics.

.oxoflow file ──► wildcard expansion ──► static plan ──┬─► LocalExecutor (run)
                (single implementation)               └─► ExecutorBackend (scheduler)

The static plan#

oxo_flow_core::backend::ScheduledPlan is the executor-agnostic plan:

  • order — topological execution order (WorkflowDag::execution_order),
  • groups — parallel groups (WorkflowDag::parallel_groups),
  • rules — one ScheduledRule per schedulable instance: the expanded rule (single source for script rendering and resource directives), the environment-wrapped shell command with cd <workdir> folded in, the workdir, instance-level dependencies, and {config.x} bindings.

ExecutorBackend trait#

#[async_trait::async_trait]
pub trait ExecutorBackend: Send + Sync {
    fn name(&self) -> &'static str;
    fn render_script(&self, rule: &ScheduledRule) -> Result<String>;
    async fn submit(&self, script_path: &Path) -> Result<String>;
    async fn poll(&self, job_ids: &[String]) -> Result<HashMap<String, BackendJobStatus>>;
    async fn cancel(&self, job_id: &str) -> Result<()>;
    async fn logs(&self, job_id: &str) -> Result<String>;

    // Provided methods (defaults shown):
    fn render_array_script(&self, rule: &Rule, cmd_dir: &str, count: usize)
        -> Result<String>  // default: Err "does not support job arrays"
        — render one ARRAY script for `count` same-rule instances whose
          per-index commands live in `cmd_dir`; backends without array
          support error and the driver falls back to per-job submission
    async fn terminal_status(&self, job_id: &str) -> Option<TerminalRecord>
        // default None — terminal record from the scheduler's accounting
        // store; None keeps the job in flight
    fn polls_elements_directly(&self) -> bool
        // default false — true when poll resolves individual array
        // elements: SLURM's `{base}_{index}` ids, Kubernetes Indexed Job
        // completion indexes, AWS Batch child job ids, GCP Batch task
        // indexes. PBS/SGE/LSF list only the base id through this
        // adapter's invocations (issue #136 H4)
}

The first implementation, ClusterExecutor (SLURM/PBS/SGE/LSF, extended by k8s and the AWS/GCP/Tencent Batch backends), renders scripts with the existing directive generator (core/cluster.rs, unchanged) and performs real submission and tracking:

  • submit — sbatch --parsable <script> for SLURM (bare job id on stdout, fixing the --dependency=afterok:Submitted batch job N trap the old wrapper script had); PBS prints a bare id; SGE/LSF ids are parsed out of their submission sentences. All id capture shares one helper (parse_job_id), as does status-line parsing (parse_status_line), including array elements like 12345_12.
  • poll — squeue -j <ids> --noheader -o "%i|%T" and per-backend equivalents.
  • cancel / logs — scancel / scheduler records (sacct and equivalents; cluster logs additionally falls back to scontrol show job on SLURM).

BackendDriver#

oxo_flow_core::backend::driver::BackendDriver executes a ScheduledPlan through a backend. It never decides what to run — the caller computes the will-run set from the shared invalidation predicates (the same ones the dry-run preview uses). The driver:

  • submits waves of at most max_submitted in-flight jobs (pending + running),
  • polls at poll_interval and settles terminal jobs into JobRecords — the same record type the local executor produces, so checkpoint recording is identical in shape,
  • propagates failures: dependents of a failed rule are skipped (blocked by failed upstream dependency),
  • cancels everything in flight on submit errors and poll timeouts,
  • writes a greppable run directory: events.jsonl (append-only, source of truth) and jobs/<rule>/ with job.sh, job.id, and status.json. Content-addressing stays inside the checkpoint — never in paths,
  • supports checkpoint re-entry via two hooks (on_checkpoint, merge) so dynamically discovered instances execute in the same run (see Checkpoint re-entry below).

DriverConfig supplies the knobs, with these defaults (this table is the single source for driver defaults — other pages link here instead of restating it):

Field Default Meaning
max_submitted 50 In-flight jobs (pending + running) before submissions top up as slots free
max_array_size 1001 Scheduler array limit — larger groups are chunked into several arrays
no_arrays false Set to submit every instance as its own job
poll_interval 5s Delay between scheduler polls
poll_timeout None Overall wall-clock budget; unset means run until terminal states

A [cluster] profile block overrides max_submitted, max_array_size, and poll_interval (see Cluster submission); no_arrays, poll_timeout, and the defaults themselves are driver-internal.

Testing without a cluster#

The workspace ships a mock SLURM scheduler at tests/fixtures/mock-scheduler/ — shell shims (sbatch, squeue, scancel, sacct) that execute submitted scripts for real in the background and record job state under $MOCK_SCHEDULER_DIR. Integration tests construct a ClusterExecutor with .with_scheduler_dir(...) and .with_env("MOCK_SCHEDULER_DIR", ...) to run whole workflows through the driver in CI without any cluster. The shims reproduce two real-scheduler behaviours worth knowing about: sbatch returns immediately (the job's output pipe is fully detached) and failing jobs still record a terminal state.

The P1 acceptance tests (tests/cluster_backend.rs) assert the core claim:

  • local execution and backend execution of the same workflow produce the same checkpoint semantics (completed sets, benchmarks, input manifests) and identical outputs,
  • the dry-run preview's will-run set equals the set the driver submits,
  • poll timeouts cancel in-flight jobs.

run --profile <NAME> now drives the backend when the profile carries a [cluster] block (see Cluster submission). Its submission set is the dry-run preview's will-run set unioned with the run's force_rules — the same bypass set the local executor receives, since run has already applied and persisted its invalidation analysis by the time the cluster path runs. tests/cluster_run_profile.rs pins that combination to what the local executor actually executes from identical state.

Backend maturity (details and audit links are indexed in docs/superpowers/README.md):

Backend Status Live evidence Gaps
Kubernetes live-qualified for the tested scope single-node k3s (2026-11-24) and two-node k3s + NFS (2026-11-26; Indexed array per element, resource-forced placement, provenance verify 3/3) PVC provisioning, HA, cloud volumes, image + multi-node volume, cancel reconciliation, crash recovery; re-attach is mock-tested only
Tencent Batch Prototype 2026-11-26: named compute environment submit reached SUCCEED; poll, DescribeTaskLogs, and TerminateJob verified no live array or artifact-pull campaign
AWS Batch Prototype CLI wrapper, mock/wire tests only live campaign not run (no credentials); #1390 closed as not planned
GCP Batch Prototype CLI wrapper, mock/wire tests only live campaign not run (endpoint unreachable); #1390 closed as not planned
SLURM / PBS / SGE Supported point-in-time real-scheduler matrix (OpenPBS 23.06, SoGE 8.1.9; 2026-09) not re-run per commit
LSF Experimental none community edition IBMid-gated; semantics cross-checked against IBM's bsub

Per-element settlement is implemented for every backend that exposes element-level status (SLURM {base}_{index} ids, Kubernetes Indexed completion indexes, AWS Batch child ids, GCP Batch task indexes). PBS/LSF/SGE and Tencent arrays are polled by the array base id; their element records name the aggregate verdict's provenance in skip_reason and invent no base-level exit code or resource numbers. Missing accounting data is unknown (exit_code: null), never 0.

The cloud backend family (AWS/GCP/Tencent Batch) is prototyped behind CLI wrappers; AWS Batch and GCP Batch are blocked at that layer and their live campaign prerequisites are in cloud-live-campaigns-todo-2026-11-26.md. See the audit ledger before describing any backend as production-ready.

Freshness note: the real-scheduler matrix is a point-in-time campaign. Before citing it against current behavior, re-run scripts/real-cluster-matrix/ locally (its runners propagate case failures).

Accounting is read once per job as it settles, not once per poll, and feeds both the run directory and the checkpoint benchmarks — see what a finished job records. Backends report only what their store proves: SLURM reads exit code, elapsed time, peak RSS and total CPU from sacct (peak memory comes from the step rows, which is where SLURM puts it — the allocation row leaves it blank), PBS and SGE report the equivalent resources_used / ru_* fields, and LSF reports state alone.

Resource accounting coverage#

The normalized oxo-flow.resource-ledger/v1 document (oxo-flow report --resource-ledger) reads the cluster path's persisted resource_usage records. Each metric is Option: a backend that cannot prove a value leaves it unknown, and every record carries a ResourceSource naming the backend, tool, and raw fields — never a synthetic zero.

Field local SLURM (sacct) PBS (qstat -x) SGE (qacct) LSF (bacct) SLURM fallback (scontrol) k8s / AWS / GCP / Tencent
wall / elapsed sampled ElapsedRaw/Elapsed resources_used.walltime ru_wallclock — — —
CPU seconds sampled (rule process subtree) TotalCPU (max over step rows) resources_used.cput cpu — — —
peak RSS bytes sampled subtree MaxRSS (max over step rows) resources_used.mem ru_maxrss — — —
I/O bytes Linux /proc/<pid>/io AveDiskRead/AveDiskWrite — — — — —
scheduler wait — Submit→Start — — — — —
nodes / cores — NNodes / AllocCPUS — — — — —
exit code process status ExitCode Exit_status exit_status state only ExitCode via the poller, not accounting
provenance sysinfo + proc sacct + raw fields qstat -x + raw fields qacct + raw fields bacct note scontrol note none note

"—" means the adapter does not parse that value from the store; the ledger renders it as unknown (absent), not as a measured zero. LSF's bacct columns vary too much between versions to parse blind, and the cloud backends expose no accounting API in this adapter at all. A baseline array record on PBS/LSF/SGE has its per-process numbers withdrawn (the aggregate is not one element's measurement), so those elements report unknown memory/CPU/I/O rather than the array's numbers.

GPU mapping#

A rule declares GPU needs through resources.gpu (simple count) and/or [rules.resources.gpu_spec] (count plus SLURM-only model/memory). The two forms are alternatives, not additive, and the backend mappings do not share one precedence:

  • SLURM, PBS, and SGE read gpu_spec when the table is present, and fall back to resources.gpu only when it is absent.
  • LSF reads resources.gpu only. A gpu_spec-only rule renders no -gpu directive and submits a warning instead of silently running CPU-only.
  • Kubernetes and AWS Batch read resources.gpu when the field is present, and fall back to gpu_spec.count only when it is absent.

0 requests no GPUs, and gpu_spec.model / memory_gb are SLURM concepts. The local executor maps no GPU directive and tracks no GPU capacity; a GPU declaration is metadata there (see the workflow format).

Backend GPU source Rendered GPU directive
SLURM gpu_spec when present, else gpu #SBATCH --gres=gpu:<count> — or gpu:<model>:<count> / gpu:<model>:<count>:<memory>g from gpu_spec, plus --mem-per-gpu when memory_gb is set
PBS gpu_spec when present (count only), else gpu gpu=<count> in the resource list (site-specific complex naming)
SGE gpu_spec when present (count only), else gpu #$ -l gpu=<count>
LSF gpu only — gpu_spec alone is not mapped #BSUB -gpu "num=<count>" (a gpu_spec-only rule warns at submission and renders no directive)
Kubernetes gpu when present, else gpu_spec.count resources.limits["nvidia.com/gpu"] = "<count>"
AWS Batch gpu when present, else gpu_spec.count a resourceRequirements entry { "type": "GPU", "value": "<count>" }
GCP Batch none not mapped — the generator omits the allocation-policy accelerator fields. GCP Batch attaches GPUs through allocationPolicy.instances[].policy.accelerators[].count plus allocationPolicy.instances[].installGpuDrivers, not the task payload's computeResource; GPU provisioning stays operator infrastructure (backend/gcp_batch.rs documents the boundary)
Tencent Batch none not mapped — the BatchCompute API (2017-03-12) has no GPU count/type field in Task, AnonymousComputeEnv/NamedComputeEnv, EnvData, or ComputeEnvData; Gpu/GpuCount exist only on the read-only InstanceTypeQuotaItem catalogue. GPU nodes are selected by CVM instance type (e.g. GN7.2XLARGE32) via TENCENTBATCH_INSTANCE_TYPE or the named environment referenced by TENCENTBATCH_ENV_ID. A submission declaring a GPU requirement emits a warning naming this omission (official data structures: https://cloud.tencent.com/document/api/599/15912)

Assumptions#

  • Outputs, workdir, and logs live on shared storage — every compute node sees the same files, so jobs can run anywhere and the driver's checkpoint bookkeeping stays meaningful.
  • Jobs are POSIX shell scripts; the scheduler runs them with /bin/bash.

Checkpoint re-entry#

See Workflow Format for the config surface. A checkpoint = true rule writes a re-entry manifest at runtime; when it completes, the engine merges the new values, re-expands the rule templates, and executes the new instances in the same run. This works on the local path (oxo-flow run); cluster submissions reject checkpoint = true rules at plan time instead of silently skipping the dynamically discovered instances. Every round is still a static plan, so previews stay deterministic and resumes reconstruct the same plan.