The platform for continuously improving AI agents.
Recover background jobs within minutes after a stopped machine (#350)
Freyam Mehta3d39d3e70f93
diff --git a/.agents/skills/backend-architecture/references/celery.md b/.agents/skills/backend-architecture/references/celery.mdindex 9ffa1246..97618942 100644--- a/.agents/skills/backend-architecture/references/celery.md+++ b/.agents/skills/backend-architecture/references/celery.md@@ -37,10 +37,12 @@ Waiting work is a PostgreSQL row, admitted by a row-locked dispatcher in least-r- `EvalGenerationScheduler` — `EVAL_MAX_IN_FLIGHT`, `EVAL_MAX_IN_FLIGHT_PER_PROJECT` and `EVAL_MAX_IN_FLIGHT_PER_RUN`; completion and a 30-second control tick refill slots.- `DatasetPipelineRun` is the exception: a queued run takes a per-project Redis slot or retries through the broker every 2 s, and fails after 15 minutes without capacity. The default project limit stays below the minimum interactive worker size.-A lost started attempt is repeated only where a repeat has no outside effect: an upload until `imports.MAX_ATTEMPTS`, and an eval row's generation once (`generation.GENERATION_ATTEMPTS`), since it replays recorded tools. Anything else becomes an explicit unknown outcome and is never repeated automatically. Queue metrics report durable backlog and oldest waiting age.+A lost started attempt is repeated only where a repeat has no outside effect: an upload until `imports.MAX_ATTEMPTS`, an eval row's generation once (`generation.GENERATION_ATTEMPTS`), since it replays recorded tools, a Workshop run twice, since its scripts run in a sandbox with no network, credentials or shared disk, and a training-preparation start that had not yet reached `function.spawn`. Anything else becomes an explicit unknown outcome and is never repeated automatically. Queue metrics report durable backlog and oldest waiting age.## Leases and reconcilers+Long background jobs (exploration, partition plans, experiment preparation, decision measurement, native-eval stages, connector chunks, eval rows) hold a five-minute lease that `services/datasets/heartbeat.py` renews while the worker lives; `models/leases.py` gives a job its `attempt`, which fences every write, and `heartbeat.take` fails a job lost `MAX_ATTEMPTS` times. A stopped job restarts once its lease lapses, not after its time limit. A training-preparation start has its own `attempt` and heartbeat: a start lost before its spawn was marked runs again until the preparation's 24-hour deadline, and one lost after stays failed with an unknown acknowledgement.+Frequent beat tasks (live-scoring admission, import and evaluation dispatch, Workshop bindings, queue metrics, sweeps) set short `expires`, so a busy queue drops stale ticks; most domain reconcilers set none. The training reconciler renews a 30-second Redis lease, so a dead worker stops suppressing observations quickly. Reconciliation repairs missed terminal events from local receipts; it never polls or resubmits a provider to do so.## Deploymentdiff --git a/.agents/skills/data-workshop/SKILL.md b/.agents/skills/data-workshop/SKILL.mdindex 160298b1..2616368f 100644--- a/.agents/skills/data-workshop/SKILL.md+++ b/.agents/skills/data-workshop/SKILL.md@@ -20,7 +20,7 @@ A customer's coding agent over MCP and the Console assistant own interpretation,| `services/datasets/versions.py`, `use.py` | Version resolution; consumer checks and pinning || `services/datasets/preparation.py` | The source-to-output graph shared by the Console and MCP || `sandbox/documents/` | Document parsing and OCR in the isolated `sandbox` service |-| `tasks/datasets.py` | Landing and pipeline execution; the reaper fails expired runs without replay |+| `tasks/datasets.py` | Landing and pipeline execution; the reaper hands lost runs back to the queue |## Sources and landing@@ -47,7 +47,7 @@ A customer's coding agent over MCP and the Console assistant own interpretation,- Steps declare `id` and `input`; `inputs` concatenates disjoint earlier branches in order and rejects overlapping `source_row` identities. It is not a relational join. `flow` (`pipeline_graph.py`) returns `nodes`, `edges` (each with its `condition`), `terminal_steps` and `unconsumed_steps`. Script conditions cite `expression` and `line` and never execute as expressions.- A successful run publishes all step cells atomically. Preview publishes nothing. `min_rows`/`max_rows` apply at publication and show as deferred in previews; row preservation, schema and lineage checks apply in both. Run receipts expose queue age, a polling interval, terminal time and structured failed checks. Runner heartbeats continue through validation and publication without advancing measured progress.- Cells carry receipt-backed `transformation` attribution (run, revision, package checksum, entrypoint). External imports and unrecorded history never claim platform execution. Every retained package file is inspectable with checksum-verified pagination.-- Recovery is lease expiry: a heartbeat renews a running run's five-minute lease and its project slot while the worker lives, and the `reap_stuck_runs` beat task calls `workbench.expire_runs`, which fails runs past their lease without publishing partial output or replaying scripts.+- Recovery is lease expiry: a heartbeat renews a running run's five-minute lease and its project slot while the worker lives, and the `reap_stuck_runs` beat task calls `workbench.expire_runs`, which hands a run past its lease back to the queue under a new attempt (`workbench.hand_off`; a sandbox lost mid-step does the same), at most twice, then fails it. Scripts change nothing outside the run and only the attempt holding the run publishes, so a run never publishes twice or partially.- Failure or cancellation leaves source and consumer versions unchanged. Cancellation prevents publication; it does not claim to stop a running calculation.- A step is one sandbox request. `batch_rows` (1–100,000) runs a row-independent script once per batch, each in a fresh process, one after another under one memory reservation (`sandbox/execute.py`); global sorting, grouping, splitting and deduplication must not batch. The worker streams the stored Parquet; the sandbox writes JSONL for the script unless the step declares `io: parquet`. A full sandbox makes the request wait inside the run lease.- `packages.runtime_id()` hashes only what a script observes (the I/O contract, the interpreter, `uv.lock`, `package_child.py`, `kernel.py`). Changing the sandbox server leaves saved packages runnable.diff --git a/overbae/innermind/generation.py b/overbae/innermind/generation.pyindex c215e771..9242129b 100644--- a/overbae/innermind/generation.py+++ b/overbae/innermind/generation.py@@ -19,6 +19,7 @@ from django.utils import timezonefrom overbae.core.llms import ModelSpec, call_llmfrom overbae.innermind import replayfrom overbae.models import EvalGenerationScheduler, EvalRun, EvalRunRow, Span+from overbae.services.datasets import heartbeatfrom overbae.services.datasets import rows as row_storefrom overbae.services.datasets.examples import matches_referencefrom overbae.services.datasets.profiler import bind_eval_reference@@ -29,8 +30,6 @@ logger = logging.getLogger(__name__)IN_FLIGHT = (EvalRunRow.State.QUEUED, EvalRunRow.State.RUNNING)UNFINISHED = (EvalRunRow.State.WAITING, *IN_FLIGHT)QUEUED_LEASE = timedelta(minutes=30)-# The worker's hard time limit is 22 minutes.-RUNNING_LEASE = timedelta(minutes=23)# Generation replays recorded tools and has no outside effect, so a lost attempt runs once# more at the cost of one duplicate model call; a second loss is recorded unknown.GENERATION_ATTEMPTS = 2@@ -67,7 +66,8 @@ def dispatch(publish, publish_scoring) -> dict[str, int]:expired = list(rows.filter(state__in=IN_FLIGHT, expires_at__lt=now))for row in expired:- current = rows.filter(pk=row.pk, state=row.state, task_id=row.task_id)+ # A heartbeat may have renewed the lease since the selection.+ current = rows.filter(pk=row.pk, state=row.state, task_id=row.task_id, expires_at__lt=now)if row.output is not None or row.error:current.update(state=EvalRunRow.State.DONE, finished_at=now)elif row.state == EvalRunRow.State.QUEUED or row.attempts < GENERATION_ATTEMPTS:@@ -166,16 +166,19 @@ def claim(row_id, task_id) -> bool:EvalRunRow.objects.filter(pk=row.pk).update(state=EvalRunRow.State.RUNNING,started_at=now,- expires_at=now + RUNNING_LEASE,+ expires_at=heartbeat.lease_end(),attempts=F("attempts") + 1,)return True+def owned(row_id, task_id):+ """The row while ``task_id`` still runs it; a row the dispatcher expired is not."""+ return EvalRunRow.objects.filter(pk=row_id, task_id=task_id, state=EvalRunRow.State.RUNNING)++def finish(row_id, task_id) -> int:- return EvalRunRow.objects.filter(- pk=row_id, task_id=task_id, state=EvalRunRow.State.RUNNING- ).update(state=EvalRunRow.State.DONE, finished_at=timezone.now())+ return owned(row_id, task_id).update(state=EvalRunRow.State.DONE, finished_at=timezone.now())@transaction.atomic@@ -489,7 +492,7 @@ def generate(run_row: EvalRunRow) -> None:output = output_of(result.output_messages)reason = degradation(result, output)- EvalRunRow.objects.filter(pk=run_row.pk).exclude(run__status__in=EvalRun.TERMINAL).update(+ owned(run_row.pk, run_row.task_id).exclude(run__status__in=EvalRun.TERMINAL).update(output=output,degraded=bool(reason),degraded_reason=reason,diff --git a/overbae/migrations/0065_job_leases.py b/overbae/migrations/0065_job_leases.pynew file mode 100644index 00000000..97881fb5--- /dev/null+++ b/overbae/migrations/0065_job_leases.py@@ -0,0 +1,83 @@+# Generated by Django 6.0.8 on 2026-11-24 12:24++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('overbae', '0064_eval_attempts'),+ ]++ operations = [+ migrations.AddField(+ model_name='dataexploration',+ name='attempt',+ field=models.UUIDField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name='dataexploration',+ name='attempts',+ field=models.SmallIntegerField(db_default=0),+ ),+ migrations.AddField(+ model_name='dataexploration',+ name='lease_until',+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name='datapartitionplan',+ name='attempt',+ field=models.UUIDField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name='datapartitionplan',+ name='attempts',+ field=models.SmallIntegerField(db_default=0),+ ),+ migrations.AddField(+ model_name='datapartitionplan',+ name='lease_until',+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name='datasetpipelinerun',+ name='handoffs',+ field=models.SmallIntegerField(db_default=0),+ ),+ migrations.AddField(+ model_name='decisionperformancerun',+ name='attempt',+ field=models.UUIDField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name='decisionperformancerun',+ name='attempts',+ field=models.SmallIntegerField(db_default=0),+ ),+ migrations.AddField(+ model_name='decisionperformancerun',+ name='lease_until',+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name='trainingexperiment',+ name='attempt',+ field=models.UUIDField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name='trainingexperiment',+ name='attempts',+ field=models.SmallIntegerField(db_default=0),+ ),+ migrations.AddField(+ model_name='trainingexperiment',+ name='lease_until',+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name='trainingpreparation',+ name='attempt',+ field=models.UUIDField(blank=True, null=True),+ ),+ ]diff --git a/overbae/models/dataset_pipeline.py b/overbae/models/dataset_pipeline.pyindex 007b71b6..f76ac934 100644--- a/overbae/models/dataset_pipeline.py+++ b/overbae/models/dataset_pipeline.py@@ -86,6 +86,8 @@ class DatasetPipelineRun(models.Model):error = models.TextField(blank=True, default="")result = models.JSONField(default=dict)lease_until = models.DateTimeField(null=True)+ # Times a run whose worker stopped went back in the queue.+ handoffs = models.SmallIntegerField(db_default=0)created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)diff --git a/overbae/models/datasets.py b/overbae/models/datasets.pyindex c749740d..c8795a06 100644--- a/overbae/models/datasets.py+++ b/overbae/models/datasets.py@@ -4,6 +4,8 @@ from django.conf import settingsfrom django.contrib.postgres.indexes import GinIndexfrom django.db import models+from .leases import Leased+class Dataset(models.Model):"""A source and a linear chain of cells. Every cell is a version of the@@ -135,7 +137,7 @@ class Dataset(models.Model):return out-class DataExploration(models.Model):+class DataExploration(Leased):id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)project = models.ForeignKey("overbae.Project", on_delete=models.CASCADE)name = models.CharField(max_length=255)@@ -163,7 +165,7 @@ class DataExploration(models.Model):]-class DataPartitionPlan(models.Model):+class DataPartitionPlan(Leased):id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)project = models.ForeignKey("overbae.Project", on_delete=models.CASCADE)name = models.CharField(max_length=255)diff --git a/overbae/models/finetuning.py b/overbae/models/finetuning.pyindex 75e2c147..1397aa8c 100644--- a/overbae/models/finetuning.py+++ b/overbae/models/finetuning.py@@ -3,6 +3,8 @@ import uuidfrom django.conf import settingsfrom django.db import models+from .leases import Leased+class TrainingPreparation(models.Model):id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)@@ -20,6 +22,8 @@ class TrainingPreparation(models.Model):config = models.JSONField(default=dict)state = models.CharField(max_length=16, default="queued")remote_id = models.CharField(max_length=255, blank=True, default="")+ # Names the worker that started the preparation; its writes and its spawn check it.+ attempt = models.UUIDField(null=True, blank=True)report = models.JSONField(default=dict)error = models.TextField(blank=True, default="")deadline = models.DateTimeField()@@ -27,7 +31,7 @@ class TrainingPreparation(models.Model):created_at = models.DateTimeField(auto_now_add=True)-class TrainingExperiment(models.Model):+class TrainingExperiment(Leased):id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)project = models.ForeignKey("overbae.Project", on_delete=models.CASCADE)name = models.CharField(max_length=255)@@ -446,7 +450,7 @@ class DecisionProviderRequest(models.Model):]-class DecisionPerformanceRun(models.Model):+class DecisionPerformanceRun(Leased):id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)project = models.ForeignKey("overbae.Project", on_delete=models.CASCADE)evaluation = models.ForeignKey(NativeEvaluationPlan, on_delete=models.PROTECT)diff --git a/overbae/models/leases.py b/overbae/models/leases.pynew file mode 100644index 00000000..e4c4b23d--- /dev/null+++ b/overbae/models/leases.py@@ -0,0 +1,14 @@+from django.db import models+++class Leased(models.Model):+ """A background job one worker holds at a time. ``attempt`` names the holder and+ fences its writes, its heartbeat renews ``lease_until``, and ``attempts`` bounds+ how often a lost job starts again."""++ attempt = models.UUIDField(null=True, blank=True)+ lease_until = models.DateTimeField(null=True, blank=True)+ attempts = models.SmallIntegerField(db_default=0)++ class Meta:+ abstract = Truediff --git a/overbae/services/connectors/sync.py b/overbae/services/connectors/sync.pyindex 982992f9..a6bf37c3 100644--- a/overbae/services/connectors/sync.py+++ b/overbae/services/connectors/sync.py@@ -47,8 +47,9 @@ def connector_imported_spans(credential):return Span.objects.filter(span_id__in=ids)-def reset_connector_import(credential) -> int:- """Delete this credential's imported spans and rewind its sync cursor."""+def reset_connector_import(credential, *, release=True) -> int:+ """Delete this credential's imported spans and rewind its sync cursor. A running+ chunk passes ``release=False`` to keep holding ``next_poll_at``, its lease."""from overbae.models import ConnectorCredentialspans = connector_imported_spans(credential)@@ -61,8 +62,8 @@ def reset_connector_import(credential) -> int:total_traces_imported=0,backfill_imported=0,backfill_total=None,- next_poll_at=None,sync_error="",+ **({"next_poll_at": None} if release else {}),)credential.refresh_from_db()return count@@ -81,7 +82,7 @@ def prepare_connector_sync(credential) -> bool:stored = credential.imported_boundary_key or ""recarving = bool(stored) and stored != currentif recarving:- reset_connector_import(credential)+ reset_connector_import(credential, release=False)if stored != current:ConnectorCredential.objects.filter(pk=credential.pk).update(imported_boundary_key=current)credential.imported_boundary_key = currentdiff --git a/overbae/services/datasets/exploration.py b/overbae/services/datasets/exploration.pyindex 4f11ffd7..b4197fad 100644--- a/overbae/services/datasets/exploration.py+++ b/overbae/services/datasets/exploration.py@@ -3,7 +3,6 @@ import loggingimport sqlite3import timeimport uuid-from datetime import timedeltafrom django.db import transactionfrom django.utils import timezone@@ -12,6 +11,7 @@ from overbae.core.errors import InputValidationErrorfrom overbae.models import Cell, DataExploration, Dataset, Projectfrom overbae.services.datasets import (events,+ heartbeat,land,lineage,paths,@@ -74,12 +74,19 @@ def advance(identifier):.select_related("source_cell__dataset", "project").get(pk=identifier))- if op.state == "completed" or (- op.state == "running" and op.updated_at > timezone.now() - timedelta(seconds=1260)- ):+ if op.state == "completed":+ return+ taken = heartbeat.take(op, running=op.state == "running")+ if taken == "held":+ return+ if taken == "exhausted":+ op.state, op.error = "failed", heartbeat.STOPPED+ op.save(update_fields=["state", "error", "attempt", "lease_until", "updated_at"])returnop.state, op.error = "running", ""op.save()+ owned = DataExploration.objects.filter(pk=op.pk, attempt=op.attempt)+ beat = heartbeat.hold(owned, owner=f"exploration {op.pk}")started = time.perf_counter()try:rows.verify(op.source_cell)@@ -185,7 +192,7 @@ def advance(identifier):transaction.on_commit(lambda: events.publish(cell.dataset_id, {"type": "dataset_changed"}))- DataExploration.objects.filter(pk=op.pk).update(+ owned.update(state="completed",report=report,output_dataset=op.output_dataset,@@ -194,11 +201,13 @@ def advance(identifier):)except Exception:logger.exception("Data exploration failed: %s", identifier)- DataExploration.objects.filter(pk=op.pk).update(+ owned.update(state="failed",error="Source exploration failed. Verify the selected version and sampling fields before retrying.",updated_at=timezone.now(),)+ finally:+ beat.set()def describe(op):diff --git a/overbae/services/datasets/heartbeat.py b/overbae/services/datasets/heartbeat.pyindex e495f7fe..fbc0daed 100644--- a/overbae/services/datasets/heartbeat.py+++ b/overbae/services/datasets/heartbeat.py@@ -4,14 +4,21 @@ from __future__ import annotationsimport loggingimport threading+import uuidfrom collections.abc import Callable+from datetime import datetime, timedeltafrom django.db import connections+from django.db.models import Q, QuerySet+from django.utils import timezonelogger = logging.getLogger(__name__)INTERVAL_SECONDS = 30STALE_SECONDS = 5 * 60+# A job that loses its worker this often is failing on its own, not being stopped.+MAX_ATTEMPTS = 3+STOPPED = f"The worker stopped {MAX_ATTEMPTS} times before this finished."def start(touch: Callable[[], object], *, owner: str) -> threading.Event:@@ -29,3 +36,37 @@ def start(touch: Callable[[], object], *, owner: str) -> threading.Event:threading.Thread(target=beat, name=f"heartbeat {owner}", daemon=True).start()return stop+++def lease_end() -> datetime:+ return timezone.now() + timedelta(seconds=STALE_SECONDS)+++def lapsed() -> Q:+ """Rows whose holder stopped renewing; a null lease predates leases."""+ return Q(lease_until__isnull=True) | Q(lease_until__lt=timezone.now())+++def take(job, *, running: bool) -> str:+ """On a ``Leased`` row locked FOR UPDATE: ``"held"`` while a live worker renews it,+ ``"exhausted"`` once its worker was lost too often (the caller saves it failed), else+ ``"taken"`` under a new attempt (unsaved). ``running`` says whether some worker started+ it before."""+ if running:+ if job.lease_until is not None and job.lease_until > timezone.now():+ return "held"+ if job.attempts >= MAX_ATTEMPTS - 1:+ # The last holder may still be running; it must find no row it owns.+ job.attempt, job.lease_until = None, None+ return "exhausted"+ job.attempts += 1+ else:+ job.attempts = 0+ job.attempt, job.lease_until = uuid.uuid4(), lease_end()+ return "taken"+++def hold(rows: QuerySet, *, owner: str, field: str = "lease_until") -> threading.Event:+ """Renew ``field`` on ``rows`` until the event is set. ``rows`` names the holder, so a+ worker whose job was taken over renews nothing."""+ return start(lambda: rows.update(**{field: lease_end()}), owner=owner)diff --git a/overbae/services/datasets/partition_plans.py b/overbae/services/datasets/partition_plans.pyindex fd61a527..9948f566 100644--- a/overbae/services/datasets/partition_plans.py+++ b/overbae/services/datasets/partition_plans.py@@ -6,7 +6,6 @@ import tempfileimport uuidfrom collections import Counter, defaultdictfrom contextlib import closing-from datetime import timedeltafrom pathlib import Pathfrom django.db import transaction@@ -14,7 +13,7 @@ from django.utils import timezonefrom overbae.core.errors import InputValidationErrorfrom overbae.models import DataPartitionMember, DataPartitionPlan, Dataset, Project-from overbae.services.datasets import land, lineage, paths, rows, store, use+from overbae.services.datasets import heartbeat, land, lineage, paths, rows, store, usefrom overbae.services.datasets.examples import field_value, native_decision, prepare_native_recordfrom overbae.services.datasets.partition import GROUP_ALIASES@@ -274,12 +273,19 @@ def build(plan_id):.select_related("source_cell__dataset", "project").get(pk=plan_id))- if plan.state == "completed" or (- plan.state == "running" and plan.updated_at > timezone.now() - timedelta(seconds=1260)- ):+ if plan.state == "completed":+ return+ taken = heartbeat.take(plan, running=plan.state == "running")+ if taken == "held":+ return+ if taken == "exhausted":+ plan.state, plan.error = "failed", heartbeat.STOPPED+ plan.save(update_fields=["state", "error", "attempt", "lease_until", "updated_at"])returnplan.state, plan.error = "running", ""plan.save()+ owned = DataPartitionPlan.objects.filter(pk=plan.pk, attempt=plan.attempt)+ beat = heartbeat.hold(owned, owner=f"partition plan {plan.pk}")def progress(stage, completed, total, **extra):value = {@@ -289,9 +295,7 @@ def build(plan_id):**extra,"updated_at": timezone.now().isoformat(),}- DataPartitionPlan.objects.filter(pk=plan.pk, state="running").update(- report={"progress": value}, updated_at=timezone.now()- )+ owned.filter(state="running").update(report={"progress": value}, updated_at=timezone.now())return valuetry:@@ -330,6 +334,9 @@ def build(plan_id):stream.close()for role in plan.recipe["fractions"]:progress("preparing_member", 0, report["counts"][role], role=role)+ # A worker whose plan was taken over stops before it lands anything.+ if not owned.filter(state="running").exists():+ returnexisting = plan.members.select_related("cell__dataset").filter(role=role).first()if existing:rows.verify(existing.cell)@@ -374,13 +381,11 @@ def build(plan_id):"total": plan.source_cell.rows,"updated_at": timezone.now().isoformat(),}- DataPartitionPlan.objects.filter(pk=plan.pk).update(- state="completed", report=report, error="", updated_at=timezone.now()- )+ owned.update(state="completed", report=report, error="", updated_at=timezone.now())except Exception as exc:- DataPartitionPlan.objects.filter(pk=plan.pk).update(- state="failed", error=str(exc)[:1000], updated_at=timezone.now()- )+ owned.update(state="failed", error=str(exc)[:1000], updated_at=timezone.now())+ finally:+ beat.set()def describe(plan):diff --git a/overbae/services/datasets/pipeline_runner.py b/overbae/services/datasets/pipeline_runner.pyindex d4f0f978..a1e39ef8 100644--- a/overbae/services/datasets/pipeline_runner.py+++ b/overbae/services/datasets/pipeline_runner.py@@ -38,6 +38,10 @@ class RuntimeUnavailableError(ValueError):pass+class SandboxLostError(RuntimeUnavailableError):+ """The sandbox stopped mid-step; the run goes back in the queue."""++@contextmanagerdef scratch():root = Path(tempfile.gettempdir())@@ -270,9 +274,7 @@ def _submit(header, parts, output, phase, receipt) -> dict:stream.write(pending)return reader.finish()except (httpx.TransportError, FramingError) as exc:- raise RuntimeUnavailableError(- "The sandbox result is unconfirmed. No script was replayed."- ) from exc+ raise SandboxLostError("The sandbox stopped during the step.") from excdef _checked(row):diff --git a/overbae/services/datasets/workbench.py b/overbae/services/datasets/workbench.pyindex 274f2afc..df0db84d 100644--- a/overbae/services/datasets/workbench.py+++ b/overbae/services/datasets/workbench.py@@ -44,6 +44,8 @@ from overbae.services.datasets.pipeline_execution import Parentslogger = logging.getLogger(__name__)# Seconds between row counts while a step's output is written and measured.ROW_REPORT_SECONDS = 2.0+# A queued run waits this long for interactive capacity before it fails.+QUEUE_LEASE = timedelta(minutes=15)SCRATCH_BYTES = 8 * 1024**3SCRATCH_FREE_BYTES = 512 * 1024**2@@ -293,7 +295,7 @@ def submit(created_by=user,mode=mode,binding=binding,- lease_until=timezone.now() + timedelta(minutes=15),+ lease_until=timezone.now() + QUEUE_LEASE,result={"stage": "queued","source_rows": source.rows,@@ -338,21 +340,34 @@ def execute(run_id, *, script_executor=None):returnif script_executor is None:return- from overbae.services.datasets.pipeline_runner import scratch+ from overbae.services.datasets.pipeline_runner import SandboxLostError, scratch- # A heartbeat renews the lease while the worker lives, so a lost run fails within- # minutes; the worker's hard time limit bounds the whole run.+ # A heartbeat renews the lease while the worker lives, so a lost run goes back in the+ # queue within minutes; the worker's hard time limit bounds the whole run.seconds = heartbeat.STALE_SECONDS- claimed = DatasetPipelineRun.objects.filter(pk=run_id, state="queued").update(+ claimed = DatasetPipelineRun.objects.filter(+ pk=run_id, state="queued", attempt=candidate.attempt+ ).update(state="running",updated_at=timezone.now(),lease_until=timezone.now() + timedelta(seconds=seconds),)if not claimed:return- run = DatasetPipelineRun.objects.select_related(- "dataset__capability", "pipeline__package", "source", "artifact", "created_by", "binding"- ).get(pk=run_id)+ run = (+ DatasetPipelineRun.objects.select_related(+ "dataset__capability",+ "pipeline__package",+ "source",+ "artifact",+ "created_by",+ "binding",+ )+ .filter(pk=run_id, attempt=candidate.attempt)+ .first()+ )+ if run is None:+ return# Open pages read the run's start from the stream, as its queueing and its end.dataset_id = run.dataset_idtransaction.on_commit(lambda: events.publish(dataset_id, {"type": "dataset_changed"}))@@ -826,13 +841,16 @@ def execute(run_id, *, script_executor=None):lambda: events.publish(dataset.pk, {"type": "dataset_changed"}))placed.clear()+ except SandboxLostError:+ hand_off(run_id, attempt=run.attempt)except (ValueError, rows.RowStoreError, DatasetError) as exc:- fail(run_id, str(exc)[:1000])+ fail(run_id, str(exc)[:1000], attempt=run.attempt)except Exception:logger.exception("Pipeline run failed: %s", run_id)fail(run_id,"Transformation failed. Inspect the recipe and source columns; no version was published.",+ attempt=run.attempt,)finally:for path in placed:@@ -924,13 +942,16 @@ def cancel_run(project, run_id):return run-def fail(run_id, error, *, expired_before=None):+def fail(run_id, error, *, expired_before=None, attempt=None):+ """``attempt`` fences a worker's own failure: a run handed to a new attempt stays."""with transaction.atomic():run = DatasetPipelineRun.objects.select_related("dataset").get(pk=run_id)Dataset.objects.select_for_update().get(pk=run.dataset_id)eligible = DatasetPipelineRun.objects.filter(pk=run_id, state__in=["queued", "running"])if expired_before is not None:eligible = eligible.filter(lease_until__lt=expired_before)+ if attempt is not None:+ eligible = eligible.filter(attempt=attempt)result = {**run.result, "stage": "failed"}for step in result.get("steps", []):if step.get("state") == "running":@@ -945,13 +966,8 @@ def fail(run_id, error, *, expired_before=None):run.attempt,stage="failed",status="failed",- facts={- "retry_safe": not run.container_id- and not any(- step.get("submission_started_at") and step.get("exit_code") is None- for step in result.get("steps", [])- )- },+ # Scripts change nothing outside the run (see expire_runs).+ facts={"retry_safe": True},)Dataset.objects.filter(pk=run.dataset_id).update(state=Dataset.State.IDLE, error="", updated_at=timezone.now()@@ -963,14 +979,58 @@ def fail(run_id, error, *, expired_before=None):def expire_runs():expired_before = timezone.now()- for run_id in DatasetPipelineRun.objects.filter(+ for run_id, state in DatasetPipelineRun.objects.filter(state__in=["queued", "running"], lease_until__lt=expired_before- ).values_list("pk", flat=True):- fail(- run_id,- "Execution timed out. No output was published. Submit a new request key to retry.",- expired_before=expired_before,- )+ ).values_list("pk", "state"):+ if state == "running":+ hand_off(run_id, expired_before=expired_before)+ else:+ fail(+ run_id,+ "Execution timed out. No output was published. Submit a new request key to retry.",+ expired_before=expired_before,+ )+++def hand_off(run_id, *, attempt=None, expired_before=None):+ """Put a run whose worker or sandbox stopped back in the queue under a new attempt.+ Scripts run in a sandbox with no network, credentials or shared disk, and only the+ attempt that holds the run publishes, so running one again changes nothing outside+ the run. A run stopped too often fails."""+ from overbae.tasks.datasets import execute_pipeline++ with transaction.atomic():+ run = DatasetPipelineRun.objects.select_for_update().get(pk=run_id)+ if run.state != "running":+ return+ if attempt is not None and run.attempt != attempt:+ return+ if attempt is None and (run.lease_until is None or run.lease_until >= expired_before):+ return+ if run.handoffs < heartbeat.MAX_ATTEMPTS - 1:+ run.state, run.attempt, run.handoffs = "queued", uuid.uuid4(), run.handoffs + 1+ run.lease_until = timezone.now() + QUEUE_LEASE+ run.result = {**run.result, "stage": "queued"}+ run.save(+ update_fields=[+ "state",+ "attempt",+ "handoffs",+ "lease_until",+ "result",+ "updated_at",+ ]+ )+ transaction.on_commit(lambda: _enqueue(run, execute_pipeline))+ transaction.on_commit(+ lambda: events.publish(run.dataset_id, {"type": "dataset_changed"})+ )+ return+ fail(+ run_id,+ f"{heartbeat.STOPPED} No output was published. Submit a new request key to retry.",+ attempt=run.attempt,+ )@transaction.atomicdiff --git a/overbae/services/decision_performance.py b/overbae/services/decision_performance.pyindex 1785fb34..18d8abb6 100644--- a/overbae/services/decision_performance.py+++ b/overbae/services/decision_performance.py@@ -3,7 +3,6 @@ import jsonimport randomimport timefrom concurrent.futures import ThreadPoolExecutor, as_completed-from datetime import timedeltaimport modalfrom django.db import transaction@@ -23,6 +22,7 @@ from overbae.models import (from overbae.services import native_evaluationfrom overbae.services.billing_ledger import charge_llm_usagefrom overbae.services.compute_costs import estimate_usage+from overbae.services.datasets import heartbeatfrom overbae.services.decision_benchmark_scoring import recordsfrom overbae.services.decision_providers import interpret_response, question@@ -272,12 +272,19 @@ def advance(run_id):.select_related("evaluation__triggered_by", "evaluation__final_cell__dataset").get(pk=run_id))- if run.state == "completed" or (- run.state == "running" and run.updated_at > timezone.now() - timedelta(seconds=1260)- ):+ if run.state == "completed":+ return+ taken = heartbeat.take(run, running=run.state == "running")+ if taken == "held":+ return+ if taken == "exhausted":+ run.state, run.error = "failed", heartbeat.STOPPED+ run.save(update_fields=["state", "error", "attempt", "lease_until", "updated_at"])returnrun.state = "running"run.save()+ owned = DecisionPerformanceRun.objects.filter(pk=run.pk, attempt=run.attempt)+ beat = heartbeat.hold(owned, owner=f"decision performance {run.pk}")settings = run.workload["settings"]totals = dict(run.results.get("active_seconds", {}))try:@@ -421,11 +428,9 @@ def advance(run_id):totals[participant["key"]] = (totals.get(participant["key"], 0) + time.perf_counter() - started_window)- DecisionPerformanceRun.objects.filter(pk=run.pk).update(- results={"active_seconds": totals}, updated_at=timezone.now()- )+ owned.update(results={"active_seconds": totals}, updated_at=timezone.now())if run.requests.filter(state="submission_unknown").exclude(call_id="").exists():- DecisionPerformanceRun.objects.filter(pk=run.pk).update(+ owned.update(state="queued", results={"active_seconds": totals}, updated_at=timezone.now())return@@ -521,14 +526,12 @@ def advance(run_id):"shared_state_questions": settings["questions_per_request"],},}- DecisionPerformanceRun.objects.filter(pk=run.pk).update(- state="completed", results=result, error="", updated_at=timezone.now()- )+ owned.update(state="completed", results=result, error="", updated_at=timezone.now())except Exception as exc:- DecisionPerformanceRun.objects.filter(pk=run.pk).update(- state="failed", error=type(exc).__name__, updated_at=timezone.now()- )+ owned.update(state="failed", error=type(exc).__name__, updated_at=timezone.now())raise+ finally:+ beat.set()def describe(run):diff --git a/overbae/services/dedicated.py b/overbae/services/dedicated.pyindex cb8aeecd..20989700 100644--- a/overbae/services/dedicated.py+++ b/overbae/services/dedicated.py@@ -381,8 +381,7 @@ def serve_systemone(row: DedicatedDeployment, body: dict) -> dict:return dedicated_runtime.post_systemone(row, payload)-def serve_decision(row: DedicatedDeployment, decisions: list) -> dict:- _online_decision(row)+def _decision_body(row: DedicatedDeployment, decisions: list) -> dict:questions = {}for index, item in enumerate(decisions):kind = item.get("kind") or "choice"@@ -393,56 +392,67 @@ def serve_decision(row: DedicatedDeployment, decisions: list) -> dict:"instructions": item["question"],"criteria": {option: option for option in item["options"]},}- result = dedicated_runtime.post_systemone(- row,- {- "model": row.served_model_id,- "state": decisions[0]["state"],- "questions": questions,- },- )- answers = result.get("answers") or {}- predictions = []- for index, item in enumerate(decisions):- answer = answers.get(str(index)) or {}- probabilities = answer.get("probabilities") or {}- predictions.append(- {- "options": item["options"],- "probabilities": [- float(probabilities.get(option) or 0) for option in item["options"]- ],- }- )- result["predictions"] = predictions- return result+ return {"model": row.served_model_id, "state": decisions[0]["state"], "questions": questions}-def complete_request(payload: dict) -> dict:+def request_call(payload: dict):+ """The dedicated container and the ``infer`` arguments for a queued request. The caller+ spawns it and saves the call ID first, so a new worker reads the result from that ID+ instead of sending the request again."""row = DedicatedDeployment.objects.select_related("deployed_model").get(pk=payload["dedicated_id"])- started = timezone.now()if row.deployed_model.inference_contract == "decision":- result = serve_decision(row, payload["decisions"])- result["latency_ms"] = result.get("latency_ms") or 0- return result- body = {- "model": row.public_model_id,- "messages": payload["messages"],- "temperature": payload.get("temperature", 1),+ _online_decision(row)+ path = "/v1/systemone"+ body = json.dumps(_decision_body(row, payload["decisions"])).encode()+ else:+ _require_chat(row)+ chat = {+ "model": row.public_model_id,+ "messages": payload["messages"],+ "temperature": payload.get("temperature", 1),+ }+ if payload.get("max_tokens"):+ chat["max_tokens"] = payload["max_tokens"]+ path = "/v1/chat/completions"+ body = dedicated_runtime.served_body(row, json.dumps(chat).encode(), stream=False)+ arguments = {+ "method": "POST",+ "path": path,+ "body": body,+ "headers": {"content-type": "application/json"},}- if payload.get("max_tokens"):- body["max_tokens"] = payload["max_tokens"]- status, raw, _content_type = serve_chat(row, json.dumps(body).encode())+ return dedicated_runtime.connect(row), arguments+++def request_result(payload: dict, reply: dict) -> dict:+ """The request's result from the ``infer`` reply ``{"status", "headers", "body"}``."""+ status = reply.get("status")+ if not isinstance(status, int) or status >= 500:+ return {"error_code": "provider_failed"}if status >= 400:- raise InputValidationError(dedicated_runtime.WORKER_UNAVAILABLE)- value = json.loads(raw)+ return {"error_code": "inference_rejected"}+ value = json.loads(reply.get("body") or b"{}")+ if "decisions" in payload:+ answers = value.get("answers") or {}+ value["predictions"] = [+ {+ "options": item["options"],+ "probabilities": [+ float(+ ((answers.get(str(index)) or {}).get("probabilities") or {}).get(option)+ or 0+ )+ for option in item["options"]+ ],+ }+ for index, item in enumerate(payload["decisions"])+ ]+ return valuechoice = (value.get("choices") or [{}])[0]- message = choice.get("message") or {}return {- "content": message.get("content") or "",+ "content": (choice.get("message") or {}).get("content") or "","usage": value.get("usage"),"finish_reason": choice.get("finish_reason"),- "latency_ms": (timezone.now() - started).total_seconds() * 1000,}diff --git a/overbae/services/dedicated_runtime.py b/overbae/services/dedicated_runtime.pyindex d7a9f02e..4fd70ade 100644--- a/overbae/services/dedicated_runtime.py+++ b/overbae/services/dedicated_runtime.py@@ -319,7 +319,7 @@ def _post(deployment, body: bytes, *, stream: bool, payload: bytes | None = Noneif not base:raise InputValidationError(WORKER_UNAVAILABLE)if payload is None:- payload = _served_body(deployment, body, stream=stream)+ payload = served_body(deployment, body, stream=stream)return _http().send(_http().build_request("POST",@@ -452,7 +452,7 @@ def shape_chat_payload(payload: dict, *, base_model_id: str) -> None:payload["structured_outputs"] = {"regex": _forced_tool_regex(spec.forced_tool_regex, names)}-def _served_body(deployment, body: bytes, *, stream: bool) -> bytes:+def served_body(deployment, body: bytes, *, stream: bool) -> bytes:try:payload = json.loads(body)except json.JSONDecodeError:@@ -560,7 +560,7 @@ def repair_forced_calls(raw: bytes, shaped: bytes) -> bytes:def chat(deployment, body: bytes) -> tuple[int, bytes, str]:- shaped = _served_body(deployment, body, stream=False)+ shaped = served_body(deployment, body, stream=False)response = _post(deployment, body, stream=False, payload=shaped)try:content_type = response.headers.get("content-type") or "application/json"diff --git a/overbae/services/inference_requests.py b/overbae/services/inference_requests.pyindex 82abdbdd..889711f5 100644--- a/overbae/services/inference_requests.py+++ b/overbae/services/inference_requests.py@@ -21,7 +21,7 @@ from modal_shared.operational_events import STOREfrom overbae.core.errors import InputValidationErrorfrom overbae.modal.model_registry import get_hf_basefrom overbae.models import InferenceCall, InferenceRequest, Project-from overbae.services import operational_progress+from overbae.services import dedicated, operational_progressfrom overbae.services.decision_serving import validate_requestsfrom overbae.services.deployed_chat import is_cold_start, record_inference_callfrom overbae.services.deployment import modal_environment, poll_operation, serving_gpu@@ -125,11 +125,14 @@ def submit(deployment, user, request_key, payload, *, source="mcp", dedicated=Noreturn request-async def bounded_call(method, *args, **kwargs):+async def bounded_call(method, /, *args, **kwargs):return await asyncio.wait_for(method(*args, **kwargs), timeout=10)def spawn(request):+ if request.payload.get("dedicated_id"):+ instance, arguments = dedicated.request_call(request.payload)+ return async_to_sync(bounded_call)(instance.infer.spawn.aio, **arguments).object_idfunction = modal.Function.from_name(request.payload.get("serving_app", "overmind-inference"),"inference_request",@@ -198,41 +201,11 @@ def advance(request_id):"state": "unresolved","error_code": "observation_deadline",}- elif request.state == "queued" and request.payload.get("dedicated_id"):- from overbae.services.dedicated import complete_request-- # Persist the intent before HTTP. Its acknowledgement cannot be recovered- # from the Modal request store, so an expired owner must never replay it.- owned.update(state="submitting", claim_until=request.deadline, updated_at=now)- try:- result = complete_request(request.payload)- result = {- key: result.get(key)- for key in (- "content",- "usage",- "finish_reason",- "latency_ms",- "predictions",- "model_identity",- )- }- changes = {- "state": "succeeded",- "result": result,- "completed_at": now,- "error_code": "",- }- except Exception:- logger.warning("Dedicated inference failed for %s", request.pk, exc_info=False)- changes = {- "state": "submission_unknown",- "error_code": "acknowledgement_unknown",- }elif request.state == "queued":owned.update(state="submitting", updated_at=now)- request.is_cold = is_cold_start(request.deployment)- owned.update(is_cold=request.is_cold)+ if not request.payload.get("dedicated_id"):+ request.is_cold = is_cold_start(request.deployment)+ owned.update(is_cold=request.is_cold)try:handle = spawn(request)changes = {"remote_id": handle, "state": "running"}@@ -249,6 +222,12 @@ def advance(request_id):)else:state, result = poll(request.remote_id)+ if (+ state == "complete"+ and request.payload.get("dedicated_id")+ and isinstance(result, dict)+ ):+ result = dedicated.request_result(request.payload, result)if state == "complete":if not isinstance(result, dict):changes = {diff --git a/overbae/services/native_evaluation.py b/overbae/services/native_evaluation.pyindex 35b8d0bb..d85df1af 100644--- a/overbae/services/native_evaluation.py+++ b/overbae/services/native_evaluation.py@@ -31,7 +31,7 @@ from overbae.models import (TrainingExperiment,)from overbae.services.compute_costs import estimate_usage-from overbae.services.datasets import paths, rows, use+from overbae.services.datasets import heartbeat, paths, rows, usefrom overbae.services.decision_benchmark_scoring import compare_suite, recordsfrom overbae.services.decision_calibration import fit_decision_calibrationfrom overbae.services.decision_providers import (@@ -927,7 +927,7 @@ def resume(plan, *, stage=None, call_id=None):requests.filter(state="failed", response__isnull=False).update(state="received", error="")call.pop("observe_started_at", None)call.pop("lease", None)- call.pop("lease_started_at", None)+ call.pop("lease_until", None)if local or external:plan.calls = {k: v for k, v in plan.calls.items() if k != pending}else:@@ -1256,9 +1256,8 @@ def advance(plan_id, *, stage=None):)call = dict(plan.calls.get(stage, {}))call.pop("retry_at", None)- since = call.get("lease_started_at") or call.get("intent_at")if call.get("lease") or call.get("state") == "submitting":- if since and (timezone.now() - datetime.fromisoformat(since)).total_seconds() < 1260:+ if stage_held(call):returnif not local and not external and not reused and not call.get("id"):plan.calls = {**plan.calls, stage: {**call, "state": "submission_unknown"}}@@ -1277,7 +1276,7 @@ def advance(plan_id, *, stage=None):**call,"state": "submitting" if starting else "running","lease": lease,- "lease_started_at": timezone.now().isoformat(),+ "lease_until": heartbeat.lease_end().isoformat(),"last_queue_wait_seconds": queue_wait,}plan.calls = {**plan.calls, stage: call}@@ -1285,114 +1284,142 @@ def advance(plan_id, *, stage=None):if not preparing_only:plan.state = "running"plan.save()- observed_at = time.perf_counter()- receipt = None+ beat = heartbeat.start(+ lambda: renew_stage(plan.pk, stage, lease), owner=f"native evaluation {plan.pk} {stage}"+ )try:- if stage == "verify_inputs":- receipt = verify_inputs(plan)- elif stage == "fit_calibration":- receipt = fit_calibration(plan)- elif stage == "score":- receipt = score(plan)- elif reused:- role, participant, _, _ = provider_stage(plan, stage)- receipt = collect_reused(plan, role, participant)- elif external:- role, participant, _, _ = provider_stage(plan, stage)- receipt = external_step(plan, role, participant)- elif preparation_unavailable:- receipt = retain_partial(plan, stage)- receipt["issues"] = [{"error": "Required input preparation could not be collected."}]- elif starting:- call["id"] = submit(plan, stage)- receipt = None- else:- receipt = modal.FunctionCall.from_id(call["id"]).get(timeout=0)- collect(plan, stage, receipt)- call.pop("progress_error", None)- call.update(- state="completed"- if receipt is not None and (not external or reused or receipt["completed"])- else "running",- receipt=receipt["report"] if stage == "score" and receipt is not None else receipt,- )- call.pop("error", None)- call.pop("consecutive_failures", None)- except TimeoutError as exc:- if local or external or reused or starting or receipt is not None:- record_failure(call, exc, can_retry=local or external or reused or bool(call.get("id")))- else:- call["state"] = "running"+ observed_at = time.perf_counter()+ receipt = None+ try:+ if stage == "verify_inputs":+ receipt = verify_inputs(plan)+ elif stage == "fit_calibration":+ receipt = fit_calibration(plan)+ elif stage == "score":+ receipt = score(plan)+ elif reused:+ role, participant, _, _ = provider_stage(plan, stage)+ receipt = collect_reused(plan, role, participant)+ elif external:+ role, participant, _, _ = provider_stage(plan, stage)+ receipt = external_step(plan, role, participant)+ elif preparation_unavailable:+ receipt = retain_partial(plan, stage)+ receipt["issues"] = [+ {"error": "Required input preparation could not be collected."}+ ]+ elif starting:+ call["id"] = submit(plan, stage)+ receipt = None+ else:+ receipt = modal.FunctionCall.from_id(call["id"]).get(timeout=0)+ collect(plan, stage, receipt)+ call.pop("progress_error", None)+ call.update(+ state="completed"+ if receipt is not None and (not external or reused or receipt["completed"])+ else "running",+ receipt=receipt["report"] if stage == "score" and receipt is not None else receipt,+ )call.pop("error", None)call.pop("consecutive_failures", None)- if not starting and not local and not external and not reused:- try:- collect_progress(plan, stage, call)- except Exception:- logger.warning("Native progress unavailable: %s %s", plan_id, stage, exc_info=True)- call["progress_error"] = (- "Live worker progress is unavailable; retained results remain available."+ except TimeoutError as exc:+ if local or external or reused or starting or receipt is not None:+ record_failure(+ call, exc, can_retry=local or external or reused or bool(call.get("id")))- except Exception as exc:- logger.exception("Native evaluation stage failed: %s %s", plan_id, stage)- record_failure(call, exc, can_retry=local or external or reused or bool(call.get("id")))- if call["state"] == "failed" and not local:- if not external and not reused and call.get("id"):+ else:+ call["state"] = "running"+ call.pop("error", None)+ call.pop("consecutive_failures", None)+ if not starting and not local and not external and not reused:+ try:+ collect_progress(plan, stage, call)+ except Exception:+ logger.warning(+ "Native progress unavailable: %s %s", plan_id, stage, exc_info=True+ )+ call["progress_error"] = (+ "Live worker progress is unavailable; retained results remain available."+ )+ except Exception as exc:+ logger.exception("Native evaluation stage failed: %s %s", plan_id, stage)+ record_failure(call, exc, can_retry=local or external or reused or bool(call.get("id")))+ if call["state"] == "failed" and not local:+ if not external and not reused and call.get("id"):+ try:+ collect_progress(plan, stage, call)+ except Exception:+ logger.warning(+ "Final progress unavailable; retaining verified local results: %s %s",+ plan_id,+ stage,+ exc_info=True,+ )try:- collect_progress(plan, stage, call)+ call["receipt"] = retain_partial(plan, stage)+ call["state"] = "completed"except Exception:- logger.warning(- "Final progress unavailable; retaining verified local results: %s %s",- plan_id,- stage,- exc_info=True,+ logger.exception(+ "Partial evaluation results could not be retained: %s %s", plan_id, stage)- try:- call["receipt"] = retain_partial(plan, stage)- call["state"] = "completed"- except Exception:- logger.exception(- "Partial evaluation results could not be retained: %s %s", plan_id, stage+ elif call["state"] == "failed" and stage == "fit_calibration":+ calibration = {+ "arms": {},+ "unavailable": {p["key"]: call["error"] for p in participants(plan)},+ "fitted_on": "calibration",+ "decisions": 0,+ }+ NativeEvaluationPlan.objects.filter(pk=plan.pk, calibration={}).update(+ calibration=calibration)- elif call["state"] == "failed" and stage == "fit_calibration":- calibration = {- "arms": {},- "unavailable": {p["key"]: call["error"] for p in participants(plan)},- "fitted_on": "calibration",- "decisions": 0,- }- NativeEvaluationPlan.objects.filter(pk=plan.pk, calibration={}).update(- calibration=calibration- )- call.update(state="completed", receipt={"partial": True})+ call.update(state="completed", receipt={"partial": True})+ with transaction.atomic():+ locked = NativeEvaluationPlan.objects.select_for_update().get(pk=plan.pk)+ if locked.calls.get(stage, {}).get("lease") != lease:+ return+ call["observation_active_seconds"] = (+ call.get("observation_active_seconds", 0) + time.perf_counter() - observed_at+ )+ call["observed_at"] = timezone.now().isoformat()+ call["timing_scope"] = (+ "local stage execution and provider observation; native provider compute duration is separate"+ )+ call.pop("enqueued_at", None)+ call.pop("lease", None)+ call.pop("lease_until", None)+ locked.calls = {**locked.calls, stage: call}+ if (+ stage == "verify_inputs"+ and preparing_only+ and call["state"] == "completed"+ and locked.state != "paused"+ ):+ locked.state = "prepared"+ elif stage == "score" and call["state"] == "completed":+ locked.state, locked.results = "completed", receipt+ else:+ settle(locked)+ locked.save()+ finally:+ beat.set()+ refresh_safely(locked)+++def stage_held(call):+ lease_until = call.get("lease_until")+ return bool(lease_until) and datetime.fromisoformat(lease_until) > timezone.now()+++def renew_stage(plan_id, stage, lease):with transaction.atomic():- locked = NativeEvaluationPlan.objects.select_for_update().get(pk=plan.pk)- if locked.calls.get(stage, {}).get("lease") != lease:+ plan = NativeEvaluationPlan.objects.select_for_update().get(pk=plan_id)+ call = plan.calls.get(stage) or {}+ if call.get("lease") != lease:return- call["observation_active_seconds"] = (- call.get("observation_active_seconds", 0) + time.perf_counter() - observed_at- )- call["observed_at"] = timezone.now().isoformat()- call["timing_scope"] = (- "local stage execution and provider observation; native provider compute duration is separate"- )- call.pop("enqueued_at", None)- call.pop("lease", None)- call.pop("lease_started_at", None)- locked.calls = {**locked.calls, stage: call}- if (- stage == "verify_inputs"- and preparing_only- and call["state"] == "completed"- and locked.state != "paused"- ):- locked.state = "prepared"- elif stage == "score" and call["state"] == "completed":- locked.state, locked.results = "completed", receipt- else:- settle(locked)- locked.save()- refresh_safely(locked)+ call = {**call, "lease_until": heartbeat.lease_end().isoformat()}+ plan.calls = {**plan.calls, stage: call}+ plan.save(update_fields=["calls"])def describe(plan):diff --git a/overbae/services/queue_capacity.py b/overbae/services/queue_capacity.pyindex ced981be..598a709f 100644--- a/overbae/services/queue_capacity.py+++ b/overbae/services/queue_capacity.py@@ -11,6 +11,8 @@ from django.db.models import Count, Exists, Min, OuterRef, Qfrom django.utils import timezonefrom overbae.models import (+ AssistantInput,+ AssistantThread,DatasetImport,DatasetLandingWork,DatasetPipelineRun,@@ -25,6 +27,7 @@ WORKER_SERVICES = {"landing": "celery-landing-worker","batch": "celery-batch-worker","interactive": "celery-interactive-worker",+ "assistant": "celery-assistant-worker",}SYSTEM_BLOCKS = ("queue_timeout", "worker_timeout", "dispatch_failed", "attempts_exhausted")NEWLY_BLOCKED_SECONDS = 5 * 60@@ -134,11 +137,26 @@ def read_workloads():for row in project_demand),)+ # A reply holds a thread while it waits on a model, so CPU cannot show a full worker.+ asked = AssistantInput.objects.filter(state=AssistantInput.State.QUEUED)+ assistant = (+ AssistantThread.objects.annotate(asked=Exists(asked.filter(thread=OuterRef("pk"))))+ .filter(Q(state=AssistantThread.State.RUNNING) | Q(asked=True))+ .aggregate(+ waiting=Count("pk", filter=Q(state=AssistantThread.State.IDLE)),+ running=Count("pk", filter=Q(state=AssistantThread.State.RUNNING)),+ )+ )+ assistant["oldest"] = asked.filter(thread__state=AssistantThread.State.IDLE).aggregate(+ oldest=Min("created_at")+ )["oldest"]+ assistant["blocked"] = 0return {"io_traces": scoring,"landing": imports,"batch": evaluation,"interactive": workshop,+ "assistant": assistant,}diff --git a/overbae/services/training_experiments.py b/overbae/services/training_experiments.pyindex 74bcd7e4..27a60ca0 100644--- a/overbae/services/training_experiments.py+++ b/overbae/services/training_experiments.py@@ -2,7 +2,6 @@ import hashlibimport jsonimport loggingimport math-from datetime import datetimefrom types import SimpleNamespacefrom django.conf import settings@@ -23,7 +22,7 @@ from overbae.models import (TrainingExperiment,)from overbae.services import native_evaluation, training_plans, training_release-from overbae.services.datasets import rows, use+from overbae.services.datasets import heartbeat, rows, usefrom overbae.services.recommendation.candidates import dataset_total_tokensfrom overbae.services.training_contract import dataset_objectivefrom overbae.services.training_forecast import forecast@@ -343,15 +342,21 @@ def prepare(experiment):)if experiment.state not in {"draft", "preparing", "preparation_failed"}:return experiment- previous = experiment.protocol.get("preparation_started_at")- if previous and (timezone.now() - datetime.fromisoformat(previous)).total_seconds() < 1260:+ started = experiment.state == "preparing" and experiment.lease_until is not None+ taken = heartbeat.take(experiment, running=started)+ if taken == "held":+ return experiment+ if taken == "exhausted":+ experiment.state = "preparation_failed"+ experiment.protocol = {**experiment.protocol, "preparation_error": heartbeat.STOPPED}+ experiment.save()return experimentexperiment.state = "preparing"- experiment.protocol = {- **experiment.protocol,- "preparation_started_at": timezone.now().isoformat(),- }experiment.save()+ owned = TrainingExperiment.objects.filter(+ pk=experiment.pk, state="preparing", attempt=experiment.attempt+ )+ beat = heartbeat.hold(owned, owner=f"experiment preparation {experiment.pk}")try:forecasts, boundaries, cells = [], {}, {}evaluation = (@@ -407,9 +412,8 @@ def prepare(experiment):"scope": "planning_estimate_not_provider_spend_cap",}protocol = {**experiment.protocol, "forecast": quote, "boundaries": boundaries}- protocol.pop("preparation_started_at", None)- TrainingExperiment.objects.filter(pk=experiment.pk, state="preparing").update(- state="prepared", protocol=protocol, updated_at=timezone.now()+ owned.update(+ state="prepared", protocol=protocol, lease_until=None, updated_at=timezone.now())except Exception:logger.exception("Experiment preparation failed: %s", experiment.pk)@@ -417,10 +421,14 @@ def prepare(experiment):**experiment.protocol,"preparation_error": "Preparation failed; inspect source versions and recipe diagnostics before retrying",}- protocol.pop("preparation_started_at", None)- TrainingExperiment.objects.filter(pk=experiment.pk, state="preparing").update(- state="preparation_failed", protocol=protocol, updated_at=timezone.now()+ owned.update(+ state="preparation_failed",+ protocol=protocol,+ lease_until=None,+ updated_at=timezone.now(),)+ finally:+ beat.set()experiment.refresh_from_db()return experimentdiff --git a/overbae/services/training_preparation.py b/overbae/services/training_preparation.pyindex 814451fc..3b62b8a0 100644--- a/overbae/services/training_preparation.py+++ b/overbae/services/training_preparation.py@@ -6,6 +6,7 @@ import ioimport jsonimport mathimport tempfile+import uuidfrom datetime import timedeltafrom pathlib import Path@@ -32,6 +33,7 @@ from overbae.modal.model_registry import (from overbae.modal.training_type import training_context_length, training_enabledfrom overbae.models import DecisionJob, FinetuningJob, Project, TrainingPreparationfrom overbae.services import operational_progress, training_release+from overbae.services.datasets import heartbeatfrom overbae.services.datasets import rows as row_storefrom overbae.services.datasets import use as dataset_usefrom overbae.services.finetuning_policy import (@@ -362,17 +364,28 @@ def advance(preparation_id):prep.save(update_fields=["state", "error", "report", "touched_at"])returnif prep.state == "starting":- if prep.touched_at < now - timedelta(minutes=30):+ if prep.touched_at >= now - timedelta(seconds=heartbeat.STALE_SECONDS):+ return+ if prep.report.get("submitting"):prep.state, prep.error = ("failed","Preprocessing submission was interrupted before acknowledgement.",)prep.save(update_fields=["state", "error", "touched_at"])- return+ return+ # The worker stopped before it asked Modal for anything, so it starts again.+ prep.state = "queued"starting = prep.state == "queued"if starting:- prep.state = "starting"- prep.save(update_fields=["state", "touched_at"])+ prep.state, prep.attempt = "starting", uuid.uuid4()+ prep.save(update_fields=["state", "attempt", "touched_at"])+ # The export, the volume slot and the upload can each take minutes.+ beat = heartbeat.start(+ lambda: TrainingPreparation.objects.filter(+ pk=prep.pk, state="starting", attempt=prep.attempt+ ).update(touched_at=timezone.now()),+ owner=f"training preparation {prep.pk}",+ )try:if starting:training_release.verify(prep.config["runtime"])@@ -388,23 +401,30 @@ def advance(preparation_id):total_rows = prep.cell.rows + (prep.validation_cell.rows if prep.validation_cell else 0)report_interval = max(1, min(1000, total_rows // 10))- def report_export(stage, completed_rows):- TrainingPreparation.objects.filter(- pk=prep.pk, state="starting", deadline=prep.deadline+ def report_export(stage, completed_rows, **marks):+ held = TrainingPreparation.objects.filter(+ pk=prep.pk, state="starting", attempt=prep.attempt).update(report={"progress": {"stage": stage,"completed_rows": completed_rows,"total_rows": total_rows,- }+ },+ **marks,},touched_at=timezone.now(),)- operational_progress.preparation(- prep,- {"stage": stage, "completed_rows": completed_rows, "total_rows": total_rows},- )+ if held:+ operational_progress.preparation(+ prep,+ {+ "stage": stage,+ "completed_rows": completed_rows,+ "total_rows": total_rows,+ },+ )+ return heldcompleted_rows = 0report_export("exporting", completed_rows)@@ -458,11 +478,15 @@ def advance(preparation_id):"prepare_" + train_function_name(prep.config["stack"]),environment_name=prep.config["runtime"]["environment"],)+ # From here a lost worker may have started a paid call it never recorded. A worker+ # whose start was handed to another attempt stops before it calls Modal.+ if not report_export("uploading", completed_rows, submitting=True):+ returncall = function.spawn(str(prep.id), {**prep.config, "rows_path": "/data" + remote, "rows_sha256": digest})TrainingPreparation.objects.filter(- pk=prep.pk, state="starting", deadline=prep.deadline+ pk=prep.pk, state="starting", attempt=prep.attempt).update(state="running", remote_id=call.object_id, touched_at=timezone.now())else:report = validate_preparation_report(@@ -491,7 +515,7 @@ def advance(preparation_id):# 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+ pk=prep.pk, state__in=["starting", "running"], attempt=prep.attempt).update(state="queued" if volume_busy else "failed",error="" if volume_busy else str(exc)[:1000],@@ -500,6 +524,8 @@ def advance(preparation_id):else {"retryable": not starting or isinstance(exc, NotFoundError)},touched_at=timezone.now(),)+ finally:+ beat.set()def ready_for_job(job, context_length):diff --git a/overbae/tasks/capability_rebind.py b/overbae/tasks/capability_rebind.pyindex 52493f93..10549599 100644--- a/overbae/tasks/capability_rebind.py+++ b/overbae/tasks/capability_rebind.py@@ -36,7 +36,13 @@ def _probes(span) -> list[str]:return [str(v) for v in raw if v and str(v) not in _GENERIC_NAMES]-@shared_task(name="overbae.tasks.capability_rebind.rebind_unbound_spans")+# Idempotent, so a run lost with its worker is delivered again once the broker's+# visibility timeout passes.+@shared_task(+ name="overbae.tasks.capability_rebind.rebind_unbound_spans",+ acks_late=True,+ reject_on_worker_lost=True,+)def rebind_unbound_spans(*, project_id: str) -> dict:from overbae.models import Span # noqa: PLC0415diff --git a/overbae/tasks/connector_sync.py b/overbae/tasks/connector_sync.pyindex caee7243..0f8af4ae 100644--- a/overbae/tasks/connector_sync.py+++ b/overbae/tasks/connector_sync.py@@ -16,6 +16,7 @@ from overbae.api.otlp import enqueue_scoringfrom overbae.services.connectors.progress import checkpoint_progressfrom overbae.services.connectors.schema import CONNECTOR_VERSION_ATTRfrom overbae.services.connectors.sync import connector_imported_spans+from overbae.services.datasets import heartbeatfrom overbae.services.span_pricing import stamp_span_costlogger = logging.getLogger(__name__)@@ -27,9 +28,6 @@ _BACKOFF_CAP_SECONDS = 3600_MAX_SYNC_RETRIES = 12_CHUNK_HARD_TIME_LIMIT = 60 * 20_CHUNK_SOFT_TIME_LIMIT = 60 * 18-# A lease that ends before the hard limit lets the poller start a second chunk on-# the same cursor while the first still runs.-_LEASE_SECONDS = _CHUNK_HARD_TIME_LIMIT + 120def _match_capabilities_by_name(project, spans: list) -> None:@@ -417,29 +415,44 @@ def sync_connector_chunk(credential_id: str) -> dict:if credential.connector_type not in registered_sources():return {"status": "skipped", "reason": "unsupported_connector_type"}- now = timezone.now()+ # next_poll_at doubles as the chunk's lease. The heartbeat renews it only while it+ # still holds the value this chunk last wrote, so the chunk's own reschedule ends it.+ lease = {"until": heartbeat.lease_end()}claimed = (ConnectorCredential.objects.filter(pk=credential.pk)- .filter(Q(next_poll_at__isnull=True) | Q(next_poll_at__lte=now))- .update(next_poll_at=now + timedelta(seconds=_LEASE_SECONDS))+ .filter(Q(next_poll_at__isnull=True) | Q(next_poll_at__lte=timezone.now()))+ .update(next_poll_at=lease["until"]))if not claimed:return {"status": "skipped", "reason": "leased"}- credential.refresh_from_db()- prepare_connector_sync(credential)- cursor = dict(credential.sync_cursor or {})- if "mode" not in cursor:- cursor["mode"] = "live" if cursor.get("watermark") else "backfill"+ def renew():+ until = heartbeat.lease_end()+ if ConnectorCredential.objects.filter(pk=credential.pk, next_poll_at=lease["until"]).update(+ next_poll_at=until+ ):+ lease["until"] = until+ # Preparation can delete every imported span on a recarve, so it runs under the lease.+ beat = heartbeat.start(renew, owner=f"connector sync {credential.pk}")try:- return _run_adapter_chunk(credential, cursor)- except SoftTimeLimitExceeded:- ConnectorCredential.objects.filter(pk=credential.pk).update(next_poll_at=None)- _schedule_next_chunk(credential)- return {"status": "soft_timeout_resumed"}- except Exception as exc:- return _apply_backoff(credential, exc)+ credential.refresh_from_db()+ prepare_connector_sync(credential)++ cursor = dict(credential.sync_cursor or {})+ if "mode" not in cursor:+ cursor["mode"] = "live" if cursor.get("watermark") else "backfill"++ try:+ return _run_adapter_chunk(credential, cursor)+ except SoftTimeLimitExceeded:+ ConnectorCredential.objects.filter(pk=credential.pk).update(next_poll_at=None)+ _schedule_next_chunk(credential)+ return {"status": "soft_timeout_resumed"}+ except Exception as exc:+ return _apply_backoff(credential, exc)+ finally:+ beat.set()@shared_task(name="overbae.tasks.connector_sync.sweep_abandoned_drafts")diff --git a/overbae/tasks/data_exploration.py b/overbae/tasks/data_exploration.pyindex 4b662ff7..d9cf5be0 100644--- a/overbae/tasks/data_exploration.py+++ b/overbae/tasks/data_exploration.py@@ -1,10 +1,8 @@-from datetime import timedelta-from celery import shared_taskfrom django.db.models import Q-from django.utils import timezonefrom overbae.models import DataExploration+from overbae.services.datasets import heartbeatfrom overbae.services.datasets.exploration import advance@@ -12,8 +10,7 @@ from overbae.services.datasets.exploration import advancedef reconcile():for identifier in (DataExploration.objects.filter(- Q(state="queued")- | Q(state="running", updated_at__lt=timezone.now() - timedelta(seconds=1260))+ Q(state="queued") | (Q(state="running") & heartbeat.lapsed())).values_list("pk", flat=True).iterator()diff --git a/overbae/tasks/data_partitions.py b/overbae/tasks/data_partitions.pyindex 38eaf293..f2de5ede 100644--- a/overbae/tasks/data_partitions.py+++ b/overbae/tasks/data_partitions.py@@ -1,18 +1,15 @@-from datetime import timedelta-from celery import shared_taskfrom django.db.models import Q-from django.utils import timezonefrom overbae.models import DataPartitionPlan+from overbae.services.datasets import heartbeatfrom overbae.services.datasets.partition_plans import build@shared_task(name="overbae.tasks.data_partitions.reconcile")def reconcile():pending = DataPartitionPlan.objects.filter(- Q(state="queued")- | Q(state="running", updated_at__lt=timezone.now() - timedelta(seconds=1260))+ Q(state="queued") | (Q(state="running") & heartbeat.lapsed()))for plan_id in pending.values_list("pk", flat=True).iterator():build_plan.delay(str(plan_id))diff --git a/overbae/tasks/datasets.py b/overbae/tasks/datasets.pyindex 703bc3a3..f23d13a9 100644--- a/overbae/tasks/datasets.py+++ b/overbae/tasks/datasets.py@@ -509,7 +509,6 @@ def refresh_pipeline_bindings():)def execute_pipeline(self, run_id):import uuid- from datetime import timedeltafrom billiard.exceptions import SoftTimeLimitExceeded@@ -517,13 +516,16 @@ def execute_pipeline(self, run_id):from overbae.services.datasets import heartbeat, pipeline_runner, workbenchrun = DatasetPipelineRun.objects.select_related("dataset").filter(pk=run_id).first()- # A lost worker can be redelivered, but a claimed script is never replayed.+ # Celery never replays a claimed run; a lost one comes back queued under a new attempt.if run is None or run.state != "queued":return- if run.created_at < timezone.now() - timedelta(seconds=pipeline_runner.QUEUE_SECONDS):+ cutoff = timezone.now()+ if run.lease_until is not None and run.lease_until < cutoff:workbench.fail(run.pk,"The run waited 15 minutes for interactive capacity. Submit a new request key to retry.",+ expired_before=cutoff,+ attempt=run.attempt,)returnowner = uuid.uuid4().hex@@ -543,7 +545,9 @@ def execute_pipeline(self, run_id):workbench.execute(run_id, script_executor=pipeline_runner.execute_script)except SoftTimeLimitExceeded:workbench.fail(- run_id, "The interactive task exceeded its 25 minute deadline. No script was replayed."+ run_id,+ "The interactive task exceeded its 25 minute deadline. No output was published.",+ attempt=run.attempt,)raisefinally:diff --git a/overbae/tasks/decision_performance.py b/overbae/tasks/decision_performance.pyindex 31d8fb69..2159a41f 100644--- a/overbae/tasks/decision_performance.py+++ b/overbae/tasks/decision_performance.py@@ -1,10 +1,8 @@-from datetime import timedelta-from celery import shared_taskfrom django.db.models import Q-from django.utils import timezonefrom overbae.models import DecisionPerformanceRun+from overbae.services.datasets import heartbeatfrom overbae.services.decision_performance import advance@@ -18,8 +16,7 @@ def measure(run_id):@shared_task(name="overbae.tasks.decision_performance.reconcile")def reconcile():runs = DecisionPerformanceRun.objects.filter(- Q(state="queued")- | Q(state="running", updated_at__lt=timezone.now() - timedelta(seconds=1260))+ Q(state="queued") | (Q(state="running") & heartbeat.lapsed()))for run_id in runs.values_list("pk", flat=True).iterator():measure.delay(str(run_id))diff --git a/overbae/tasks/innermind.py b/overbae/tasks/innermind.pyindex 13748989..6c30f44a 100644--- a/overbae/tasks/innermind.py+++ b/overbae/tasks/innermind.py@@ -17,6 +17,7 @@ from django.db.models import Qfrom overbae.core import async_loopfrom overbae.innermind import admission, generation, runs, signals, span_processor, trajectoryfrom overbae.models import EvalRun, EvalRunRow, Span+from overbae.services.datasets import heartbeatlogger = logging.getLogger(__name__)@@ -210,8 +211,8 @@ def dispatch_generation() -> dict:return generation.dispatch(publish, publish_scoring)-# A claimed admission is never replayed after a worker loss; the dispatcher records an-# unknown outcome once the running lease expires. Prefork enforces the time limit.+# A claimed admission is never replayed by Celery; a heartbeat renews the row's lease, and+# the dispatcher retries or records the row once it lapses. Prefork enforces the time limit.@shared_task(name="overbae.tasks.innermind.generate_row",bind=True,@@ -221,28 +222,37 @@ def dispatch_generation() -> dict:time_limit=1320,)def generate_row(self, *, row_id: str) -> str:- if not generation.claim(row_id, self.request.id):+ task_id = self.request.id+ if not generation.claim(row_id, task_id):return row_id+ beat = heartbeat.hold(+ generation.owned(row_id, task_id), owner=f"eval row {row_id}", field="expires_at"+ )try:- row = EvalRunRow.objects.select_related("run__cell", "run__model_ref").get(pk=row_id)+ row = (+ EvalRunRow.objects.select_related("run__cell", "run__model_ref")+ .filter(pk=row_id, task_id=task_id)+ .first()+ )+ if row is None:+ return row_idgeneration.generate(row)except generation.GenerationStoppedError:passexcept SoftTimeLimitExceeded:- record_row_error(row_id, "generation timed out (exceeded soft_time_limit)")+ record_row_error(row_id, task_id, "generation timed out (exceeded soft_time_limit)")except Exception as exc: # noqa: BLE001 — the row records the failure; the run carries onlogger.exception("generation failed for row %s", row_id)- record_row_error(row_id, str(exc))+ record_row_error(row_id, task_id, str(exc))finally:- generation.finish(row_id, self.request.id)+ beat.set()+ generation.finish(row_id, task_id)wake_generation_dispatcher()return row_id-def record_row_error(row_id: str, error: str) -> None:- EvalRunRow.objects.filter(pk=row_id).exclude(run__status__in=EvalRun.TERMINAL).update(- error=error- )+def record_row_error(row_id: str, task_id: str, error: str) -> None:+ generation.owned(row_id, task_id).exclude(run__status__in=EvalRun.TERMINAL).update(error=error)@shared_task(diff --git a/overbae/tasks/native_evaluation.py b/overbae/tasks/native_evaluation.pyindex 79495271..6c3fe5ce 100644--- a/overbae/tasks/native_evaluation.py+++ b/overbae/tasks/native_evaluation.py@@ -6,7 +6,7 @@ from django.db import transactionfrom django.utils import timezonefrom overbae.models import FinetuningJob, NativeEvaluationPlan, TrainingExperiment-from overbae.services.native_evaluation import advance, ready_stages+from overbae.services.native_evaluation import advance, ready_stages, stage_heldfrom overbae.services.native_evaluation_monitor import refresh_safely@@ -65,12 +65,7 @@ def advance_plan(plan_id, stage=None):locked = NativeEvaluationPlan.objects.select_for_update().get(pk=plan.pk)call = dict(locked.calls.get(ready, {}))queued = call.get("enqueued_at")- leased = call.get("lease_started_at")- if (- call.get("lease")- and leased- and (timezone.now() - datetime.fromisoformat(leased)).total_seconds() < 1260- ) or (+ if (call.get("lease") and stage_held(call)) or (queued and (timezone.now() - datetime.fromisoformat(queued)).total_seconds() < 60):continuediff --git a/overbae/tasks/training_experiments.py b/overbae/tasks/training_experiments.pyindex 846535ed..2a765d73 100644--- a/overbae/tasks/training_experiments.py+++ b/overbae/tasks/training_experiments.py@@ -1,9 +1,7 @@-from datetime import datetime-from celery import shared_task-from django.utils import timezonefrom overbae.models import TrainingExperiment+from overbae.services.datasets import heartbeat@shared_task(@@ -20,13 +18,10 @@ def prepare_experiment(identifier):@shared_task(name="overbae.tasks.training_experiments.reconcile")def reconcile():- for experiment in TrainingExperiment.objects.filter(state="preparing"):- started = experiment.protocol.get("preparation_started_at")- if (- not started- or (timezone.now() - datetime.fromisoformat(started)).total_seconds() >= 1260- ):- prepare_experiment.delay(str(experiment.pk))+ for identifier in TrainingExperiment.objects.filter(+ heartbeat.lapsed(), state="preparing"+ ).values_list("pk", flat=True):+ prepare_experiment.delay(str(identifier))# The service imports this task through API serializers.from overbae.services.training_experiments import reconcile as reconcile_experimentdiff --git a/tests/test_connector_poll.py b/tests/test_connector_poll.pyindex 28b13843..fb39594c 100644--- a/tests/test_connector_poll.py+++ b/tests/test_connector_poll.py@@ -21,6 +21,7 @@ from overbae.services.connectors.sync import (enqueue_connector_sync,reset_connector_import,)+from overbae.services.datasets import heartbeatfrom overbae.services.mcp.resources import connector_resource_payloadfrom overbae.tasks import connector_sync@@ -192,13 +193,13 @@ def test_the_poller_queues_only_due_active_auto_syncing_connectors(credential, cassert continuations == [str(credential.id)]-def test_the_poller_leaves_a_running_chunk_alone_until_its_time_limit_has_passed(+def test_the_poller_leaves_a_running_chunk_alone_while_its_lease_lasts(credential, langfuse, continuations, monkeypatch):_traces(langfuse, 1)ConnectorCredential.objects.filter(id=credential.id).update(auto_sync_enabled=True)langfuse.status = 429- still_running = timedelta(seconds=connector_sync.sync_connector_chunk.time_limit - 60)+ still_running = timedelta(seconds=heartbeat.STALE_SECONDS - 60)polled: list[int] = []def vendor_backoff(_seconds):diff --git a/tests/test_context_budget.py b/tests/test_context_budget.pyindex a760713b..49b27334 100644--- a/tests/test_context_budget.py+++ b/tests/test_context_budget.py@@ -152,7 +152,9 @@ def test_truncated_generation_stays_visible_but_cannot_be_a_quality_score(fake_lmodel_name="gpt-4.1",matrix=[{"name": "Report", "type": "llm", "source": "The output is the report."}],)- row = EvalRunRow.objects.create(run=run, row_index=0)+ row = EvalRunRow.objects.create(+ run=run, row_index=0, state=EvalRunRow.State.RUNNING, task_id="generation"+ )train = frozen_dataset(project, TRAIN_ROWS, contract="train")job = FinetuningJob.objects.create(project=project, dataset=train, base_model="Qwen/Qwen3.5-27B", status="succeeded"diff --git a/tests/test_dedicated_deployment.py b/tests/test_dedicated_deployment.pyindex 21e85f1e..c85e0a7d 100644--- a/tests/test_dedicated_deployment.py+++ b/tests/test_dedicated_deployment.py@@ -3,15 +3,11 @@from __future__ import annotationsimport json-import threadingimport uuid-from concurrent.futures import ThreadPoolExecutorfrom datetime import timedelta-import httpximport pytestfrom conftest import drain_stream-from django.db import close_old_connectionsfrom django.utils import timezonefrom rest_framework.test import APIClientfrom rest_framework_simplejwt.tokens import RefreshToken@@ -346,9 +342,8 @@ def test_failed_warmup_releases_the_remote_floor_before_becoming_terminal(fake_massert row.stopped_at is not None[email protected]_db(transaction=True)@pytest.mark.covers("work-once")-def test_dedicated_request_holds_its_claim_while_the_provider_runs(fake_modal, scripted):+def test_a_dedicated_request_is_read_back_from_its_saved_call(fake_modal):user = _user()project = Project.objects.create(name="Dedicated request")model = _ready(project)@@ -356,20 +351,7 @@ def test_dedicated_request_holds_its_claim_while_the_provider_runs(fake_modal, srow = dedicated.start(model, user, gpu_type="H100")row.status = "online"row.save(update_fields=["status"])- fake_modal.deploy(- "overmind-dedicated",- "H100_vllm_dedicated.direct_url",- lambda **kwargs: "https://audit-dedicated.test",- )- started, release = threading.Event(), threading.Event()-- def respond(call):- started.set()- assert release.wait(10)- result = _ok()- return result["status"], result["headers"], result["body"]-- provider = scripted("https://audit-dedicated.test").then(respond)+ fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok, held=True)request = inference_requests.submit(model,user,@@ -377,32 +359,18 @@ def test_dedicated_request_holds_its_claim_while_the_provider_runs(fake_modal, s{"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 32},dedicated=row,)-- def advance():- try:- inference_requests.advance(request.pk)- finally:- close_old_connections()-- with ThreadPoolExecutor(max_workers=1) as executor:- future = executor.submit(advance)- try:- assert started.wait(10)- request.refresh_from_db()- assert request.state == "submitting"- assert request.claim_until >= timezone.now() + timedelta(seconds=300)- inference_requests.advance(request.pk)- assert len(provider.calls) == 1- finally:- release.set()- future.result(timeout=10)+ inference_requests.advance(request.pk)+ # A worker that takes over reads the saved call instead of sending the request again.+ inference_requests.advance(request.pk)+ fake_modal.release("H100_vllm_dedicated.infer")+ inference_requests.advance(request.pk)request.refresh_from_db()- assert request.state == "succeeded"- assert request.result["content"] == "hi"+ assert request.state == "succeeded" and request.result["content"] == "hi"+ assert fake_modal.spawns() == ["H100_vllm_dedicated.infer"]@pytest.mark.covers("work-once")-def test_dedicated_unknown_acknowledgement_is_never_replayed(fake_modal, scripted):+def test_dedicated_unknown_acknowledgement_is_never_replayed(fake_modal):user = _user()project = Project.objects.create(name="Unknown dedicated acknowledgement")model = _ready(project)@@ -410,14 +378,6 @@ def test_dedicated_unknown_acknowledgement_is_never_replayed(fake_modal, scripterow = dedicated.start(model, user, gpu_type="H100")row.status = "online"row.save(update_fields=["status"])- fake_modal.deploy(- "overmind-dedicated",- "H100_vllm_dedicated.direct_url",- lambda **kwargs: "https://audit-dedicated.test",- )- provider = scripted("https://audit-dedicated.test").fail(- httpx.ReadTimeout("acknowledgement lost")- )request = inference_requests.submit(model,user,@@ -426,7 +386,8 @@ def test_dedicated_unknown_acknowledgement_is_never_replayed(fake_modal, scriptededicated=row,)inference_requests.advance(request.pk)+ fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)inference_requests.advance(request.pk)request.refresh_from_db()assert request.state == "submission_unknown"- assert len(provider.calls) == 1+ assert fake_modal.spawns() == []diff --git a/tests/test_job_leases.py b/tests/test_job_leases.pynew file mode 100644index 00000000..f307f324--- /dev/null+++ b/tests/test_job_leases.py@@ -0,0 +1,48 @@+from datetime import timedelta++import pytest+from django.utils import timezone+from test_data_first_workflow import workspace++from overbae.models import DataExploration+from overbae.services.datasets import exploration, heartbeat+from overbae.tasks import data_exploration++pytestmark = [pytest.mark.django_db, pytest.mark.covers("recovery")]+++def _profile(project, dataset):+ return exploration.request(+ project,+ source_cell=dataset.active_cell,+ name="Profile",+ request_key="profile",+ kind="profile",+ sampling_request=None,+ )+++def test_a_lost_job_restarts_once_its_lease_lapses_and_fails_after_three_losses(monkeypatch):+ project, _, dataset = workspace()+ op = _profile(project, dataset)+ started = []+ monkeypatch.setattr(data_exploration.run, "delay", started.append)+ rows = DataExploration.objects.filter(pk=op.pk)++ rows.update(state="running", lease_until=timezone.now() + timedelta(minutes=1))+ data_exploration.reconcile()+ assert started == []++ rows.update(lease_until=timezone.now() - timedelta(seconds=1))+ data_exploration.reconcile()+ assert started == [str(op.pk)]+ exploration.advance(op.pk)+ assert rows.get().state == "completed"++ rows.update(+ state="running",+ lease_until=timezone.now() - timedelta(seconds=1),+ attempts=heartbeat.MAX_ATTEMPTS - 1,+ )+ exploration.advance(op.pk)+ assert rows.values_list("state", "error").get() == ("failed", heartbeat.STOPPED)diff --git a/tests/test_mcp_research_journey.py b/tests/test_mcp_research_journey.pyindex da5c5661..bc068f95 100644--- a/tests/test_mcp_research_journey.py+++ b/tests/test_mcp_research_journey.py@@ -366,7 +366,7 @@ def test_expired_stage_lease_is_reconciled_after_worker_loss():"verify_inputs": {"state": "running","lease": "lost",- "lease_started_at": (timezone.now() - timedelta(seconds=1300)).isoformat(),+ "lease_until": (timezone.now() - timedelta(seconds=1)).isoformat(),}}plan.save()diff --git a/tests/test_native_evaluation_plan.py b/tests/test_native_evaluation_plan.pyindex 578b404b..77bcf9ce 100644--- a/tests/test_native_evaluation_plan.py+++ b/tests/test_native_evaluation_plan.py@@ -114,7 +114,7 @@ def test_many_question_report_stays_in_artifact_and_paused_scoring_recovers_withplan.calls["score"] = {"state": "submitting","lease": "stopped-worker",- "lease_started_at": native_evaluation.timezone.now().isoformat(),+ "lease_until": native_evaluation.timezone.now().isoformat(),}plan.state = "paused"plan.save()@@ -289,7 +289,7 @@ def test_paused_provider_collection_recovers_only_its_recorded_call(tmp_path, se"state": "running","id": "fc-existing","lease": "interrupted-collector",- "lease_started_at": native_evaluation.timezone.now().isoformat(),+ "lease_until": native_evaluation.timezone.now().isoformat(),}plan.save()for call_id in (None, "fc-different"):diff --git a/tests/test_queue_metrics.py b/tests/test_queue_metrics.pyindex c3378413..97b44856 100644--- a/tests/test_queue_metrics.py+++ b/tests/test_queue_metrics.py@@ -182,7 +182,7 @@ def test_publisher_uses_refreshing_task_role_instead_of_archive_keys(settings, msettings.QUEUE_METRICS_CLUSTER = "test-cluster"settings.AWS_REGION = "eu-west-1"try:- assert publish() == {"metrics": 33}+ assert publish() == {"metrics": 41}assert len(credential_reads) >= 2assert len(requests) == 2for _, headers in requests:@@ -320,3 +320,25 @@ def test_eval_demand_counts_only_rows_admission_can_start(settings):workload = read_workloads()["batch"]assert workload["waiting"] == 15001assert workload["scaling_demand"] == 4 + 1 + 1+++def test_assistant_demand_counts_replies_waiting_and_running():+ from overbae.models import AssistantInput, AssistantThread, Dataset, Project, User++ project = Project.objects.create(name="Assistant queues", slug="assistant-queues")+ user = User.objects.create_user(email="[email protected]")+ asked, replying, quiet = (+ AssistantThread.objects.create(+ project=project, dataset=Dataset.objects.create(project=project, name=name), state=state+ )+ for name, state in (("asked", "idle"), ("replying", "running"), ("quiet", "idle"))+ )+ for thread in (asked, replying):+ AssistantInput.objects.create(+ thread=thread, created_by=user, request_key="k", text="hi", position=0+ )++ demand = read_workloads()["assistant"]+ assert (demand["waiting"], demand["running"]) == (1, 1)+ assert demand["oldest"] is not Nonediff --git a/tests/test_training_preparation.py b/tests/test_training_preparation.pyindex acc48dd1..4a8bd599 100644--- a/tests/test_training_preparation.py+++ b/tests/test_training_preparation.py@@ -327,10 +327,26 @@ def test_layer_limit_on_a_running_call_keeps_the_remote_id(cell, monkeypatch):call.cancel.assert_called_once()+def test_a_start_lost_before_submission_starts_again(cell, monkeypatch):+ prep = preparation.request_preparation(cell, "Qwen/Qwen3-8B", 4096)+ prep.__class__.objects.filter(pk=prep.pk).update(+ state="starting", touched_at=timezone.now() - timedelta(minutes=6)+ )+ spawn = Mock(return_value=SimpleNamespace(object_id="fc-prep"))+ monkeypatch.setattr(+ preparation.modal.Function, "from_name", Mock(return_value=SimpleNamespace(spawn=spawn))+ )+ preparation.advance(prep.id)+ prep.refresh_from_db()+ assert spawn.call_count == 1 and prep.state == "running" and prep.remote_id == "fc-prep"++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(- state="starting", touched_at=timezone.now() - timedelta(minutes=31)+ state="starting",+ report={"submitting": True},+ touched_at=timezone.now() - timedelta(minutes=6),)preparation.advance(prep.id)prep.refresh_from_db()diff --git a/tests/test_workshop_mcp_acceptance.py b/tests/test_workshop_mcp_acceptance.pyindex 94aa75d5..8a5b1a3d 100644--- a/tests/test_workshop_mcp_acceptance.py+++ b/tests/test_workshop_mcp_acceptance.py@@ -376,8 +376,7 @@ def test_workbench_pages_every_immutable_recipe_without_losing_older_records():assert set(found) == saved[email protected]("interruption", ["cancel", "expire"])-def test_interrupted_worker_cannot_publish_over_a_newer_queued_run(interruption):+def test_cancelled_worker_cannot_publish_over_a_newer_queued_run():project, client, context = workspace()response = client.post("/api/datasets/",@@ -408,16 +407,9 @@ def test_interrupted_worker_cannot_publish_over_a_newer_queued_run(interruption)impact = workbench.measure.describe_framedef interrupt(*positional, **keyword):- if interruption == "cancel":- assert (- client.post(f"/api/datasets/{dataset.pk}/cancel/", {}, format="json").status_code- == 202- )- else:- DatasetPipelineRun.objects.filter(pk=first["run"]["id"]).update(- lease_until=timezone.now() - timedelta(seconds=1)- )- workbench.expire_runs()+ assert (+ client.post(f"/api/datasets/{dataset.pk}/cancel/", {}, format="json").status_code == 202+ )replacement.append(call(context, "run_dataset_pipeline", {**args, "request_key": "replacement"}))@@ -439,11 +431,61 @@ def test_interrupted_worker_cannot_publish_over_a_newer_queued_run(interruption)assert paths.cell_path(dataset.pk, source.pk).read_bytes() == originalstates = dict(dataset.pipeline_runs.values_list("request_key", "state"))assert states == {- "interrupted": "cancelled" if interruption == "cancel" else "failed",+ "interrupted": "cancelled","replacement": "completed",}+def test_a_run_whose_worker_stopped_runs_again_and_only_its_new_attempt_publishes():+ project, client, context = workspace()+ response = client.post(+ "/api/datasets/",+ {"project": str(project.pk), "source": {"rows": [{"text": "preserved"}]}},+ format="json",+ )+ dataset = Dataset.objects.get(pk=response.data["id"])+ source = dataset.active_cell+ recipe = call(+ context,+ "save_dataset_pipeline",+ {+ "dataset": str(dataset.pk),+ "name": "Select",+ "request_key": "select",+ "package": retained_package(context.project, context.user, [select_script(["text"])]),+ },+ )+ impact = workbench.measure.describe_frame++ def stop_worker(*positional, **keyword):+ DatasetPipelineRun.objects.filter(pk=run["run"]["id"]).update(+ lease_until=timezone.now() - timedelta(seconds=1)+ )+ workbench.expire_runs()+ return impact(*positional, **keyword)++ with patch("overbae.tasks.datasets.execute_pipeline.delay"):+ run = call(+ context,+ "run_dataset_pipeline",+ {+ "dataset": str(dataset.pk),+ "pipeline": recipe["pipeline"]["id"],+ "source_cell": str(source.pk),+ "source_fingerprint": source.fingerprint,+ "request_key": "handed-off",+ },+ )+ with patch.object(workbench.measure, "describe_frame", side_effect=stop_worker):+ workbench.execute(run["run"]["id"], script_executor=execute_fixture)+ handed = DatasetPipelineRun.objects.get(pk=run["run"]["id"])+ assert (handed.state, handed.handoffs, dataset.cells.count()) == ("queued", 1, 1)+ workbench.execute(handed.pk, script_executor=execute_fixture)+ handed.refresh_from_db()+ dataset.refresh_from_db()+ assert handed.state == "completed" and dataset.cells.count() == 2++def test_workbench_run_history_and_rest_pagination_remain_complete():project, client, context = workspace()response = client.post(diff --git a/tests/test_workshop_preparation_journey.py b/tests/test_workshop_preparation_journey.pyindex 36af2b65..8a99893d 100644--- a/tests/test_workshop_preparation_journey.py+++ b/tests/test_workshop_preparation_journey.py@@ -123,14 +123,15 @@ def test_worker_redelivery_never_replays_claimed_work_and_expiry_preserves_sourcfrom overbae.tasks.datasets import execute_pipeline- DatasetPipelineRun.objects.filter(pk=run.pk).update(- state="running", lease_until=timezone.now() - timedelta(seconds=1)- )- execute_pipeline(str(run.pk))- run.refresh_from_db()- assert run.state == "running"- workbench.expire_runs()- run.refresh_from_db()+ # A claimed run is never run by a redelivered message, and a run lost three times fails.+ for handoffs in (1, 2, 2):+ DatasetPipelineRun.objects.filter(pk=run.pk).update(+ state="running", lease_until=timezone.now() - timedelta(seconds=1)+ )+ execute_pipeline(str(run.pk))+ workbench.expire_runs()+ run.refresh_from_db()+ assert run.handoffs == handoffsassert run.state == "failed"assert run.output_id is Nonedataset.refresh_from_db()