The platform for continuously improving AI agents.
Retry a Modal volume-layer rejection instead of failing the shared preparation (#238)
Rohit Guptaeaf92d1c5b77
diff --git a/overbae/services/training_preparation.py b/overbae/services/training_preparation.pyindex 34ea2471..dd9819e8 100644--- a/overbae/services/training_preparation.py+++ b/overbae/services/training_preparation.py@@ -438,7 +438,15 @@ def advance(preparation_id):volume = modal.Volume.from_name("overmind-sft", environment_name=prep.config["runtime"]["environment"])- with volume.batch_upload(force=True) as batch:+ # Same cap as training-file commits. A launch wave otherwise stacks layers+ # until Modal refuses every writer on this volume.+ from overbae.services.training_transfer import VOLUME_WRITERS+ from overbae.tasks.utils.task_lock import hold_one_slot++ with (+ hold_one_slot("sft-volume", VOLUME_WRITERS, timeout=3600),+ volume.batch_upload(force=True) as batch,+ ):batch.put_file(source, remote)function = modal.Function.from_name(prep.config["runtime"]["app"],@@ -474,12 +482,17 @@ def advance(preparation_id):# An observer failure is not a remote failure. Keep its handle until the deadline.returnexcept Exception as exc:+ # Modal squashes volume layers in the background and asks the caller to wait.+ # Leaving the shared preparation failed makes every later job for this signature fail too.+ volume_busy = starting and "too many layers" in str(exc).lower()TrainingPreparation.objects.filter(pk=prep.pk, state__in=["starting", "running"], deadline=prep.deadline).update(- state="failed",- error=str(exc)[:1000],- report={"retryable": not starting or isinstance(exc, NotFoundError)},+ state="queued" if volume_busy else "failed",+ error="" if volume_busy else str(exc)[:1000],+ report={}+ if volume_busy+ else {"retryable": not starting or isinstance(exc, NotFoundError)},touched_at=timezone.now(),)diff --git a/overbae/services/training_transfer.py b/overbae/services/training_transfer.pyindex 5c2c74a3..3afc4ccf 100644--- a/overbae/services/training_transfer.py+++ b/overbae/services/training_transfer.py@@ -11,7 +11,7 @@ from modal_shared.training_data import write_selectionfrom overbae.services import training_monitoring, training_release, training_submission# Modal's published v1 guidance: a handful of concurrent small commits.-_VOLUME_WRITERS = 5+VOLUME_WRITERS = 5STAGES = {"building_selections": "Building row selections",@@ -59,7 +59,7 @@ def stage_data(job, paths, run_id, preparation, volume, upload_fn, *, num_exampl# One commit for every selection file, and at most five launches at once.# A commit per file across a sweep stacks volume layers until Modal refuses.- with hold_one_slot("sft-volume", _VOLUME_WRITERS, timeout=3600):+ with hold_one_slot("sft-volume", VOLUME_WRITERS, timeout=3600):with volume.batch_upload() as batch:for name in paths:report(diff --git a/overbae/tasks/finetuning.py b/overbae/tasks/finetuning.pyindex 978d2fd4..2f972f69 100644--- a/overbae/tasks/finetuning.py+++ b/overbae/tasks/finetuning.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport jsonimport logging+import mathimport osimport tempfileimport time@@ -254,6 +255,17 @@ def _progress_fingerprint(progress):)+def _finite_json(value):+ # Postgres json rejects NaN and Infinity; Python's encoder emits them.+ if isinstance(value, float) and not math.isfinite(value):+ return None+ if isinstance(value, dict):+ return {key: _finite_json(item) for key, item in value.items()}+ if isinstance(value, list):+ return [_finite_json(item) for item in value]+ return value++def _persist_snapshot_progress(job, snap, *, tick_evals: bool) -> None:from overbae.models import FinetuningJobfrom overbae.services.finetuning_runner import progress_from_snapshot@@ -340,6 +352,7 @@ def _persist_snapshot_progress(job, snap, *, tick_evals: bool) -> None:observe["poll_errors"] = 0progress["observe"] = observe+ progress = _finite_json(progress)FinetuningJob.objects.filter(pk=job.pk).update(progress=progress)job.progress = progressoperational_progress.training(job)diff --git a/overbae/tasks/finetuning_reconciler.py b/overbae/tasks/finetuning_reconciler.pyindex a2db5c9a..60c2e58f 100644--- a/overbae/tasks/finetuning_reconciler.py+++ b/overbae/tasks/finetuning_reconciler.py@@ -69,8 +69,12 @@ def _reconcile() -> dict:logger.exception("Provider submission reconciliation unavailable for %s", job.id)continueif job.remote_job_id and job.status in {"running", "preparing", "queued"}:- observe_finetuning_job(job)- observed += 1+ try:+ observe_finetuning_job(job)+ except Exception:+ logger.exception("Provider observation failed for %s", job.id)+ else:+ observed += 1continueif job.status == "preparing" and not job.remote_job_id:if not inventory_known or (timezone.now() - job.updated_at).total_seconds() < 120:diff --git a/tests/test_training_preparation.py b/tests/test_training_preparation.pyindex cdaa1bbd..a0b0a388 100644--- a/tests/test_training_preparation.py+++ b/tests/test_training_preparation.py@@ -207,6 +207,126 @@ def test_preparation_reports_exported_rows_before_upload(cell, monkeypatch):]+class _LayerBatch:+ """First upload raises Modal's layer-limit error; the next one commits."""++ def __init__(self, attempts):+ self.attempts = attempts++ def __enter__(self):+ self.attempts["n"] += 1+ if self.attempts["n"] == 1:+ raise RuntimeError("Volume commit failed: Too Many Layers in volume")+ return self++ def __exit__(self, *args):+ return False++ def put_file(self, _local, _remote):+ return None+++def test_volume_layer_limit_is_retried_for_the_same_preparation(cell, monkeypatch):+ prep = preparation.request_preparation(cell, "Qwen/Qwen3-8B", 4096)+ attempts = {"n": 0}+ spawn = Mock(return_value=SimpleNamespace(object_id="fc-prep"))+ monkeypatch.setattr(+ preparation.modal.Volume,+ "from_name",+ Mock(return_value=SimpleNamespace(batch_upload=lambda **_: _LayerBatch(attempts))),+ )+ monkeypatch.setattr(+ preparation.modal.Function,+ "from_name",+ Mock(return_value=SimpleNamespace(spawn=spawn)),+ )++ preparation.advance(prep.id)+ prep.refresh_from_db()+ assert prep.state == "queued" and not prep.error and not prep.report+ assert spawn.call_count == 0+ assert preparation.request_preparation(cell, "Qwen/Qwen3-8B", 4096).id == prep.id++ preparation.advance(prep.id)+ prep.refresh_from_db()+ same = preparation.request_preparation(cell, "Qwen/Qwen3-8B", 4096)+ assert same.id == prep.id and same.state == "running" and same.remote_id == "fc-prep"+ assert spawn.call_count == 1++[email protected]("where", ["enter", "put_file", "exit"])+def test_volume_layer_limit_at_each_upload_step_stays_retriable(cell, monkeypatch, where):+ prep = preparation.request_preparation(cell, "Qwen/Qwen3-8B", 4096)++ class Batch:+ def __enter__(self):+ if where == "enter":+ raise RuntimeError("too many layers in volume. Please wait and retry.")+ return self++ def __exit__(self, exc_type, exc, tb):+ if where == "exit" and exc_type is None:+ raise RuntimeError("too many layers in volume. Please wait and retry.")+ return False++ def put_file(self, _local, _remote):+ if where == "put_file":+ raise RuntimeError("too many layers in volume. Please wait and retry.")++ monkeypatch.setattr(+ preparation.modal.Volume,+ "from_name",+ Mock(return_value=SimpleNamespace(batch_upload=lambda **_: Batch())),+ )+ preparation.advance(prep.id)+ prep.refresh_from_db()+ assert prep.state == "queued" and not prep.error and not prep.report+++def test_other_upload_errors_still_fail_the_preparation(cell, monkeypatch):+ prep = preparation.request_preparation(cell, "Qwen/Qwen3-8B", 4096)++ class Batch:+ def __enter__(self):+ raise RuntimeError("dataset bytes changed during export")++ def __exit__(self, *args):+ return False++ monkeypatch.setattr(+ preparation.modal.Volume,+ "from_name",+ Mock(return_value=SimpleNamespace(batch_upload=lambda **_: Batch())),+ )+ preparation.advance(prep.id)+ prep.refresh_from_db()+ assert prep.state == "failed" and "dataset bytes changed" in prep.error+ assert prep.report["retryable"] is False+ with pytest.raises(ValueError, match="safely"):+ preparation.retry_preparation(prep)+++def test_layer_limit_on_a_running_call_keeps_the_remote_id(cell, monkeypatch):+ prep = preparation.request_preparation(cell, "Qwen/Qwen3-8B", 4096)+ prep.state, prep.remote_id = "running", "fc-live"+ prep.save(update_fields=["state", "remote_id"])+ call = SimpleNamespace(+ get=Mock(side_effect=RuntimeError("too many layers in volume. Please wait and retry.")),+ cancel=Mock(),+ )+ monkeypatch.setattr(+ preparation.modal.FunctionCall,+ "from_id",+ Mock(return_value=call),+ )+ preparation.advance(prep.id)+ prep.refresh_from_db()+ assert prep.state == "failed" and prep.remote_id == "fc-live"+ assert prep.report["retryable"] is True and call.cancel.call_count == 0+ assert preparation.retry_preparation(prep).state == "queued"+ call.cancel.assert_called_once()++def test_uncertain_submission_and_expired_operations_fail_closed(cell):prep = preparation.request_preparation(cell, "Qwen/Qwen3-8B", 4096)prep.__class__.objects.filter(pk=prep.pk).update(