Dev plan: composite pipeline tasks — multi-stage × sweep × HPC × enqueue
Superseded status (2026-10-16): the user approved immediate pre-1.0 removal of automatic cache search, marker-based partial-stage resume and chained fanout. The candidate implements removal, not deprecated opt-in compatibility. Historical inventories below explain prior decisions; use current migration notes and workflow guidelines for supported calls.
Branch: pipeline-tasks (worktree of flexlock @ 0a4726d, v0.8.1).
Integration with env-fingerprint uses one stage executor for plain and
composite tasks, retaining batched claims/completions, task tags, full run
records, preset links, and code-drift detection. Composite DB snapshots store
each executed stage under stages[absolute_save_dir]; the record reader
selects that stage and exports materialize all stages with the master.
Goal
Lift the restriction that multi-stage selection (flexlock-run -s train linear_probe)
is incompatible with --sweep*, --slurm-config/--pbs-config, and --enqueue
(runner.py::_validate_multiselect). Additionally make --sweep + --enqueue
work in the single-stage path (today the enqueue branch returns before
load_sweep is called, silently dropping the sweep).
Core design: composite pipeline tasks
A task in the sweep task DB may be a stage sequence instead of a single config:
_stages_:
- {_target_: ..., save_dir: results/xp1/train, ...} # fully compiled stage cfg
- {_target_: ..., save_dir: results/xp1/linear_probe, ...}
One sweep item = one composite task = the whole stage sequence for that item.
The worker runs a composite task’s stages sequentially, guaranteeing intra-item ordering by construction. Parallelism (local
n_jobs, Slurm/PBS array workers) fans out across items.Plain dict tasks keep their exact current behaviour.
_hash_task,queue_tasks, tags, resume, orphan reconciliation,flexlock-statusall work unchanged —task_infois opaque YAML; no DB schema change.Stage configs are compiled and frozen at build time (root refs baked by
select_and_freeze_root_refs, thenfreeze_deferredper stage so${run_lock:}/${latest:}stay deferred and fire on the worker at stage start). A composite task is therefore self-contained: never re-merge the base config into it at dequeue time.
Semantics for multi-stage sweeps (docs §14g pipeline_dir pattern): each sweep
item merges into the root config before selection (respecting
--sweep-target as a root dot-path), then every stage is re-selected and
re-frozen from that merged root. -s train linear_probe --sweep pipeline_dir=xp1,xp2 → 2 composite tasks × 2 stages.
Known accepted limitation (document it): all stages of an item run inside one
scheduler job / worker slot, so per-stage HPC resource configs are not
possible. Scheduler-level --dependency chaining is a possible later
enhancement, out of scope here.
Phase 1 — worker: execute composite tasks
flexlock/worker.py::worker_loop
Refactor the current per-task body (merge →
resolve_deferred→extract_tracking_info→ fingerprint →snapshot(parent_lock=master)→.flexlock_marker→func(cfg)→results.json→mark_complete→index.record_task) into a helper, e.g._run_stage(func, cfg, task_to, db_path, db_dir, master_lock, stage, node, task_id) -> (save_dir, result). Keep behaviour byte-identical for plain tasks (they call it once).Detect composite tasks:
isinstance(task, (dict, DictConfig))and"_stages_" in task. For those:Iterate
task["_stages_"]in order; run each stage through_run_stage.Stage-level resume: honour an optional
_skip_complete_: truekey on the composite task — if a stage’ssave_diralready hasrun.complete, log and skip it (mirrors--check-existssemantics). Without the key, run every stage (collision guard was applied driver-side).On stage failure: write
run.errorin that stage’s dir (existingRunRecord.write_error, include stage index), abort the remaining stages, andfinish_task(db_path, task, error=...)with the traceback prefixed by which stage failed (e.g."[stage 1/2 linear_probe] ...").On success of all stages:
finish_task(..., result=<per-stage list>)where the result is[{"save_dir": ..., "result": ...}, ...](must stayyaml.safe_dump-able —taskdb._to_yamlraises on arbitrary objects)..flexlock_markerper stage dir points at the shared DB + the compositetask_id(same as today’s single-task marker).
KeyboardInterrupt mid-item:
finish_task(status="interrupted")as today; completed stage dirs keep theirrun.completeso a reclaim resumes past them when_skip_complete_is set.
Phase 2 — api: Project.submit_pipeline
flexlock/api.py
New method (name it submit_pipeline; keep _submit_sweep untouched):
def submit_pipeline(self, items: "List[List[DictConfig]]", *, n_jobs=1,
smart_run=False, search_dirs=None, slurm_config=None,
pbs_config=None, wait=True, sweep_root=None, tag=None,
force=False, timeout=None, note=None,
save_dir_policy=None, debug=False,
dry_run=False) -> "List[List[ExecutionResult]]":
Serialization: composite task dict per item =
{"_stages_": [OmegaConf.to_container(stage, resolve=False, throw_on_missing=False), ...]}. Stages arrive already frozen (freeze_deferredapplied by the caller). Whensmart_run/check-exists is requested, set"_skip_complete_": Trueon the task dict.DB root:
sweep_rootif given, else the item root per item =os.path.commonpathof that item’s stagesave_dirs (the pipeline dir), and the master root = commonpath of the item roots. For a single item the master root is its pipeline dir. Task DB lives at<master_root>/run.lock.tasks.dbvia the existingParallelExecutor(cfg=executor_cfg)convention (executor_cfg = {"save_dir": str(master_root), "_snapshot_": {}}).Containment validation: every stage
save_dirmust nest under the master root unlesssweep_rootwas explicitly provided (mirror_validate_sweep_save_dirs, including the helpful error text suggesting--sweep-root). RaiseFlexLockValidationErrorbefore queueing anything.Collision guard (
save_dir_policy): naming policies (increment/timestamp) don’t compose cleanly with pre-baked cross-stage paths — reject them with a clearFlexLockValidationErrorfor pipelines. Guard policies apply per stage dir, driver-side, before queueing:raise(default, unlessforce),overwrite(clean_run_dir),skip(→ set_skip_complete_),unsafe(no check).force: unlink each stage’s
run.complete/results.jsonand reset the task DB (reuse_reset_sweep_for_forceshape; DB files at master root).smart_run (driver-side): optional first cut — for each item, if every stage cache-hits
_find_matching_run, return CACHED results for the item without queueing it. Partial hits: queue the item with_skip_complete_. (Keep simple; per-stage fingerprint checks on the worker are out of scope.)Dispatch: one
ParallelExecutor(func=instantiate, tasks=composite_tasks, task_target=None, cfg=executor_cfg, n_jobs=..., slurm_config=..., pbs_config=..., tag=..., note=...);executor.run(wait=wait, timeout=...).dry_run (HPC): render the submission script via the existing
_preview_hpc_scriptand return without queueing (call it beforeParallelExecutoris constructed so the DB isn’t touched).Results: after the run, build
List[List[ExecutionResult]](items × stages) from the task DB rows: composite row status maps to the item; per stage, prefer the stage dir’sresults.json/run.complete(a stage that ran before a later-stage failure is SUCCESS; unreached stages are SUBMITTED/INTERRUPTED; the failing stage FAILED with the row’s error). Reuse/extendcollect_resultsor addcollect_pipeline_results.wait=False→ all-SUBMITTEDskeleton results.
Phase 3 — runner: wire _run_multi to sweeps, HPC, enqueue
flexlock/runner.py
_validate_multiselect: remove--sweep/--sweep-file/--sweep-key,--slurm-config/--pbs-config, and--enqueuefrom the offending list. Keep-O/-Mand-e/--edit-configrejected. Update the--selecthelp string and the error text._run_multirework:sweep_tasks = load_sweep(...)(same call as the single-stage path);items = sweep_tasks or [None](None= no override).Per item:
merged_root = root_cfgif item isNoneelsemerge_task_into_cfg(root_cfg, item, args.sweep_target)(root-level merge, pre-selection). Then per stage:stage_cfg = self._build_node_cfg(args, merged_root, base_cfg, sel)followed byfreeze_deferred(stage_cfg).--print-config/--dump: iterate items × stages with# --- item i / stage sel ---headers, then return (as today).--enqueue FILE: append one{"_stages_": [to_container(stage, resolve=False), ...]}dict per item viaenqueue_to_file; log count; return.--check: runProject.checkper stage config (item-merged), aggregate errors with item/stage labels.Otherwise dispatch:
proj.submit_pipeline(items_stages, n_jobs=args.n_jobs, smart_run=bool(args.check_exists), slurm_config=..., pbs_config=..., sweep_root=args.sweep_root, dry_run=..., note=..., force=..., save_dir_policy=..., debug=debug).Return shape back-compat: single item → return the flat per-stage list of raw results (matches today’s
_run_multireturn); multiple items → list of lists.Keep the current local sequential path? No — route everything through
submit_pipeline(single item, n_jobs=1, local == worker_loop in-process, same ordering). BUT: this changes the current multi-select behaviour from directproj.submitper stage to the task-DB path. If test fallout is large, keep the old direct path for the no-sweep/no-HPC/no-enqueue case and usesubmit_pipelineotherwise — decide by test results, prefer one path if green.
Phase 4 — dequeue: composite entries in --sweep-file
flexlock/runner.py::run (single-stage path), possibly utils.load_sweep.
After
load_sweep, partition items: composite ("_stages_"key) vs plain.All-composite → route to
proj.submit_pipeline(items already compiled; do NOT merge the base config into them).Mixed queues: normalize plain items by merging into the compiled node config (
merge_task_into_cfg(node_cfg, item, args.sweep_target)+freeze_deferred) and wrapping as single-stage composites — then the whole queue goes throughsubmit_pipelineuniformly. Only do this when at least one composite entry is present; a purely plain queue keeps the existingproj.submit(sweep=...)path untouched (no regression risk).Containment: composite items validate against their pipeline dirs (Phase 2 logic); recommend
--sweep-rootin the error message.
Phase 5 — single-stage --sweep + --enqueue
flexlock/runner.py::run
Move the
args.enqueuebranch below theload_sweepcall.sweep_tasksempty → current behaviour (enqueue the compiled node config).sweep_tasksnon-empty → for each item, mirror theprint_configsweep preview inProject.submit(api.py ~631):merge_task_into_cfg(node_cfg, item, args.sweep_target)+freeze_deferred, thenenqueue_to_file(args.enqueue, to_container(resolve=False))per item. Log the total.
Tests
Follow existing patterns (tests/test_multistage_config.py,
test_dump_enqueue.py, test_parallel.py, test_runner.py). New coverage,
roughly in tests/test_pipeline_tasks.py (+ edits to
test_multistage_config.py where it asserts the old rejections):
worker: composite task runs stages in order (record call order via a target writing to a shared file); mid-item failure aborts remaining stages, DB row
failedwith stage-labelled error, earlier stage dirs haverun.complete;_skip_complete_skips completed stage dirs.api:
submit_pipelinelocal n_jobs=1 and n_jobs=2 (2 items × 2 stages, intra-item ordering preserved, items parallel); containment validation errorsweep_rootopt-out;forceresets markers+DB; naming policies rejected; result shape items × stages;wait=Falsereturns SUBMITTED.
runner:
-s a b --sweep k=v1,v2builds 2×2 configs with item merged at root pre-selection (assert a${pipeline_dir}-style root ref differs per item);--print-config/--dump/--checkiterate items × stages;-O/-M/-estill rejected; old sweep/HPC/enqueue rejections removed.enqueue/dequeue roundtrip:
-s a b --enqueue q.yamltwice with different-o pipeline_dir=...→ 2 composite entries;--sweep-file q.yamlruns both items correctly (no base re-merge); mixed queue (1 plain + 1 composite) runs both; single-stage--sweep 0.1,0.2 --sweep-target lr --enqueue q.yaml→ 2 merged plain entries; deferred resolvers survive the roundtrip unresolved.HPC: no cluster in CI — test the dispatch boundary:
submit_pipelinewithslurm_config+dry_run=Truerenders a script without touching the DB; monkeypatchSlurmBackend.submitto runworker_loopinline and assert the composite path completes (pattern likely exists intest_parallel.py).
Run the full suite (pytest tests/ -x -q) — zero regressions is the bar,
especially test_multistage_config.py, test_dump_enqueue.py,
test_parallel.py, test_node_selection.py.
Docs
docs/usage_guide.md§14g: replace the “deliberately restricted” paragraph; add sweep×stages,--enqueuebatching, and the one-job-per-item resource limitation. §6 sweeps:--sweep+--enqueue. §9 HPC: pipeline example.docs/cli_reference.md: update--select,--enqueue, sweep interactions.--selectargparse help string inrunner.py.
Commit discipline
Commit per phase on the pipeline-tasks branch (worker → api → runner →
dequeue → enqueue-sweep → docs), each with green tests. Do not touch main.