Skip to content

The platform for continuously improving AI agents.

Let worker services shrink without losing users' work (#348)

Freyam Mehta899e0453fe71
diff --git a/.agents/skills/backend-architecture/references/assistant.md b/.agents/skills/backend-architecture/references/assistant.md
index 88b0730f..f10f4a52 100644
--- a/.agents/skills/backend-architecture/references/assistant.md
+++ b/.agents/skills/backend-architecture/references/assistant.md
@@ -6,7 +6,7 @@ The Console's assistant is a second author beside a customer's coding agent, sco
- A dataset has at most one `AssistantThread` (`dataset.assistant_thread`) and its append-only `AssistantEvent` log (`user`, `assistant`, `tool_result`, `status`, `summary`). The log is the model context and the transcript. Messages wait in `AssistantInput` until a turn delivers them.
- A turn is one Celery task (`tasks/assistant.run_turn`, queue `assistant`): from the delivered messages to a reply without tool calls, or to a `present` that asks a Question or Choices. `turn.wake` sends it after the commit that queued a message; a second task finds the thread taken and ends. The task starts the next turn itself when messages arrived while it ran.
-- A turn takes the thread by raising `AssistantThread.turn` and writes only while it still holds that number (`log.append(..., turn=)` raises `LostTurnError`). `updated_at` is its progress mark. `turn.settle`, called by every read of the thread and every message, marks a turn without progress for `STALE` (15 minutes) as interrupted; no process watches for it. A turn ends itself after `TURN_SECONDS`. An interrupted turn is never resumed: the next message starts a new one, and a call left without a result is answered as abandoned.
+- A turn takes the thread by raising `AssistantThread.turn` and writes only while it still holds that number (`log.append(..., turn=)` raises `LostTurnError`). `updated_at` is its progress mark, which a heartbeat also moves while the worker lives. The `resume_lost_turns` beat task (control queue, every minute) wakes a running turn whose mark is older than `turn.LEASE` (2 minutes); `run` takes it over under a new number, writes a `resumed` status and continues the reply from the log, where a call left without a result is answered as abandoned and never run again. After `turn.RESUMES` take-overs for one message, or when nothing resumed it for `STALE` (`turn.settle`, called by every read and message), the turn is marked interrupted. A turn ends itself after `TURN_SECONDS`.
- A message for a dataset whose source still lands waits: `_begin` leaves it queued, and the landing task calls `turn.wake_dataset` when it ends.
- A Console dataset made with `prepare` (the dialog sends it when an intent or a brief is given) queues `threads.queue_first_pass` in the create transaction, so its turn starts when the source lands. `turn.ready` holds that message while the dataset has no landed source, so a failed import keeps it queued for the next landing. A split queues one pass on the train half; the brief names the eval half (`split.sibling`), and both halves share the cleaning steps.
- A message is delivered with `threads.brief`: what the dataset holds now: its intent, the linked capability's contract, the split sibling, its pipeline, and for the source and latest versions their `data/<cell>.parquet` path, `fit`, exact `duplicate_rows` and a column profile (`store.frame_profile`, cached per frame). It is attached again only when it changed or a summary replaced the message that carried it.
diff --git a/.agents/skills/backend-architecture/references/celery.md b/.agents/skills/backend-architecture/references/celery.md
index 7820aae7..9ffa1246 100644
--- a/.agents/skills/backend-architecture/references/celery.md
+++ b/.agents/skills/backend-architecture/references/celery.md
@@ -22,22 +22,22 @@ Each worker consumes only its own queue. Beat runs as its own `celery-beat` serv
- `run_eval_run` routes to `io` because Modal warm-up blocks for minutes.
- `io_traces` is separate from `io` so trace scoring cannot occupy preparation or serving slots.
-Every prefork lane runs `--prefetch-multiplier=1 --disable-prefetch`. A reserved late-ack message is redelivered after the broker `visibility_timeout` (2 h), which must stay above every late-ack time limit.
+Every worker lane runs `--prefetch-multiplier=1 --disable-prefetch`. A reserved late-ack message is redelivered after the broker `visibility_timeout` (2 h), which must stay above every late-ack time limit.
## Routing must agree in four places
-`CELERY_TASK_ROUTES`, `make worker` (one local process, so its `-Q` lists every queue), docker-compose and `docker/worker-topology.json`. `tests/test_celery_topology.py` checks that compose and `make worker` drain every routed queue, rejects a time-limited task on a compose thread pool, checks the prefork prefetch flags and the `io`/`io_traces` split in `worker-topology.json`, and imports `overbae.tasks` in a fresh worker. Nothing checks that `worker-topology.json` drains every queue; keep it in step by hand. Workers hot-restart via watchmedo on `.py` changes.
+`CELERY_TASK_ROUTES`, `make worker` (one local process, so its `-Q` lists every queue), docker-compose and `docker/worker-topology.json`. `tests/test_celery_topology.py` checks that compose and `make worker` drain every routed queue, rejects a time-limited task on a compose thread pool, checks every lane's prefetch flags and the `io`/`io_traces` split in `worker-topology.json`, and imports `overbae.tasks` in a fresh worker. Nothing checks that `worker-topology.json` drains every queue; keep it in step by hand. Workers hot-restart via watchmedo on `.py` changes.
## Durable admission
Waiting work is a PostgreSQL row, admitted by a row-locked dispatcher in least-recent-project order:
- `LiveScoringWork` — spans, trajectories and signals; global and per-project caps; fenced running lease longer than the five-minute hard limit.
-- `DatasetLandingWork` — one import per project, global admission follows observed landing capacity up to eight. Waiting never expires unless `DATASET_IMPORT_MAX_QUEUE_SECONDS` is nonzero. A lost started import needs explicit recovery.
+- `DatasetLandingWork` — one import per project, global admission follows observed landing capacity up to eight. Waiting never expires unless `DATASET_IMPORT_MAX_QUEUE_SECONDS` is nonzero. A started import whose worker or document parser stopped goes back to waiting under a new owner until `imports.MAX_ATTEMPTS`; the claim counts each attempt, so a file that keeps killing its worker stops.
- `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 becomes an explicit unknown outcome. It 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`, 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.
## Leases and reconcilers
@@ -45,7 +45,7 @@ Frequent beat tasks (live-scoring admission, import and evaluation dispatch, Wor
## Deployment
-Hosted commands come from `docker/worker-topology.json`. A rollout runs migrations, verifies a healthy landing-only consumer on the new image (`overbae.worker_health <queue>`), then updates workers, beat and API. Drain old consumers before stopping them; never discard reserved tasks or revoke acknowledged provider work. Scale-in needs an explicit idle drain.
+Hosted commands come from `docker/worker-topology.json`. A release (`scripts/deploy_ecs.py`) changes only each task definition's image, command and entrypoint; Terraform in cloud-platform owns everything else, including health checks, stop timeouts, scratch volumes and environment. A rollout checks the consumer services exist, runs migrations as a one-off task (waiting up to `MIGRATION_SECONDS`), then updates every service at once; each waits until its tasks run the new revision, healthy where the task definition has a health check (`overbae.worker_health <queue>` on queue lanes). Drain old consumers before stopping them; never discard reserved tasks or revoke acknowledged provider work. A worker stopped by scale-in or a release loses its running tasks; its lease lapses and a reconciler recovers it (durable admission above; the evaluation and assistant references; data-workshop).
## HTTP clients
diff --git a/.agents/skills/backend-architecture/references/evaluation.md b/.agents/skills/backend-architecture/references/evaluation.md
index ec23eb4f..18cafcc0 100644
--- a/.agents/skills/backend-architecture/references/evaluation.md
+++ b/.agents/skills/backend-architecture/references/evaluation.md
@@ -5,7 +5,7 @@
An `EvalRun` scores one target (`mode` `recorded`, `generate` or `provided`) over one pinned dataset cell with a frozen `matrix` (`runs.freeze_matrix`: the eval set's rows, else every enabled row for the capability). Creating several `targets` makes one run per target under a shared `group`; REST creation allows at most one `is_baseline`. Training groups can mark several baselines, and `baseline_of` takes the newest completed one. Startup commits the running state and the complete row inventory atomically before admission; model warm-up stays outside that transaction.
- `innermind/runs.py` owns the lifecycle (create, launch, generate, score, aggregate, finish, cancel, relaunch, reap). `generation.py` and `replay.py` produce outputs. A `provided` run cannot relaunch.
-- `dataset.DatasetRowProcessor` scores rows with the live span evaluators and appends `EvalScore(source_type=dataset_row)`.
+- `dataset.DatasetRowProcessor` scores rows with the live span evaluators and saves each `EvalScore(source_type=dataset_row)` as it is written, only while the run's `scoring_task_id` is the scorer's own. The scorer beats `updated_at` every 30 s; `runs.reap_stalled` hands a silent one to a new scorer that skips saved rows (up to `SCORING_ATTEMPTS`), sends a pending run's start again after 10 minutes and fails it after 60.
- A row stands for the capability's answer: it takes every frozen row whose `span_type` is blank or `llm_call`, whatever its `span_name`. `tool_call`, `retrieval` and `workflow` rows stay live-only.
- An optimiser experiment reuses its first run's matrix for later candidates; a training job does the same for its evaluations.
- `comparison.compare` pairs the latest score per row that both runs scored into wins, losses and ties (`EPSILON` 0.005), and labels per-metric and overall means improved, regressed or unchanged; added and removed mark a metric present in only one run. It also reports trust.
diff --git a/.agents/skills/backend-architecture/references/tracing-and-scoring.md b/.agents/skills/backend-architecture/references/tracing-and-scoring.md
index ebcbdd22..1a635e42 100644
--- a/.agents/skills/backend-architecture/references/tracing-and-scoring.md
+++ b/.agents/skills/backend-architecture/references/tracing-and-scoring.md
@@ -6,7 +6,7 @@ Span-only: there is no Trace table. A trace is the spans sharing a `trace_id`; t
## Ingest
-`POST /api/v1/traces` (alias `/v1/traces`) accepts an OTLP protobuf or JSON export → flatten `ResourceSpans → ScopeSpans → Span` → bulk upsert on `span_id` → `process_span` → `enqueue_scoring`, which adds `LiveScoringWork` rows and wakes `dispatch_live_scoring`; `execute_live_scoring` then runs `span_processor.score_spans`. Connector imports use the same path.
+`POST /api/v1/traces` (alias `/v1/traces`) accepts an OTLP protobuf or JSON export of at most `MAX_EXPORT_BYTES` (20 MiB) before and after gzip, else 413 → flatten `ResourceSpans → ScopeSpans → Span` → bulk upsert on `span_id` → `process_span` → `enqueue_scoring`, which adds `LiveScoringWork` rows and wakes `dispatch_live_scoring`; `execute_live_scoring` then runs `span_processor.score_spans`. Connector imports use the same path.
Span cost has one owner: `services/span_pricing.stamp_span_cost` runs on every OTLP and connector span before storage. A reported cost (any alias, coalesced to `genai.cost`) is kept; otherwise `genai-prices` prices it from model, tokens and cache reads. The SDK never prices. Gateway billing is separate on purpose: it charges what OpenRouter reports (`usage.cost`), with `model_catalog.estimate_cost` list prices as the fallback.
diff --git a/.agents/skills/data-workshop/SKILL.md b/.agents/skills/data-workshop/SKILL.md
index 6ecfe568..160298b1 100644
--- a/.agents/skills/data-workshop/SKILL.md
+++ b/.agents/skills/data-workshop/SKILL.md
@@ -29,7 +29,7 @@ A customer's coding agent over MCP and the Console assistant own interpretation,
- CLI uploads use `DatasetTransfer`: a project request key binds SHA-256, byte count and destination. Up to 100 ordered files and 2 GiB per transfer; file order is part of identity; one batch becomes one source cell or one version. Repeat the identical command after an interruption. `get_job(kind=dataset_transfer)` reads byte and publication state; `dataset_run` reports landing. An explicit `--json-rows-field` selects a top-level JSON row array and is recorded.
- Local upload, export and checkpoint download authenticate separately from MCP. Without an explicit or repository key they use the address-bound account connection at `$XDG_CONFIG_HOME/overmind/connection.toml` (mode `0600`); repository keys are endpoint-bound too. `overmind connection check --project-id PROJECT --json` verifies MCP and transfer access from the invoking environment; MCP connectivity alone is not readiness. Verify the installed CLI from the workspace and from a repository-free directory.
- Confirmed permission denial uses the host's scoped approval. Missing credentials and transfer errors never authorize a browser fallback or an automatic sandbox-policy change.
-- Landing admission is one import per project, least-recent-project first, up to the observed landing capacity (backend-architecture `references/celery.md`). A lost started import needs explicit `resume_dataset_import`.
+- Landing admission is one import per project, least-recent-project first, up to the observed landing capacity (backend-architecture `references/celery.md`). A started import whose worker or document parser stopped is retried by `admission.reconcile` under a new owner, up to `imports.MAX_ATTEMPTS` in total; other failures need explicit `resume_dataset_import`.
- Trace sources pin `preferred_capability_id`. A unique matching invocation scopes I/O, transcript, usage and score; repeated invocations fail before publication; unmatched traces keep whole-trace evidence. Missing wrapper I/O stays missing and never borrows tool arguments.
## Documents and OCR
@@ -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: 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 fails runs past their lease without publishing partial output or replaying scripts.
- 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/docker-compose.yml b/docker-compose.yml
index f6a910bf..0e5a6585 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -143,7 +143,7 @@ services:
celery-control-worker:
<<: *build-common
entrypoint: ["/usr/local/bin/worker-entrypoint.sh"]
- command: watchmedo auto-restart --directory=/code/overbae --pattern='*.py' --recursive --signal SIGTERM -- celery -A overbae worker -l info --pool=threads --concurrency=8 -Q control
+ command: watchmedo auto-restart --directory=/code/overbae --pattern='*.py' --recursive --signal SIGTERM -- celery -A overbae worker -l info --pool=threads --concurrency=8 --prefetch-multiplier=1 --disable-prefetch -Q control
restart: unless-stopped
environment:
<<: *env-common
diff --git a/docker/worker-topology.json b/docker/worker-topology.json
index 13a855e4..9f902a84 100644
--- a/docker/worker-topology.json
+++ b/docker/worker-topology.json
@@ -1,5 +1,5 @@
{
- "celery-control-worker": ["celery", "-A", "overbae", "worker", "-l", "info", "--pool=threads", "--concurrency=8", "-Q", "control"],
+ "celery-control-worker": ["celery", "-A", "overbae", "worker", "-l", "info", "--pool=threads", "--concurrency=8", "--prefetch-multiplier=1", "--disable-prefetch", "-Q", "control"],
"celery-io-worker": ["celery", "-A", "overbae", "worker", "-l", "info", "--pool=threads", "--concurrency=24", "--prefetch-multiplier=1", "--disable-prefetch", "--hostname=io@%h", "-Q", "io"],
"celery-assistant-worker": ["celery", "-A", "overbae", "worker", "-l", "info", "--pool=threads", "--concurrency=24", "--prefetch-multiplier=1", "--disable-prefetch", "--hostname=assistant@%h", "-Q", "assistant"],
"celery-traces-worker": ["celery", "-A", "overbae", "worker", "-l", "info", "--pool=prefork", "--concurrency=4", "--prefetch-multiplier=1", "--disable-prefetch", "--hostname=io_traces@%h", "-Q", "io_traces"],
diff --git a/frontend/src/components/assistant/assistant-dock.tsx b/frontend/src/components/assistant/assistant-dock.tsx
index b4c5548d..8ce92a61 100644
--- a/frontend/src/components/assistant/assistant-dock.tsx
+++ b/frontend/src/components/assistant/assistant-dock.tsx
@@ -68,9 +68,12 @@ function statusOf(
return runningLabel(assistant.events) ?? assistant.draft?.steps.at(-1) ?? "Working";
}
if (last?.kind === "status")
- return { failed: "Run failed", interrupted: "Interrupted", stopped: "Stopped" }[
- last.payload.state
- ];
+ return {
+ failed: "Run failed",
+ interrupted: "Interrupted",
+ resumed: "Complete",
+ stopped: "Stopped",
+ }[last.payload.state];
return last ? "Complete" : "Ask about this data";
}
diff --git a/frontend/src/components/assistant/assistant-transcript.tsx b/frontend/src/components/assistant/assistant-transcript.tsx
index c64085f5..7dba8500 100644
--- a/frontend/src/components/assistant/assistant-transcript.tsx
+++ b/frontend/src/components/assistant/assistant-transcript.tsx
@@ -235,6 +235,7 @@ function ToolGroup({ steps, active }: { steps: Step[]; active: boolean }) {
const STATUS_NOTE = {
failed: "text-error",
interrupted: "text-warning",
+ resumed: "text-muted-foreground",
stopped: "text-muted-foreground",
};
diff --git a/frontend/src/components/assistant/types.ts b/frontend/src/components/assistant/types.ts
index f102494c..71e1cfae 100644
--- a/frontend/src/components/assistant/types.ts
+++ b/frontend/src/components/assistant/types.ts
@@ -51,7 +51,7 @@ export type AssistantEvent =
> & {
presentation: Presentation | null;
})
- | Envelope<"status", { state: "stopped" | "failed" | "interrupted"; detail: string }>
+ | Envelope<"status", { state: "stopped" | "failed" | "interrupted" | "resumed"; detail: string }>
| Envelope<"summary", { text: string; through: number }>;
/** The API refuses a longer message. */
diff --git a/overbae/admin.py b/overbae/admin.py
index bade9807..0b06e2bf 100644
--- a/overbae/admin.py
+++ b/overbae/admin.py
@@ -9,7 +9,6 @@ from overbae.models import (
Dataset,
EvalMatrix,
EvalRun,
- EvalRunRow,
EvalScore,
EvalSet,
Feedback,
@@ -251,6 +250,7 @@ class SubscriptionAdmin(admin.ModelAdmin):
@admin.register(BillingTelemetry)
class BillingTelemetryAdmin(admin.ModelAdmin):
list_display = ["user", "service", "amount", "project", "timestamp", "idempotency_key"]
+ list_select_related = ["user", "project"]
list_filter = ["service"]
search_fields = ["user__email", "idempotency_key"]
readonly_fields = ["id", "timestamp"]
@@ -413,28 +413,24 @@ class EvalSetAdmin(admin.ModelAdmin):
readonly_fields = ["id", "created_at", "updated_at"]
-class EvalRunRowInline(admin.TabularInline):
- model = EvalRunRow
- extra = 0
- fields = ["row_index", "state", "degraded", "error"]
- readonly_fields = fields
-
-
@admin.register(EvalRun)
class EvalRunAdmin(admin.ModelAdmin):
list_display = ["name", "project", "status", "mode", "is_baseline", "group", "created_at"]
+ list_select_related = ["project"]
list_filter = ["status", "mode", "created_at"]
search_fields = ["name", "project__slug", "group"]
readonly_fields = ["id", "created_at", "updated_at", "completed_at"]
- inlines = [EvalRunRowInline]
+ raw_id_fields = ["project", "dataset", "cell", "eval_set", "model_ref", "triggered_by"]
@admin.register(EvalScore)
class EvalScoreAdmin(admin.ModelAdmin):
list_display = ["source_type", "source_id", "score", "run", "project", "created_at"]
+ list_select_related = ["run", "project"]
list_filter = ["source_type", "created_at"]
search_fields = ["source_id", "run__name"]
readonly_fields = ["id", "created_at"]
+ raw_id_fields = ["project", "run"]
@admin.register(SignalSubscription)
diff --git a/overbae/api/otlp.py b/overbae/api/otlp.py
index e66c8fb1..30572c83 100644
--- a/overbae/api/otlp.py
+++ b/overbae/api/otlp.py
@@ -711,6 +711,11 @@ def process_span(span_id: str, project_id: str | None = None):
)
+def _fit(field: str, value: str) -> str:
+ """OTLP sets no length on names; one long name must not reject its whole batch."""
+ return value[: Span._meta.get_field(field).max_length]
+
+
def _build_span(
span_proto,
project: Project,
@@ -730,18 +735,18 @@ def _build_span(
parent_span_id=_parent_hex_or_none(span_proto),
project=project,
span_type=_classify_span_type(span_proto.name, attrs),
- operation=_operation_from(span_proto, attrs),
- name=span_proto.name or "",
+ operation=_fit("operation", _operation_from(span_proto, attrs)),
+ name=_fit("name", span_proto.name or ""),
kind=int(span_proto.kind),
start_time_ns=start,
end_time_ns=end,
duration_ns=duration,
status_code=int(span_proto.status.code),
status_message=span_proto.status.message or "",
- service_name=str(resource_attrs.get("service.name") or ""),
+ service_name=_fit("service_name", str(resource_attrs.get("service.name") or "")),
resource_attrs=resource_attrs,
- scope_name=_normalize_scope_name(scope_name),
- scope_version=scope_version or "",
+ scope_name=_fit("scope_name", _normalize_scope_name(scope_name)),
+ scope_version=_fit("scope_version", scope_version or ""),
attributes=attrs,
usage=usage_slice(attrs),
events=[_span_event_to_dict(e) for e in span_proto.events],
@@ -802,20 +807,39 @@ _SPAN_UPSERT_FIELDS = [
_EVAL_FIELDS = frozenset({"eval_attributes", "eval_claimed_at"})
+# The OpenTelemetry Collector's default request limit. Parsed spans take several times
+# their wire size in memory, so the limit holds after decompression too.
+MAX_EXPORT_BYTES = 20 * 1024 * 1024
+
+
def _decoded_request_body(request) -> bytes:
- raw = request.body
- if "gzip" in request.headers.get("Content-Encoding", ""):
- try:
- return zlib.decompress(raw, 16 + zlib.MAX_WBITS)
- except zlib.error as exc:
- raise _MalformedBodyError(f"Invalid gzip body: {exc}") from exc
- return raw
+ if safe_int(request.headers.get("Content-Length")) > MAX_EXPORT_BYTES:
+ raise _TooLargeError
+ raw = request.read(MAX_EXPORT_BYTES + 1)
+ if len(raw) > MAX_EXPORT_BYTES:
+ raise _TooLargeError
+ if "gzip" not in request.headers.get("Content-Encoding", ""):
+ return raw
+ stream = zlib.decompressobj(16 + zlib.MAX_WBITS)
+ try:
+ body = stream.decompress(raw, MAX_EXPORT_BYTES + 1)
+ except zlib.error as exc:
+ raise _MalformedBodyError(f"Invalid gzip body: {exc}") from exc
+ if len(body) > MAX_EXPORT_BYTES:
+ raise _TooLargeError
+ if not stream.eof:
+ raise _MalformedBodyError("Invalid gzip body: incomplete or truncated stream")
+ return body
class _MalformedBodyError(Exception):
pass
+class _TooLargeError(Exception):
+ pass
+
+
def _hex_id_to_base64(holder: dict, *keys: str) -> None:
for key in keys:
if isinstance(holder.get(key), str):
@@ -853,6 +877,11 @@ def otlp_traces(request):
body = _decoded_request_body(request)
except _MalformedBodyError as exc:
return JsonResponse({"error": str(exc)}, status=400)
+ except _TooLargeError:
+ return JsonResponse(
+ {"error": f"OTLP export exceeds {MAX_EXPORT_BYTES} bytes; send smaller batches."},
+ status=413,
+ )
try:
export_request = _parse_export(request, body)
diff --git a/overbae/innermind/admission.py b/overbae/innermind/admission.py
index 2eb98bdf..ec6a29e9 100644
--- a/overbae/innermind/admission.py
+++ b/overbae/innermind/admission.py
@@ -6,6 +6,7 @@ from datetime import timedelta
from django.conf import settings
from django.db import transaction
from django.db.models import Count, F
+from django.db.models.functions import Now
from django.utils import timezone
from overbae.models import LiveScoringProject, LiveScoringScheduler, LiveScoringWork
@@ -24,7 +25,7 @@ def enqueue(project_id, kind: str, keys: list[str]) -> None:
# Completed failed passes may retry after the existing span/trajectory claim grace.
LiveScoringWork.objects.filter(
project_id=project_id, kind=kind, key__in=keys, state="done"
- ).update(state="waiting", task_id="", expires_at=None)
+ ).update(state="waiting", task_id="", expires_at=None, waiting_since=Now())
@transaction.atomic
diff --git a/overbae/innermind/dataset.py b/overbae/innermind/dataset.py
index 5b16142e..d47ecff1 100644
--- a/overbae/innermind/dataset.py
+++ b/overbae/innermind/dataset.py
@@ -8,10 +8,11 @@ import json
from typing import Any
from asgiref.sync import sync_to_async
+from django.db import transaction
from overbae.core.decisions import DecisionError
from overbae.innermind import generation
-from overbae.innermind.span_processor import EVAL_SCORE_BATCH, SpanProcessor
+from overbae.innermind.span_processor import SpanProcessor
from overbae.models import EvalMatrix, EvalRun, EvalRunRow, EvalScore, Span
from overbae.services.datasets import rows as row_store
@@ -65,7 +66,13 @@ class DatasetRowProcessor(SpanProcessor):
def scoreable(run: EvalRun) -> list[tuple[row_store.DatasetRow, EvalRunRow]]:
- run_rows = list(run.rows.filter(error="", degraded=False).exclude(output=None))
+ """Rows a previous scorer already saved are skipped."""
+ scored = set(run.scores.values_list("source_id", flat=True))
+ run_rows = [
+ row
+ for row in run.rows.filter(error="", degraded=False).exclude(output=None)
+ if f"{run.cell_id}:{row.row_index}" not in scored
+ ]
if not run_rows:
return []
dataset_rows = {
@@ -74,7 +81,35 @@ def scoreable(run: EvalRun) -> list[tuple[row_store.DatasetRow, EvalRunRow]]:
return [(dataset_rows[r.row_index], r) for r in run_rows if r.row_index in dataset_rows]
-async def score_rows(run: EvalRun) -> int:
+class ScoringLostError(Exception):
+ pass
+
+
+def _hold(run_id, task_id) -> None:
+ """Writes go through only while this scorer holds the run; the caller is atomic."""
+ held = (
+ EvalRun.objects.select_for_update()
+ .filter(pk=run_id, scoring_task_id=task_id)
+ .exclude(status__in=EvalRun.TERMINAL)
+ )
+ if held.values_list("pk", flat=True).first() is None:
+ raise ScoringLostError("scoring was handed to another worker")
+
+
+def _save(score: EvalScore, task_id: str) -> None:
+ """Each score is saved as soon as it exists."""
+ _hold(score.run_id, task_id)
+ score.save()
+
+
+def _row_failed(run_row: EvalRunRow, task_id: str, error: str) -> None:
+ _hold(run_row.run_id, task_id)
+ EvalRunRow.objects.filter(pk=run_row.pk).update(error=error)
+
+
+async def score_rows(run: EvalRun, task_id: str) -> int:
"""Appends one EvalScore per scoreable row and returns how many were written. The
run must arrive with ``dataset__capability`` and ``cell`` loaded."""
pairs = await sync_to_async(scoreable)(run)
@@ -94,12 +129,12 @@ async def score_rows(run: EvalRun) -> int:
break
except DecisionError as exc:
if attempt + 1 == ROW_ATTEMPTS:
- await EvalRunRow.objects.filter(pk=run_row.pk).aupdate(
- error=f"scoring failed: Jev {exc.reason}"
+ await sync_to_async(_row_failed)(
+ run_row, task_id, f"scoring failed: Jev {exc.reason}"
)
return None
await asyncio.sleep(RETRY_SECONDS * 2**attempt)
- return EvalScore(
+ saved = EvalScore(
project_id=run.project_id,
source_type=EvalScore.SourceType.DATASET_ROW,
source_id=f"{run.cell_id}:{run_row.row_index}",
@@ -107,8 +142,8 @@ async def score_rows(run: EvalRun) -> int:
score=span.eval_attributes["score"],
metrics=span.eval_attributes["metrics"],
)
+ await sync_to_async(_save)(saved, task_id)
+ return saved
results = await asyncio.gather(*(score(row, run_row) for row, run_row in pairs))
- scores = [score for score in results if score is not None]
- await EvalScore.objects.abulk_create(scores, batch_size=EVAL_SCORE_BATCH)
- return len(scores)
+ return sum(score is not None for score in results)
diff --git a/overbae/innermind/generation.py b/overbae/innermind/generation.py
index 9593dea7..c215e771 100644
--- a/overbae/innermind/generation.py
+++ b/overbae/innermind/generation.py
@@ -29,8 +29,11 @@ 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; never replay an attempt whose outcome is unknown.
+# 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
SCHEDULER_HEALTHY = timedelta(minutes=2)
@@ -64,15 +67,17 @@ def dispatch(publish, publish_scoring) -> dict[str, int]:
expired = list(rows.filter(state__in=IN_FLIGHT, expires_at__lt=now))
for row in expired:
- saved = row.output is not None or bool(row.error)
- changed = rows.filter(pk=row.pk, state=row.state, task_id=row.task_id).update(
- state=EvalRunRow.State.DONE if saved else EvalRunRow.State.UNKNOWN, finished_at=now
- )
- if changed and not saved:
+ current = rows.filter(pk=row.pk, state=row.state, task_id=row.task_id)
+ 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:
+ # The new token fences the old message; a never-claimed row costs no attempt.
+ current.update(
+ state=EvalRunRow.State.WAITING, task_id="", queued_at=None, expires_at=None
+ )
+ elif current.update(state=EvalRunRow.State.UNKNOWN, finished_at=now):
rows.filter(pk=row.pk, error="").update(
- error="generation outcome unknown after worker deadline; not replayed"
- if row.state == EvalRunRow.State.RUNNING
- else "generation outcome unknown: dispatch expired before worker claim"
+ error=f"generation outcome unknown after {row.attempts} lost attempts"
)
running = EvalRun.objects.filter(status=EvalRun.Status.RUNNING)
@@ -159,7 +164,10 @@ def claim(row_id, task_id) -> bool:
if row.expires_at is not None and row.expires_at <= now:
return False
EvalRunRow.objects.filter(pk=row.pk).update(
- state=EvalRunRow.State.RUNNING, started_at=now, expires_at=now + RUNNING_LEASE
+ state=EvalRunRow.State.RUNNING,
+ started_at=now,
+ expires_at=now + RUNNING_LEASE,
+ attempts=F("attempts") + 1,
)
return True
@@ -177,7 +185,11 @@ def begin_scoring(run_id, task_id) -> bool:
return False
if run.scoring_task_id != task_id or run.scoring_started_at is not None:
return False
- EvalRun.objects.filter(pk=run.pk).update(scoring_started_at=timezone.now())
+ # A hand-off that waited in the queue starts with a fresh heartbeat.
+ now = timezone.now()
+ EvalRun.objects.filter(pk=run.pk).update(
+ scoring_started_at=now, scoring_attempts=F("scoring_attempts") + 1, updated_at=now
+ )
return True
diff --git a/overbae/innermind/runs.py b/overbae/innermind/runs.py
index 39ba24ff..5414dc82 100644
--- a/overbae/innermind/runs.py
+++ b/overbae/innermind/runs.py
@@ -20,6 +20,7 @@ from overbae.innermind import classes, comparison, dataset, generation
from overbae.innermind.metrics import FAIL_BELOW
from overbae.models import EvalMatrix, EvalRun, EvalRunRow, EvalSet, FinetuningJob
from overbae.services.activity import update_task
+from overbae.services.datasets import heartbeat
from overbae.services.datasets import rows as row_store
from overbae.services.datasets.alignment import system_prompt
from overbae.services.datasets.sampling import select_rows
@@ -29,8 +30,13 @@ logger = logging.getLogger(__name__)
ROW_BATCH = 500
# A running run whose rows have not moved for this long is failed.
STALL = timedelta(minutes=30)
-# Scoring writes nothing until it ends; it matches the scoring task's hard limit.
-SCORING_LIMIT = timedelta(hours=2)
+# A scorer beats while its process lives; a silent one is replaced, and the new
+# scorer skips the scores already saved.
+SCORER_STALE = timedelta(seconds=heartbeat.STALE_SECONDS)
+SCORING_ATTEMPTS = 3
+# A pending run whose start message was lost is sent again, then failed.
+PENDING_RESEND = timedelta(minutes=10)
+PENDING_LIMIT = timedelta(minutes=60)
class RunError(ValueError):
@@ -122,6 +128,7 @@ def relaunch(run: EvalRun) -> bool:
completed_at=None,
scoring_task_id="",
scoring_started_at=None,
+ scoring_attempts=0,
updated_at=timezone.now(),
):
return False
@@ -196,13 +203,24 @@ def score(run_id, task_id) -> bool:
if not generation.begin_scoring(run_id, task_id):
return False
run = EvalRun.objects.select_related("dataset__capability", "cell", "model_ref").get(pk=run_id)
+
+ held = Q(scoring_task_id=task_id)
+ beat = heartbeat.start(
+ lambda: EvalRun.objects.filter(held, pk=run_id).update(updated_at=timezone.now()),
+ owner=f"scoring {run_id}",
+ )
try:
- async_loop.run(dataset.score_rows(run))
+ async_loop.run(dataset.score_rows(run, task_id))
+ # Aggregation runs under the heartbeat too.
+ finish(run, where=held)
+ except dataset.ScoringLostError:
+ return False
except Exception as exc:
logger.exception("Scoring run %s failed", run_id)
- fail(run_id, f"scoring failed: {exc}")
+ fail(run_id, f"scoring failed: {exc}", where=held)
return False
- finish(run)
+ finally:
+ beat.set()
return True
@@ -241,14 +259,15 @@ def aggregate(run: EvalRun) -> dict:
}
-def finish(run: EvalRun) -> None:
+def finish(run: EvalRun, *, where: Q = Q()) -> None:
"""Completes the run, then wires its consumers explicitly on fresh rows: the
- status flip is a queryset update, so no model signal fires."""
+ status flip is a queryset update, so no model signal fires. ``where`` must still
+ hold when the status flips."""
summary = aggregate(run)
if found := classes.class_metrics(run):
summary["class_metrics"] = found
if (
- not EvalRun.objects.filter(pk=run.pk)
+ not EvalRun.objects.filter(where, pk=run.pk)
.exclude(status__in=EvalRun.TERMINAL)
.update(
status=EvalRun.Status.COMPLETED,
@@ -275,10 +294,11 @@ def on_terminal(run: EvalRun) -> None:
on_candidate_eval_finished(run)
-def fail(run_id, reason: str) -> bool:
+def fail(run_id, reason: str, *, where: Q = Q()) -> bool:
+ """``where`` must still hold when the status flips."""
now = timezone.now()
if (
- not EvalRun.objects.filter(pk=run_id)
+ not EvalRun.objects.filter(where, pk=run_id)
.exclude(status__in=EvalRun.TERMINAL)
.update(status=EvalRun.Status.FAILED, error=reason, completed_at=now, updated_at=now)
):
@@ -329,14 +349,47 @@ def row_scores(run: EvalRun) -> dict[int, float | None]:
def reap_stalled() -> int:
now = timezone.now()
reaped = 0
- for run_id in (
- EvalRun.objects.filter(status=EvalRun.Status.RUNNING, updated_at__lt=now - STALL)
- .exclude(scoring_started_at__gte=now - SCORING_LIMIT)
- .values_list("pk", flat=True)
+ running = EvalRun.objects.filter(status=EvalRun.Status.RUNNING)
+ silent = Q(updated_at__lt=now - SCORER_STALE)
+ for run_id, token, started, attempts, updated in (
+ running.exclude(scoring_task_id="")
+ .filter(silent)
+ .values_list(
+ "pk", "scoring_task_id", "scoring_started_at", "scoring_attempts", "updated_at"
+ )
+ ):
+ if started is None and updated >= now - STALL:
+ continue # The hand-off may still wait in the queue.
+ # A scorer that beat again since the read keeps its run.
+ still = silent & Q(scoring_task_id=token)
+ if started is not None and attempts >= SCORING_ATTEMPTS:
+ reaped += fail(run_id, f"scoring stopped {attempts} times", where=still)
+ continue
+ # The dispatcher hands the run to a new scorer; the old token can no longer save.
+ running.filter(still, pk=run_id).update(
+ scoring_task_id="", scoring_started_at=None, updated_at=now
+ )
+ for run_id in running.filter(scoring_task_id="", updated_at__lt=now - STALL).values_list(
+ "pk", flat=True
):
if generation.wait_is_healthy(run_id):
continue
reaped += fail(
run_id, f"evaluation stalled for over {int(STALL.total_seconds() // 60)} minutes"
)
+ # tasks.innermind imports this module.
+ from overbae.tasks.innermind import run_eval_run # noqa: PLC0415
+
+ for run_id, updated in EvalRun.objects.filter(
+ status=EvalRun.Status.PENDING, updated_at__lt=now - PENDING_RESEND
+ ).values_list("pk", "updated_at"):
+ if updated < now - PENDING_LIMIT:
+ never_started = Q(status=EvalRun.Status.PENDING, updated_at__lt=now - PENDING_LIMIT)
+ reaped += fail(run_id, "The run never started. Re-launch it.", where=never_started)
+ continue
+ # start() claims the run once, so a duplicate start does nothing.
+ result = run_eval_run.delay(eval_run_id=str(run_id))
+ EvalRun.objects.filter(pk=run_id, status=EvalRun.Status.PENDING).update(
+ celery_task_id=result.id
+ )
return reaped
diff --git a/overbae/innermind/span_processor.py b/overbae/innermind/span_processor.py
index 351964d2..b9f3aa40 100644
--- a/overbae/innermind/span_processor.py
+++ b/overbae/innermind/span_processor.py
@@ -17,7 +17,6 @@ from overbae.models import EvalMatrix, EvalScore, Span
logger = logging.getLogger(__name__)
-EVAL_SCORE_BATCH = 500
TRACE_SPAN_CAP = 2_000
MAX_CONCURRENT_SPANS = 64
# A claim older than this belongs to a worker that died; the sweep takes it over.
diff --git a/overbae/migrations/0062_live_scoring_waiting_since.py b/overbae/migrations/0062_live_scoring_waiting_since.py
new file mode 100644
index 00000000..4eda538b
--- /dev/null
+++ b/overbae/migrations/0062_live_scoring_waiting_since.py
@@ -0,0 +1,18 @@
+# Generated by Django 6.0.8 on 2026-11-23 13:08
+
+import django.db.models.functions.datetime
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("overbae", "0061_retire_baseten_together"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="livescoringwork",
+ name="waiting_since",
+ field=models.DateTimeField(db_default=django.db.models.functions.datetime.Now()),
+ ),
+ ]
diff --git a/overbae/migrations/0063_span_trajectory_due_idx.py b/overbae/migrations/0063_span_trajectory_due_idx.py
new file mode 100644
index 00000000..86466723
--- /dev/null
+++ b/overbae/migrations/0063_span_trajectory_due_idx.py
@@ -0,0 +1,20 @@
+from django.contrib.postgres.operations import AddIndexConcurrently
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [("overbae", "0062_live_scoring_waiting_since")]
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="span",
+ index=models.Index(
+ fields=["received_at"],
+ condition=models.Q(parent_span_id__isnull=True, eval_attributes__has_key="score")
+ & ~models.Q(eval_attributes__has_key="trajectory"),
+ name="span_trajectory_due_idx",
+ ),
+ ),
+ ]
diff --git a/overbae/migrations/0064_eval_attempts.py b/overbae/migrations/0064_eval_attempts.py
new file mode 100644
index 00000000..571027a0
--- /dev/null
+++ b/overbae/migrations/0064_eval_attempts.py
@@ -0,0 +1,22 @@
+# Generated by Django 6.0.8 on 2026-11-23 13:24
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("overbae", "0063_span_trajectory_due_idx"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="evalrun",
+ name="scoring_attempts",
+ field=models.SmallIntegerField(db_default=0),
+ ),
+ migrations.AddField(
+ model_name="evalrunrow",
+ name="attempts",
+ field=models.SmallIntegerField(db_default=0),
+ ),
+ ]
diff --git a/overbae/models/innermind.py b/overbae/models/innermind.py
index 501f6491..7577cccb 100644
--- a/overbae/models/innermind.py
+++ b/overbae/models/innermind.py
@@ -11,6 +11,7 @@ import uuid
from django.conf import settings
from django.db import models
+from django.db.models.functions import Now
class ModelRef(models.Model):
@@ -264,6 +265,7 @@ class EvalRun(models.Model):
last_admitted_at = models.DateTimeField(null=True, blank=True)
scoring_task_id = models.CharField(max_length=255, blank=True, default="")
scoring_started_at = models.DateTimeField(null=True, blank=True)
+ scoring_attempts = models.SmallIntegerField(db_default=0)
triggered_by = models.ForeignKey(
settings.AUTH_USER_MODEL,
@@ -334,6 +336,7 @@ class EvalRunRow(models.Model):
started_at = models.DateTimeField(null=True, blank=True)
finished_at = models.DateTimeField(null=True, blank=True)
expires_at = models.DateTimeField(null=True, blank=True)
+ attempts = models.SmallIntegerField(db_default=0)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
@@ -508,6 +511,8 @@ class LiveScoringWork(models.Model):
state = models.CharField(max_length=16, default="waiting")
task_id = models.CharField(max_length=36, blank=True, default="")
created_at = models.DateTimeField(auto_now_add=True)
+ # A finished row is recycled to waiting; its wait starts again then.
+ waiting_since = models.DateTimeField(db_default=Now())
queued_at = models.DateTimeField(null=True)
started_at = models.DateTimeField(null=True)
expires_at = models.DateTimeField(null=True)
diff --git a/overbae/models/traces.py b/overbae/models/traces.py
index 412de89d..b467b9e4 100644
--- a/overbae/models/traces.py
+++ b/overbae/models/traces.py
@@ -194,6 +194,13 @@ class Span(models.Model):
condition=~Q(eval_attributes__has_key="score"),
name="span_unscored_idx",
),
+ # Roots whose spans are scored and whose trajectory is not: the trajectory sweep.
+ models.Index(
+ fields=["received_at"],
+ condition=Q(parent_span_id__isnull=True, eval_attributes__has_key="score")
+ & ~Q(eval_attributes__has_key="trajectory"),
+ name="span_trajectory_due_idx",
+ ),
]
def __str__(self) -> str:
diff --git a/overbae/services/assistant/turn.py b/overbae/services/assistant/turn.py
index 61391a4a..788291ea 100644
--- a/overbae/services/assistant/turn.py
+++ b/overbae/services/assistant/turn.py
@@ -1,15 +1,18 @@
"""A turn: from a user's message to the assistant's reply, in one task. The event log is
-saved at every step, so a turn that stops halfway leaves an exact record, and the next
-message starts a new turn from it. A turn is never resumed by itself.
+saved at every step, so a turn that stops halfway leaves an exact record.
-A turn holds the thread by its number and writes only while it is the newest. A turn that
-stopped moving for ``STALE`` is taken for interrupted, and from then on it can write
-nothing."""
+A turn holds the thread by its number and writes only while it is the newest, and a
+heartbeat moves the thread while its worker lives. When the worker is lost, another task
+takes the thread over under a new number and continues the reply from the log; a call that
+may have been running is answered as abandoned, never run again. After ``RESUMES`` such
+take-overs for one message, or once nothing resumed it for ``STALE``, the turn is marked
+interrupted."""
import json
import logging
import time
import uuid
+from datetime import timedelta
from django.conf import settings
from django.contrib.auth import get_user_model
@@ -27,8 +30,9 @@ from overbae.models import (
Dataset,
)
from overbae.models.assistant import STALE
-from overbae.services.assistant import log, prompt, threads, tools
+from overbae.services.assistant import log, presentation, prompt, threads, tools
from overbae.services.billing_ledger import InsufficientCredits, charge_llm_usage, ensure_credits
+from overbae.services.datasets import heartbeat
logger = logging.getLogger(__name__)
Kind, State = AssistantEvent.Kind, AssistantThread.State
@@ -36,6 +40,9 @@ Queued = AssistantInput.State.QUEUED
# Longer than any one step: a model reply, a cell at its limit, or one poll of a job.
TURN_SECONDS = 30 * 60
+# A turn whose heartbeat is this old lost its worker and may be taken over.
+LEASE = timedelta(minutes=2)
+RESUMES = 2
DRAFT_INTERVAL_SECONDS = 0.1
ABANDONED = {
"error": "This call has no recorded result: the turn stopped or was interrupted. It may "
@@ -83,36 +90,55 @@ def wake_dataset(dataset_id) -> None:
def settle(thread: AssistantThread) -> AssistantThread:
"""Mark a turn that stopped moving as interrupted. A page that reads the thread and a
- user who writes to it call this; no process watches for it."""
+ user who writes to it call this, for when nothing resumed it."""
if thread.state != State.RUNNING or thread.updated_at > timezone.now() - STALE:
return thread
with transaction.atomic():
held = AssistantThread.objects.select_for_update().get(pk=thread.pk)
if held.state == State.RUNNING and held.updated_at <= timezone.now() - STALE:
- # A newer number fences the lost turn out of every later write.
- held.turn += 1
- held.state = State.IDLE
- held.save(update_fields=["turn", "state", "updated_at"])
- log.append(
- held,
- Kind.STATUS,
- {
- "state": "interrupted",
- "detail": "The turn was interrupted. Send a message to continue.",
- },
- )
- if ready(held).exists():
- wake(held)
+ _interrupt(held)
thread.refresh_from_db()
return thread
+def _interrupt(held) -> None:
+ """The caller holds the thread's row lock."""
+ # A newer number fences the lost turn out of every later write.
+ held.turn += 1
+ held.state = State.IDLE
+ held.save(update_fields=["turn", "state", "updated_at"])
+ log.append(
+ held,
+ Kind.STATUS,
+ {"state": "interrupted", "detail": "The turn was interrupted. Send a message to continue."},
+ )
+ if ready(held).exists():
+ wake(held)
+
+
+def resume_lost() -> int:
+ """Wake every turn whose worker stopped beating; ``run`` takes each over."""
+ from overbae.tasks.assistant import run_turn # lazy: tasks import the API serializers
+
+ lost = AssistantThread.objects.filter(
+ state=State.RUNNING, updated_at__lt=timezone.now() - LEASE
+ ).values_list("pk", flat=True)
+ for thread_id in lost:
+ run_turn.delay(str(thread_id))
+ return len(lost)
+
+
def run(thread_id) -> None:
"""The task: one turn, and the next one when messages arrived as it ended."""
- thread = _begin(thread_id)
+ thread, resumed = _begin(thread_id)
if thread is None:
return
+ beat = heartbeat.start(
+ lambda: _held(thread).update(updated_at=timezone.now()), owner=f"assistant {thread_id}"
+ )
try:
+ if resumed:
+ _resume(thread)
_turn(thread)
except log.LostTurnError:
logger.warning("assistant turn on %s was taken over", thread_id)
@@ -122,14 +148,17 @@ def run(thread_id) -> None:
except Exception:
logger.exception("assistant turn failed on %s", thread_id)
_status(thread, "failed", "The turn failed. Send a message to continue.")
+ finally:
+ beat.set()
if _held(thread).update(state=State.IDLE, stop_requested=False):
log.changed(thread)
if ready(thread).exists():
wake(thread)
-def _begin(thread_id) -> AssistantThread | None:
- """Take the thread for a turn, when a message waits and nothing holds it."""
+def _begin(thread_id) -> tuple[AssistantThread | None, bool]:
+ """Take the thread for a turn, when a message waits and nothing holds it, or take over
+ a turn whose worker was lost. True with a take-over."""
thread = settle(AssistantThread.objects.select_related("project", "dataset").get(pk=thread_id))
with transaction.atomic():
thread = (
@@ -137,16 +166,65 @@ def _begin(thread_id) -> AssistantThread | None:
.select_related("project", "dataset")
.get(pk=thread_id)
)
- if thread.state == State.RUNNING or not ready(thread).exists():
- return None
- # A first message on a new dataset waits for its source; landing wakes the thread.
- if thread.dataset.state == Dataset.State.LANDING:
- return None
- thread.state, thread.stop_requested = State.RUNNING, False
- thread.turn += 1
- thread.save(update_fields=["state", "stop_requested", "turn", "updated_at"])
+ resumed = thread.state == State.RUNNING
+ if resumed:
+ if thread.updated_at >= timezone.now() - LEASE:
+ return None, False
+ if _resumes(thread) >= RESUMES:
+ _interrupt(thread)
+ return None, False
+ # The new number fences the lost worker out of every later write.
+ thread.turn += 1
+ thread.save(update_fields=["turn", "updated_at"])
+ _status(thread, "resumed", "The reply continues after its worker stopped.")
+ else:
+ if not ready(thread).exists():
+ return None, False
+ # A first message on a new dataset waits for its source; landing wakes the thread.
+ if thread.dataset.state == Dataset.State.LANDING:
+ return None, False
+ thread.state, thread.stop_requested = State.RUNNING, False
+ thread.turn += 1
+ thread.save(update_fields=["state", "stop_requested", "turn", "updated_at"])
log.changed(thread)
- return thread
+ return thread, resumed
+
+
+def _resumes(thread) -> int:
+ """Take-overs since the newest message."""
+ since = (
+ thread.events.filter(kind=Kind.USER)
+ .order_by("-sequence")
+ .values_list("sequence", flat=True)
+ .first()
+ )
+ return thread.events.filter(
+ kind=Kind.STATUS, sequence__gt=since or 0, payload__state="resumed"
+ ).count()
+
+
+def _resume(thread) -> None:
+ """Continue the reply the lost worker was writing. Calls without a result are read as
+ abandoned (``messages``); a reply that ended, failed or asked the user is left."""
+ last = (
+ thread.events.exclude(kind=Kind.STATUS, payload__state="resumed")
+ .order_by("-sequence")
+ .only("kind", "payload", "presentation")
+ .first()
+ )
+ if last is None or last.kind == Kind.STATUS:
+ return
+ if last.kind == Kind.ASSISTANT and not last.payload["calls"]:
+ return
+ if last.kind == Kind.TOOL_RESULT:
+ # Any call of the newest reply that asked the user ends the answer, as in ``_answer``.
+ reply = thread.events.filter(kind=Kind.ASSISTANT).order_by("-sequence").first()
+ results = thread.events.filter(kind=Kind.TOOL_RESULT, sequence__gt=reply.sequence).exclude(
+ presentation=None
+ )
+ if any(presentation.asks(r.presentation) for r in results.only("presentation")):
+ return
+ _answer(thread, time.monotonic() + TURN_SECONDS)
def _held(thread):
diff --git a/overbae/services/datasets/admission.py b/overbae/services/datasets/admission.py
index 7fe6a988..778cb3ef 100644
--- a/overbae/services/datasets/admission.py
+++ b/overbae/services/datasets/admission.py
@@ -12,6 +12,7 @@ from django.db.models import Exists, F, OuterRef, Subquery
from django.utils import timezone
from overbae.models import Dataset, DatasetImport, DatasetLandingWork, Project
+from overbae.services.datasets.imports import MAX_ATTEMPTS, validate_sources
from overbae.services.datasets.lifecycle import DatasetError
logger = logging.getLogger(__name__)
@@ -255,6 +256,10 @@ def finish(task_id, owner, outcome=None):
return
outcome = outcome or {}
status = outcome.get("status")
+ if status == "retry":
+ # The lease lapses and reconcile retries the import under a new owner.
+ wake()
+ return
source = (
DatasetImport.objects.filter(pk=task_id).values("state", "failure_code", "error").first()
)
@@ -346,12 +351,17 @@ def reconcile(publish):
updated_at=now,
)
continue
- error = (
- "The landing worker stopped; retry explicitly from the retained source."
- if work.state == "running"
- else "The import exceeded its configured queue-wait limit."
- )
- code = "worker_timeout" if work.state == "running" else "queue_timeout"
+ if work.state == "running" and _retry(work, source, targets, now):
+ continue
+ if work.state == "running" and source and source.attempts >= MAX_ATTEMPTS:
+ error = f"The import stopped {source.attempts} times. Its source is retained."
+ code = "attempts_exhausted"
+ elif work.state == "running":
+ error = "The landing worker stopped; retry explicitly from the retained source."
+ code = "worker_timeout"
+ else:
+ error = "The import exceeded its configured queue-wait limit."
+ code = "queue_timeout"
DatasetLandingWork.objects.filter(pk=task_id).update(
failure_code=code,
state="failed",
@@ -380,12 +390,62 @@ def reconcile(publish):
lease_until=None,
updated_at=now,
)
+ # Lazy: the assistant reaches the MCP catalog, which imports this module.
+ from overbae.services.assistant.turn import wake_dataset
+
+ # A message sent with the upload waited for its source; landing has ended.
+ for target in targets:
+ transaction.on_commit(
+ lambda dataset_id=target.pk: wake_dataset(dataset_id), robust=True
+ )
DatasetLandingWork.objects.filter(state="waiting").exclude(dataset__state="landing").update(
state="cancelled", finished_at=now, updated_at=now
)
return dispatch(publish)
+def _retry(work, source, targets, now):
+ """Puts lost work back in line while its import has attempts left. The new owner
+ fences the old message, and a file that keeps stopping its worker hits the limit.
+ The caller holds the source, dataset and work locks."""
+ if source is None or source.state not in ("queued", "running"):
+ return False
+ if source.attempts >= MAX_ATTEMPTS:
+ return False
+ try:
+ validate_sources(source)
+ except DatasetError:
+ return False
+ DatasetLandingWork.objects.filter(pk=work.pk).update(
+ state="waiting",
+ owner=None,
+ queued_at=now,
+ started_at=None,
+ lease_until=None,
+ published_at=None,
+ error="",
+ failure_code="",
+ updated_at=now,
+ )
+ # Admission publishes it; the receipt's own publisher stays idle.
+ DatasetImport.objects.filter(pk=source.pk).update(
+ state="queued",
+ owner=None,
+ lease_until=None,
+ started_at=None,
+ queued_at=now,
+ published_at=now,
+ next_publish_at=None,
+ publish_owner=None,
+ updated_at=now,
+ )
+ for target in targets:
+ Dataset.objects.filter(pk=target.pk, state="landing").update(
+ operation={"state": "queued", "task_id": str(work.pk), "queued_at": now.isoformat()}
+ )
+ return True
+
+
def status(dataset):
task_id = dataset.operation.get("task_id")
if not task_id:
diff --git a/overbae/services/datasets/documents.py b/overbae/services/datasets/documents.py
index d75cc3b5..7b5fbfd9 100644
--- a/overbae/services/datasets/documents.py
+++ b/overbae/services/datasets/documents.py
@@ -26,6 +26,12 @@ class DocumentError(InputValidationError):
pass
+class ParserUnavailableError(DocumentError):
+ """The sandbox stopped or refused the read; pages already read are saved."""
+
+ code = "parser_unavailable"
+
+
def extract(
path: Path,
*,
@@ -79,6 +85,10 @@ def extract(
follow_redirects=False,
) as response,
):
+ if response.status_code == 503:
+ raise ParserUnavailableError(
+ "The isolated document parser is busy or restarting. No source was landed."
+ )
if response.status_code != 200:
raise DocumentError(
f"The isolated document parser returned HTTP {response.status_code}. No source was landed."
@@ -114,7 +124,11 @@ def extract(
return rows, metadata
except DocumentError:
raise
- except (httpx.TransportError, FramingError, ValueError) as exc:
+ except (httpx.TransportError, FramingError) as exc:
+ raise ParserUnavailableError(
+ "The isolated document parser did not return a complete result. No source was landed."
+ ) from exc
+ except ValueError as exc:
raise DocumentError(
"The isolated document parser did not return a complete result. No source was landed."
) from exc
diff --git a/overbae/services/datasets/imports.py b/overbae/services/datasets/imports.py
index be01ab01..e08db251 100644
--- a/overbae/services/datasets/imports.py
+++ b/overbae/services/datasets/imports.py
@@ -507,7 +507,12 @@ def reconcile():
):
from overbae.models import DatasetLandingWork
- if (
+ if DatasetLandingWork.objects.filter(
+ pk=run.pk, state__in=("waiting", "admitted", "running")
+ ).exists():
+ # Admission owns lost landing work and retries it.
+ pass
+ elif (
run.attempts >= MAX_ATTEMPTS
or DatasetLandingWork.objects.filter(pk=run.pk).exists()
):
@@ -683,6 +688,7 @@ def execute(task_id, inputs):
run.refresh_from_db()
return {"status": run.state}
stage = paths.dataset_dir(dataset.pk) / "imports" / str(run.pk) / str(claimed.owner)
+ retrying = False
beat = heartbeat.start(lambda: renew(claimed), owner=f"import {run.pk}")
try:
run.refresh_from_db()
@@ -765,6 +771,10 @@ def execute(task_id, inputs):
return {"status": "ok", "rows": rows}
except Exception as exc: # noqa: BLE001 — a failed attempt retains its exact source
logger.exception("dataset import %s failed", run.pk)
+ if getattr(exc, "code", "") == "parser_unavailable" and run.attempts < MAX_ATTEMPTS:
+ # The import stays claimed until its lease lapses; admission then retries it.
+ retrying = True
+ return {"status": "retry", "error": str(exc)}
fail(claimed, str(exc), code=getattr(exc, "code", "import_failed"))
return {"status": "failed", "error": str(exc)}
finally:
@@ -773,7 +783,7 @@ def execute(task_id, inputs):
from overbae.services.assistant.turn import wake_dataset
try:
- for target_id in _target_ids(run):
+ for target_id in [] if retrying else _target_ids(run):
operations.finished(target_id, task_id=str(run.pk))
# A message sent with the upload waited for its source, landed or failed.
try:
diff --git a/overbae/services/datasets/land.py b/overbae/services/datasets/land.py
index 1f561a4a..d8958c00 100644
--- a/overbae/services/datasets/land.py
+++ b/overbae/services/datasets/land.py
@@ -43,7 +43,9 @@ logger = logging.getLogger(__name__)
class LandError(ValueError):
- pass
+ def __init__(self, detail: str, *, code: str = "import_failed") -> None:
+ super().__init__(detail)
+ self.code = code
SPLIT_POSITIONS = ("head", "tail", "random")
@@ -291,7 +293,7 @@ def _read_one(
)
except (files.FileError, documents.DocumentError) as exc:
progress({"stage": "failed"})
- raise LandError(str(exc)) from exc
+ raise LandError(str(exc), code=getattr(exc, "code", "import_failed")) from exc
if not rows and extraction.get("status") != "no_text":
raise LandError("The file has no rows.")
identity = store.file_sha256(path)
diff --git a/overbae/services/datasets/pipeline_runner.py b/overbae/services/datasets/pipeline_runner.py
index a63aa165..d4f0f978 100644
--- a/overbae/services/datasets/pipeline_runner.py
+++ b/overbae/services/datasets/pipeline_runner.py
@@ -21,6 +21,8 @@ from sandbox.protocol import FramingError, HeaderReader, header_bytes
QUEUE_SECONDS = 15 * 60
TASK_SECONDS = 1560
+# A slot renewed by the run's heartbeat; a dead worker's slot frees within this.
+SLOT_SECONDS = 5 * 60
_TAKE_SLOT = """
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[1])
if redis.call('ZCARD', KEYS[1]) < tonumber(ARGV[4]) then
@@ -71,7 +73,7 @@ def take_slot(project_id, owner):
1,
f"workshop:project:{project_id}:slots",
now,
- now + TASK_SECONDS + 60,
+ now + SLOT_SECONDS,
owner,
settings.WORKSHOP_PROJECT_CONCURRENCY,
TASK_SECONDS + 120,
@@ -79,6 +81,13 @@ def take_slot(project_id, owner):
)
+def renew_slot(project_id, owner):
+ if settings.CELERY_BROKER_URL != "memory://":
+ _client(settings.CELERY_BROKER_URL).zadd(
+ f"workshop:project:{project_id}:slots", {owner: time.time() + SLOT_SECONDS}, xx=True
+ )
+
+
def release_slot(project_id, owner):
if settings.CELERY_BROKER_URL != "memory://":
_client(settings.CELERY_BROKER_URL).zrem(f"workshop:project:{project_id}:slots", owner)
diff --git a/overbae/services/datasets/workbench.py b/overbae/services/datasets/workbench.py
index 339d701d..274f2afc 100644
--- a/overbae/services/datasets/workbench.py
+++ b/overbae/services/datasets/workbench.py
@@ -25,6 +25,7 @@ from overbae.models import (
from overbae.services import activity, operational_progress
from overbae.services.datasets import (
events,
+ heartbeat,
lifecycle,
lineage,
measure,
@@ -337,9 +338,11 @@ def execute(run_id, *, script_executor=None):
return
if script_executor is None:
return
- from overbae.services.datasets.pipeline_runner import TASK_SECONDS, scratch
+ from overbae.services.datasets.pipeline_runner import scratch
- seconds = TASK_SECONDS + 60
+ # 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.
+ seconds = heartbeat.STALE_SECONDS
claimed = DatasetPipelineRun.objects.filter(pk=run_id, state="queued").update(
state="running",
updated_at=timezone.now(),
@@ -465,6 +468,13 @@ def execute(run_id, *, script_executor=None):
counting(f"step_{index + 1}_writing", done)
yield row
+ beat = heartbeat.start(
+ lambda: DatasetPipelineRun.objects.filter(
+ pk=run.pk, state="running", attempt=run.attempt
+ ).update(lease_until=timezone.now() + timedelta(seconds=seconds)),
+ owner=f"pipeline lease {run.pk}",
+ )
+ local_files.callback(beat.set)
try:
if not progress("verifying_source"):
return
diff --git a/overbae/services/mcp/resources.py b/overbae/services/mcp/resources.py
index ca892193..b9ce8d7a 100644
--- a/overbae/services/mcp/resources.py
+++ b/overbae/services/mcp/resources.py
@@ -1486,7 +1486,7 @@ def interface_resource():
"unavailable_code": "query_capacity_unavailable",
"retry": "Use the returned cell, identical SQL and retry_after_seconds. Bulk analysis belongs in a retained pipeline. No private SQL engine is created before admission.",
},
- "source_admission": "Source imports wait durably before bounded broker publication. Dataset-run progress.admission and dataset operation.landing_admission expose queue, execution and terminal states with timestamps. One import per project runs at a time; waiting does not consume an execution attempt or expire unless explicitly configured. Lost started imports retain their source and require resume_dataset_import; unknown started work is not replayed.",
+ "source_admission": "Source imports wait durably before bounded broker publication. Dataset-run progress.admission and dataset operation.landing_admission expose queue, execution and terminal states with timestamps. One import per project runs at a time; waiting does not consume an execution attempt or expire unless explicitly configured. A started import whose worker or document parser stopped is retried automatically under a new owner, up to 3 attempts in total, and keeps its source. Other failures, and imports at the attempt limit, stop; resume_dataset_import retries a stopped import with attempts left.",
"progress": "Preview and publication expose aggregate seconds plus per-step runtime stage_seconds for container setup, input transfer, script execution, artifact transfer, output reading and cleanup. A stopped script never reports completed runtime; cleanup_confirmed is separate from publication success.",
"parameters": "Package manifest parameters declare types, for example {seed: integer}; run parameters supply values, for example {seed: 42}.",
"queries": "Read-only queries have a deployment-configured deadline (default 10 seconds); query_timeout leaves the cell unchanged. Oversized results are rejected during materialization, not clipped.",
diff --git a/overbae/services/queue_capacity.py b/overbae/services/queue_capacity.py
index 0f390627..ced981be 100644
--- a/overbae/services/queue_capacity.py
+++ b/overbae/services/queue_capacity.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from collections import defaultdict
from datetime import timedelta
from django.conf import settings
@@ -13,6 +14,7 @@ from overbae.models import (
DatasetImport,
DatasetLandingWork,
DatasetPipelineRun,
+ EvalRun,
EvalRunRow,
LiveScoringWork,
)
@@ -82,6 +84,26 @@ def read_workloads():
)
ages = [evaluation.pop(key) for key in ("oldest_waiting", "oldest_queued")]
evaluation["oldest"] = min((stamp for stamp in ages if stamp is not None), default=None)
+ # Generation admits at most EVAL_MAX_IN_FLIGHT rows, per run and per project; each
+ # run being scored holds one more slot.
+ per_run = max(1, settings.EVAL_MAX_IN_FLIGHT_PER_RUN)
+ by_project = defaultdict(int)
+ for row in (
+ EvalRunRow.objects.filter(
+ run__status="running",
+ run__scoring_task_id="",
+ state__in=["waiting", "queued", "running"],
+ )
+ .values("run_id", "run__project_id")
+ .annotate(total=Count("pk"))
+ ):
+ by_project[row["run__project_id"]] += min(row["total"], per_run)
+ per_project = max(1, settings.EVAL_MAX_IN_FLIGHT_PER_PROJECT)
+ generating = sum(min(total, per_project) for total in by_project.values())
+ evaluation["scaling_demand"] = (
+ min(max(1, settings.EVAL_MAX_IN_FLIGHT), generating)
+ + EvalRun.objects.filter(status="running").exclude(scoring_task_id="").count()
+ )
workshop = DatasetPipelineRun.objects.filter(state__in=["queued", "running"]).aggregate(
waiting=Count("pk", filter=Q(state="queued")),
running=Count("pk", filter=Q(state="running")),
@@ -98,7 +120,7 @@ def read_workloads():
waiting=Count("pk", filter=Q(state__in=["waiting", "queued"])),
running=Count("pk", filter=Q(state="running")),
blocked=Count("pk", filter=recent_expiry),
- oldest=Min("created_at", filter=Q(state__in=["waiting", "queued"])),
+ oldest=Min("waiting_since", filter=Q(state__in=["waiting", "queued"])),
)
project_demand = (
LiveScoringWork.objects.filter(state__in=["waiting", "queued", "running"])
diff --git a/overbae/settings.py b/overbae/settings.py
index f8fc9ab3..854d0865 100644
--- a/overbae/settings.py
+++ b/overbae/settings.py
@@ -442,6 +442,7 @@ CELERY_TASK_ROUTES = {
"overbae.tasks.training_preparation.inspect_preparation": {"queue": "io"},
# A streamed model reply holds a worker slot for its whole length, so steps have their
# own queue. The reconciler only reads and enqueues: it must run when that queue is full.
+ "overbae.tasks.assistant.resume_lost_turns": {"queue": "control"},
"overbae.tasks.assistant.run_turn": {"queue": "assistant"},
"overbae.tasks.assistant.stop_kernel": {"queue": "assistant"},
"overbae.tasks.assistant.forget_workspace_data": {"queue": "assistant"},
@@ -527,7 +528,7 @@ CELERY_BEAT_SCHEDULE = {
"task": "overbae.tasks.finetuning_reconciler.reconcile_finetuning_jobs",
"schedule": 15.0,
},
- # Fails runs stuck in RUNNING with no row progress and no healthy generation wait.
+ # Hands a silent scorer to a new worker, resends a lost run start and fails stalled runs.
"reap-stalled-eval-runs": {
"task": "overbae.tasks.innermind.reap_stalled_runs",
"schedule": 300.0,
@@ -562,6 +563,11 @@ CELERY_BEAT_SCHEDULE = {
"task": "overbae.tasks.inference_controller.reconcile_deployments",
"schedule": 15.0,
},
+ "resume-lost-assistant-turns": {
+ "task": "overbae.tasks.assistant.resume_lost_turns",
+ "schedule": 60.0,
+ "options": {"expires": 55.0},
+ },
# Re-drives spans still waiting for an ancestor, stale claims and lost enqueues.
"admit-live-scoring": {
"task": "overbae.tasks.innermind.dispatch_live_scoring",
diff --git a/overbae/tasks/assistant.py b/overbae/tasks/assistant.py
index b909c2a0..b102e478 100644
--- a/overbae/tasks/assistant.py
+++ b/overbae/tasks/assistant.py
@@ -11,6 +11,13 @@ def run_turn(thread_id):
turn.run(thread_id)
+@shared_task(name="overbae.tasks.assistant.resume_lost_turns")
+def resume_lost_turns():
+ from overbae.services.assistant import turn
+
+ return {"resumed": turn.resume_lost()}
+
+
@shared_task(name="overbae.tasks.assistant.stop_kernel")
def stop_kernel(project_id, thread_id, turn):
"""End the kernel of the turn that was stopped, also during a cell: that turn gets its
diff --git a/overbae/tasks/datasets.py b/overbae/tasks/datasets.py
index b876c7d4..703bc3a3 100644
--- a/overbae/tasks/datasets.py
+++ b/overbae/tasks/datasets.py
@@ -533,7 +533,12 @@ def execute_pipeline(self, run_id):
raise self.retry(exc=exc, countdown=2) from exc
if not admitted:
raise self.retry(countdown=2)
- beat = heartbeat.start(pipeline_runner.heartbeat, owner=f"pipeline {run.pk}")
+
+ def beat_once():
+ pipeline_runner.renew_slot(run.dataset.project_id, owner)
+ pipeline_runner.heartbeat()
+
+ beat = heartbeat.start(beat_once, owner=f"pipeline {run.pk}")
try:
workbench.execute(run_id, script_executor=pipeline_runner.execute_script)
except SoftTimeLimitExceeded:
diff --git a/overbae/tasks/innermind.py b/overbae/tasks/innermind.py
index db805b42..13748989 100644
--- a/overbae/tasks/innermind.py
+++ b/overbae/tasks/innermind.py
@@ -12,6 +12,7 @@ from collections import defaultdict
from celery import current_app, shared_task
from celery.exceptions import SoftTimeLimitExceeded
from django.core.cache import cache
+from django.db.models import Q
from overbae.core import async_loop
from overbae.innermind import admission, generation, runs, signals, span_processor, trajectory
@@ -254,7 +255,7 @@ def score_eval_run(self, *, eval_run_id: str) -> dict:
try:
scored = runs.score(eval_run_id, self.request.id)
except SoftTimeLimitExceeded:
- runs.fail(eval_run_id, "scoring timed out")
+ runs.fail(eval_run_id, "scoring timed out", where=Q(scoring_task_id=self.request.id))
scored = False
return {"scored": scored}
diff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.py
index bd5498b4..418808bb 100644
--- a/overmind/overmind/__init__.py
+++ b/overmind/overmind/__init__.py
@@ -10,7 +10,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any
-__version__ = "0.1.126"
+__version__ = "0.1.127"
from .client import Client, ModelDeleted, OvermindInferenceError
diff --git a/overmind/pyproject.toml b/overmind/pyproject.toml
index 4ed86406..f38c601f 100644
--- a/overmind/pyproject.toml
+++ b/overmind/pyproject.toml
@@ -46,7 +46,7 @@ license = { text = "MIT" }
name = "overmind"
readme = "README.md"
requires-python = ">=3.10,<4" # todo; remove the upper bound
-version = "0.1.126"
+version = "0.1.127"
[project.urls]
"Agent setup" = "https://console.overmindlab.ai/setup.md"
diff --git a/overmind/skills/overmind-datasets/SKILL.md b/overmind/skills/overmind-datasets/SKILL.md
index 4338df91..692a303c 100644
--- a/overmind/skills/overmind-datasets/SKILL.md
+++ b/overmind/skills/overmind-datasets/SKILL.md
@@ -138,9 +138,10 @@ completed landing. Dataset-run `progress.admission` and dataset-operation
`landing_admission` show fair-queue waiting, admission, execution and terminal
state with measured timestamps. A waiting import consumes no execution attempt;
follow polling guidance rather than resubmitting. One project's imports execute
-serially so another project can use available workers. Failed or lost started
-attempts retain their source and require explicit recovery through
-`resume_dataset_import`; no automatic replay is implied. For a JSON wrapper use `--json-rows-field FIELD` after inspecting
+serially so another project can use available workers. A started import whose
+worker or document parser stopped is retried automatically, up to 3 attempts in
+total, and keeps its source. Other failures, and imports at the limit, stop;
+`resume_dataset_import` retries a stopped import that has attempts left. For a JSON wrapper use `--json-rows-field FIELD` after inspecting
the file's structure. Original wrapper bytes remain retained; the selected field
is recorded as extraction provenance.
The CLI marks a saved upload state as `state_scope=at_publication`; it is not
diff --git a/overmind/uv.lock b/overmind/uv.lock
index f2372199..26b4b174 100644
--- a/overmind/uv.lock
+++ b/overmind/uv.lock
@@ -923,7 +923,7 @@ wheels = [
[[package]]
name = "overmind"
-version = "0.1.126"
+version = "0.1.127"
source = { editable = "." }
dependencies = [
{ name = "packaging" },
diff --git a/scripts/deploy_ecs.py b/scripts/deploy_ecs.py
index 836a09be..f64125de 100644
--- a/scripts/deploy_ecs.py
+++ b/scripts/deploy_ecs.py
@@ -17,13 +17,9 @@ import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
-HEALTH_CHECKED_QUEUES = {
- "celery-io-worker": "io",
- "celery-assistant-worker": "assistant",
- "celery-traces-worker": "io_traces",
- "celery-landing-worker": "landing",
- "celery-interactive-worker": "interactive",
-}
+# A large index build outlasts the AWS CLI waiter's 10 minutes; this stays inside the
+# deploy role's one-hour credentials.
+MIGRATION_SECONDS = 45 * 60
READ_ONLY_FIELDS = (
"taskDefinitionArn",
"revision",
@@ -36,20 +32,20 @@ READ_ONLY_FIELDS = (
)
-def _environment(container, **values):
- existing = {item["name"]: item["value"] for item in container.get("environment", [])}
- existing.update({name: str(value) for name, value in values.items()})
- container["environment"] = [{"name": key, "value": value} for key, value in existing.items()]
+def _app_container(definition, service):
+ containers = [item for item in definition["containerDefinitions"] if item["name"] == service]
+ if len(containers) != 1:
+ raise ValueError(f"Expected exactly one app container named {service!r}")
+ return containers[0]
-def render_task_definition(document, *, service, image, cluster):
+def render_task_definition(document, *, service, image):
+ """Terraform (cloud-platform) owns every other field; a release changes only what
+ ships with the code."""
result = copy.deepcopy(document)
for field in READ_ONLY_FIELDS:
result.pop(field, None)
- containers = [item for item in result["containerDefinitions"] if item["name"] == service]
- if len(containers) != 1:
- raise ValueError(f"Expected exactly one app container named {service!r}")
- app = containers[0]
+ app = _app_container(result, service)
app["image"] = image
topology = json.loads((ROOT / "docker/worker-topology.json").read_text())
if service in topology:
@@ -57,86 +53,6 @@ def render_task_definition(document, *, service, image, cluster):
app["entryPoint"] = ["/usr/local/bin/worker-entrypoint.sh"]
elif service != "api":
raise ValueError(f"No reviewed command for service {service!r}")
- if service == "sandbox":
- linux = app.setdefault("linuxParameters", {})
- linux["initProcessEnabled"] = True
- linux["capabilities"] = {
- "add": ["SYS_PTRACE"],
- "drop": [
- "AUDIT_WRITE",
- "FSETID",
- "MKNOD",
- "NET_BIND_SERVICE",
- "NET_RAW",
- "SETFCAP",
- "SETPCAP",
- "SYS_CHROOT",
- ],
- }
- app["healthCheck"] = {
- "command": [
- "CMD",
- "python",
- "-c",
- "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health', timeout=5)",
- ],
- "interval": 30,
- "timeout": 15,
- "retries": 3,
- "startPeriod": 90,
- }
- app["stopTimeout"] = 120
- if service != "sandbox":
- _environment(app, RUN_DB_BOOTSTRAP="0")
- if service in {"celery-interactive-worker", "celery-landing-worker"}:
- volumes = result.setdefault("volumes", [])
- if any(
- volume["name"] == "workshop-scratch"
- and volume
- not in ({"name": "workshop-scratch"}, {"name": "workshop-scratch", "host": {}})
- for volume in volumes
- ):
- raise ValueError("Workshop scratch must use task-local ephemeral storage.")
- if not any(volume["name"] == "workshop-scratch" for volume in volumes):
- volumes.append({"name": "workshop-scratch"})
- mounts = app.setdefault("mountPoints", [])
- if any(
- mount["containerPath"] == "/scratch"
- and (mount["sourceVolume"] != "workshop-scratch" or mount.get("readOnly"))
- for mount in mounts
- ):
- raise ValueError("The /scratch mount conflicts with Workshop temporary storage.")
- if not any(mount["containerPath"] == "/scratch" for mount in mounts):
- mounts.append(
- {"sourceVolume": "workshop-scratch", "containerPath": "/scratch", "readOnly": False}
- )
- _environment(app, TMPDIR="/scratch/tmp")
- if service == "api" and cluster in {"overmind-prod-cluster", "overmind-staging-cluster"}:
- host = (
- "api.overmindlab.ai"
- if cluster == "overmind-prod-cluster"
- else "api-staging.overmindlab.ai"
- )
- _environment(app, MCP_SERVER_URL=f"https://{host}/api/mcp/")
- if service == "celery-control-worker":
- _environment(app, QUEUE_METRICS_ENABLED="1", QUEUE_METRICS_CLUSTER=cluster)
- if service in HEALTH_CHECKED_QUEUES:
- app["healthCheck"] = {
- "command": [
- "CMD",
- "python",
- "-m",
- "overbae.worker_health",
- HEALTH_CHECKED_QUEUES[service],
- ],
- "interval": 30,
- "timeout": 15,
- "retries": 3,
- "startPeriod": 90,
- }
- # Durable leases own retries after an interrupted process; scale-in
- # remains disabled until a reviewed graceful-drain policy is installed.
- app["stopTimeout"] = 120
return result
@@ -236,9 +152,7 @@ def register(cluster, service_name, image):
definition = aws("ecs", "describe-task-definition", "--task-definition", family)[
"taskDefinition"
]
- rendered = render_task_definition(
- definition, service=service_name, image=image, cluster=cluster
- )
+ rendered = render_task_definition(definition, service=service_name, image=image)
registered = aws("ecs", "register-task-definition", payload=rendered)["taskDefinition"]
return service, registered
@@ -259,11 +173,12 @@ def migrate(cluster, image):
if response.get("failures") or len(response.get("tasks", [])) != 1:
raise RuntimeError(f"Migration task was not accepted: {response.get('failures')}")
arn = response["tasks"][0]["taskArn"]
- subprocess.run(
- ["aws", "ecs", "wait", "tasks-stopped", "--cluster", cluster, "--tasks", arn],
- check=True,
- )
- task = aws("ecs", "describe-tasks", "--cluster", cluster, "--tasks", arn)["tasks"][0]
+ task = _stopped(cluster, arn, MIGRATION_SECONDS)
+ if task is None:
+ raise TimeoutError(
+ f"Migration {arn} still runs after {MIGRATION_SECONDS // 60} minutes; "
+ "re-run the release once it stops."
+ )
# Only the API app container runs migrations; ignore a successfully stopped sidecar.
app = next(c for c in task["containers"] if c["name"] == "api")
if app.get("exitCode") != 0:
@@ -289,17 +204,24 @@ def drain_io(cluster, image, timeout=4200):
if result.get("failures") or len(result.get("tasks", [])) != 1:
raise RuntimeError("IO drain task was not accepted; worker deployment stopped")
arn = result["tasks"][0]["taskArn"]
- deadline = time.monotonic() + timeout + 180
+ task = _stopped(cluster, arn, timeout + 180)
+ if task is None:
+ raise TimeoutError(f"IO drain did not complete: {arn}; worker deployment stopped")
+ app = next(c for c in task["containers"] if c["name"] == "api")
+ if app.get("exitCode") != 0:
+ raise RuntimeError(f"IO drain failed in {arn}; worker deployment stopped")
+ print(f"Mixed IO consumers drained: {arn}", flush=True)
+
+
+def _stopped(cluster, arn, timeout):
+ """The task once it stopped, or None at the deadline."""
+ deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
task = aws("ecs", "describe-tasks", "--cluster", cluster, "--tasks", arn)["tasks"][0]
if task["lastStatus"] == "STOPPED":
- app = next(c for c in task["containers"] if c["name"] == "api")
- if app.get("exitCode") != 0:
- raise RuntimeError(f"IO drain failed in {arn}; worker deployment stopped")
- print(f"Mixed IO consumers drained: {arn}", flush=True)
- return
+ return task
time.sleep(10)
- raise TimeoutError(f"IO drain did not complete: {arn}; worker deployment stopped")
+ return None
def deploy(cluster, service_name, image, timeout=4200, desired_count=None):
@@ -362,7 +284,7 @@ def deploy(cluster, service_name, image, timeout=4200, desired_count=None):
service,
tasks,
task_definition=arn,
- require_health=service_name in HEALTH_CHECKED_QUEUES or service_name == "sandbox",
+ require_health="healthCheck" in _app_container(definition, service_name),
):
print(f"Ready: {service_name} {arn}")
return
diff --git a/tests/coverage_map.py b/tests/coverage_map.py
index 32f7d2fd..0b736406 100644
--- a/tests/coverage_map.py
+++ b/tests/coverage_map.py
@@ -237,8 +237,9 @@ COVERAGE_MAP: dict[str, Entry] = {
"assistant-turn": Entry(
S2,
INVARIANT,
- "A turn runs from a message to the reply and saves every step: a turn that stopped "
- "moving is marked interrupted and writes nothing more, a stop ends it at the next "
+ "A turn runs from a message to the reply and saves every step: a turn whose worker "
+ "was lost continues its reply on another without running a call again, one lost too "
+ "often is marked interrupted and writes nothing more, a stop ends it at the next "
"step, a question ends it, and a dataset's deletion removes its copies from the "
"workspace. A publish runs its package on a sample first and publishes nothing when "
"the sample fails; the first message carries each version's fit and profile; a "
diff --git a/tests/test_admin_capacity.py b/tests/test_admin_capacity.py
new file mode 100644
index 00000000..b73f2aa2
--- /dev/null
+++ b/tests/test_admin_capacity.py
@@ -0,0 +1,52 @@
+import uuid
+
+import pytest
+from django.conf import settings
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
+
+from overbae.models import EvalRun, EvalRunRow, EvalScore, Project, User
+
+pytestmark = [pytest.mark.django_db, pytest.mark.covers("capacity")]
+
+
+def _pages(client, size):
+ project = Project.objects.create(name="admin", slug=uuid.uuid4().hex)
+ runs = EvalRun.objects.bulk_create(
+ [
+ EvalRun(project=project, name=f"run {index}", status="completed", model_name="m")
+ for index in range(size)
+ ]
+ )
+ EvalRunRow.objects.bulk_create(
+ [EvalRunRow(run=runs[0], row_index=index, error="lost") for index in range(size)]
+ )
+ EvalScore.objects.bulk_create(
+ [
+ EvalScore(project=project, run=run, source_id=f"cell:{index}", score=1)
+ for index, run in enumerate(runs)
+ ]
+ )
+ root = f"/{settings.ADMIN_URL_PATH}overbae"
+ score = EvalScore.objects.filter(run=runs[0]).get()
+ measured = []
+ for url in (
+ f"{root}/evalrun/{runs[0].pk}/change/",
+ f"{root}/evalscore/{score.pk}/change/",
+ f"{root}/evalscore/",
+ ):
+ with CaptureQueriesContext(connection) as queries:
+ response = client.get(url)
+ assert response.status_code == 200, url
+ measured.append((len(response.content), len(queries)))
+ return measured
+
+
+def test_eval_admin_pages_do_not_grow_with_rows_runs_or_scores(client):
+ client.force_login(User.objects.create_superuser(email="[email protected]", password="x" * 16))
+ small, large = _pages(client, 5), _pages(client, 400)
+ for (_, small_queries), (_, large_queries) in zip(small, large, strict=True):
+ assert large_queries <= small_queries
+ # A change page renders one record; a list page grows only to its page size.
+ for (small_bytes, _), (large_bytes, _) in zip(small[:2], large[:2], strict=True):
+ assert large_bytes < small_bytes * 1.2
diff --git a/tests/test_assistant_turn.py b/tests/test_assistant_turn.py
index 7475a1ce..4f2cfd75 100644
--- a/tests/test_assistant_turn.py
+++ b/tests/test_assistant_turn.py
@@ -176,6 +176,93 @@ def test_a_turn_that_stopped_moving_is_interrupted_and_writes_nothing_more(
log.append(thread, "assistant", {"text": "late", "calls": [], "usage": {}}, turn=4)
+def lost_midway(thread, user, *, calls):
+ """The record a worker leaves when it is lost while its reply is under way."""
+ threads.send(thread, user, request_key="lost", text="Count.")
+ message = thread.inputs.get()
+ AssistantThread.objects.filter(pk=thread.pk).update(state="running", turn=4)
+ AssistantInput.objects.filter(pk=message.pk).update(state=AssistantInput.State.DELIVERED)
+ log.append(
+ thread,
+ "user",
+ {
+ "input": str(message.pk),
+ "user": user.pk,
+ "text": "Count.",
+ "cells": [],
+ "interaction": None,
+ },
+ turn=4,
+ )
+ log.append(
+ thread, "assistant", {"text": "", "calls": calls, "reasoning": None, "usage": {}}, turn=4
+ )
+ AssistantThread.objects.filter(pk=thread.pk).update(
+ updated_at=timezone.now() - turn.LEASE - timedelta(seconds=1)
+ )
+
+
+def test_a_turn_whose_worker_was_lost_is_taken_over_and_continues_its_reply(
+ fake_llm, user, thread, woken
+):
+ query = {"summary": "Counting", "dataset": "x", "sql": "select 1"}
+ lost_midway(
+ thread, user, calls=[{"id": "c1", "name": "query_dataset", "raw": json.dumps(query)}]
+ )
+
+ assert turn.resume_lost() == 1 and woken == [str(thread.pk)]
+ fake_llm.stream_rounds([([], "It has 2 rows.")])
+ turn.run(thread.pk)
+ thread.refresh_from_db()
+
+ assert kinds(thread) == ["user", "assistant", "status", "assistant"]
+ assert thread.events.get(kind="status").payload["state"] == "resumed"
+ # The call that may have run is answered as abandoned, never run again.
+ assert not results(thread)
+ (request,) = fake_llm.streamed()
+ answered = [m for m in request.body["messages"] if m.get("tool_call_id") == "c1"]
+ assert json.loads(answered[0]["content"]) == turn.ABANDONED
+ assert thread.state == AssistantThread.State.IDLE and thread.turn == 5
+ with pytest.raises(log.LostTurnError):
+ log.append(thread, "assistant", {"text": "late", "calls": [], "usage": {}}, turn=4)
+
+
[email protected]("ended", ["reply", "failure", "question"])
+def test_a_reply_that_ended_is_not_written_again_when_its_turn_is_taken_over(
+ fake_llm, user, thread, ended
+):
+ calls = [
+ {"id": "ask", "name": "present", "raw": "{}"},
+ {"id": "q", "name": "query_dataset", "raw": "{}"},
+ ]
+ lost_midway(thread, user, calls=calls if ended == "question" else [])
+ if ended == "failure":
+ log.append(thread, "status", {"state": "failed", "detail": "The model did not answer."})
+ if ended == "question":
+ # The question came first; the reply's last call was an ordinary one.
+ question = {"root": {"type": "Question", "id": "task", "prompt": "Which task?"}}
+ for call, shown in (("ask", question), ("q", None)):
+ result = {"call": call, "name": "x", "ok": True, "content": {}}
+ log.append(thread, "tool_result", result, presentation=shown)
+ turn.run(thread.pk)
+ thread.refresh_from_db()
+ assert thread.events.last().payload["state"] == "resumed"
+ assert fake_llm.streamed() == []
+ assert thread.state == AssistantThread.State.IDLE
+
+
+def test_an_answered_question_is_replied_to_when_its_turn_is_taken_over(fake_llm, user, thread):
+ lost_midway(thread, user, calls=[{"id": "ask", "name": "present", "raw": "{}"}])
+ question = {"root": {"type": "Question", "id": "task", "prompt": "Which task?"}}
+ result = {"call": "ask", "name": "present", "ok": True, "content": {}}
+ log.append(thread, "tool_result", result, presentation=question)
+ answer = {"input": "x", "user": user.pk, "text": "Chat", "cells": [], "interaction": None}
+ log.append(thread, "user", answer)
+ fake_llm.stream_rounds([([], "Chat it is.")])
+ turn.run(thread.pk)
+ assert len(fake_llm.streamed()) == 1
+
+
def test_a_sender_who_left_the_project_runs_nothing(fake_llm, user, thread):
threads.send(thread, user, request_key="k", text="Prepare it.")
ProjectMembership.objects.filter(user=user).delete()
diff --git a/tests/test_celery_topology.py b/tests/test_celery_topology.py
index 429b98cb..08034c8b 100644
--- a/tests/test_celery_topology.py
+++ b/tests/test_celery_topology.py
@@ -265,23 +265,24 @@ def _deployed_commands() -> dict[str, str]:
return {name: " ".join(argv) for name, argv in topology.items()}
-def test_prefork_lanes_reserve_only_the_tasks_they_run():
+def test_worker_lanes_reserve_only_the_tasks_they_run():
"""A reserved late-ack message stays unacknowledged while it waits behind a
running task. Behind a 42-minute turn it outlives the broker's visibility
timeout and is delivered twice; reserving only for a free slot bounds the
- unacknowledged time by the task's own time limit."""
+ unacknowledged time by the task's own time limit. A reserved message also
+ waits behind a busy thread instead of going to an idle worker."""
commands = {
**{f"compose:{name}": service["command"] for name, service in _compose_services().items()},
**{f"deploy:{name}": command for name, command in _deployed_commands().items()},
}
- prefork = {name: c for name, c in commands.items() if "--pool=prefork" in c}
- assert prefork
+ workers = {name: c for name, c in commands.items() if _worker_queues(c) is not None}
+ assert workers
offenders = sorted(
name
- for name, command in prefork.items()
+ for name, command in workers.items()
if "--prefetch-multiplier=1" not in command or "--disable-prefetch" not in command
)
- assert not offenders, f"prefork workers that reserve ahead of a free slot: {offenders}"
+ assert not offenders, f"workers that reserve ahead of a free slot: {offenders}"
def test_redis_redelivers_only_after_every_late_ack_task_has_hit_its_time_limit():
diff --git a/tests/test_ecs_worker_rollout.py b/tests/test_ecs_worker_rollout.py
index 872abdc3..ff87e188 100644
--- a/tests/test_ecs_worker_rollout.py
+++ b/tests/test_ecs_worker_rollout.py
@@ -80,37 +80,32 @@ def test_every_release_overrides_stale_worker_command(definition, queue):
service = "celery-traces-worker" if queue == "io_traces" else f"celery-{queue}-worker"
definition["family"] = service
definition["containerDefinitions"][0]["name"] = service
- rendered = render_task_definition(
- definition, service=service, image="repo:new", cluster="test-cluster"
- )
+ rendered = render_task_definition(definition, service=service, image="repo:new")
container = rendered["containerDefinitions"][0]
assert container["image"] == "repo:new"
assert container["command"][-2:] == ["-Q", queue]
assert f"--hostname={queue}@%h" in container["command"]
assert container["entryPoint"] == ["/usr/local/bin/worker-entrypoint.sh"]
- assert container["healthCheck"]["command"][-2:] == ["overbae.worker_health", queue]
- assert container["stopTimeout"] == 120
assert rendered["containerDefinitions"][1]["image"] == "otel:stable"
- if queue in {"landing", "interactive"}:
- assert {entry["name"]: entry["value"] for entry in container["environment"]}[
- "TMPDIR"
- ] == "/scratch/tmp"
- assert {"name": "workshop-scratch"} in rendered["volumes"]
- assert rendered["cpu"] == definition["cpu"] and rendered["memory"] == definition["memory"]
- repeated = render_task_definition(
- rendered, service=service, image="repo:newer", cluster="test-cluster"
- )
- assert repeated["volumes"] == rendered["volumes"]
- assert repeated["containerDefinitions"][0]["mountPoints"] == container["mountPoints"]
- next(volume for volume in rendered["volumes"] if volume["name"] == "workshop-scratch")[
- "host"
- ] = {}
- assert (
- render_task_definition(
- rendered, service=service, image="repo:future", cluster="test-cluster"
- )["volumes"]
- == rendered["volumes"]
- )
+
+
[email protected]("service", ["api", "sandbox", "celery-landing-worker"])
+def test_a_release_keeps_every_field_terraform_owns(definition, service):
+ app = definition["containerDefinitions"][0]
+ app["name"] = service
+ app["healthCheck"] = {"command": ["CMD", "terraform"], "interval": 30}
+ app["linuxParameters"] = {"initProcessEnabled": True}
+ app["environment"].append({"name": "MCP_SERVER_URL", "value": "https://terraform/api/mcp/"})
+ definition["volumes"].append({"name": "workshop-scratch"})
+ rendered = render_task_definition(definition, service=service, image="repo:new")
+ owned = {
+ key: value for key, value in definition.items() if key not in deploy_ecs.READ_ONLY_FIELDS
+ }
+ kept = {key: value for key, value in rendered.items() if key != "containerDefinitions"}
+ assert kept == {key: value for key, value in owned.items() if key != "containerDefinitions"}
+ container = rendered["containerDefinitions"][0]
+ for key in ("healthCheck", "linuxParameters", "environment", "stopTimeout", "mountPoints"):
+ assert container[key] == app[key]
def test_migration_cannot_start_http_server(definition, service):
@@ -128,25 +123,6 @@ def test_migration_cannot_start_http_server(definition, service):
)
- ("cluster", "url"),
- [
- ("overmind-prod-cluster", "https://api.overmindlab.ai/api/mcp/"),
- ("overmind-staging-cluster", "https://api-staging.overmindlab.ai/api/mcp/"),
- ],
-)
-def test_api_release_restores_environment_bound_mcp_url(definition, cluster, url):
- app = definition["containerDefinitions"][0]
- app["name"] = "api"
- app["environment"].append({"name": "MCP_SERVER_URL", "value": "http://localhost:8000/api/mcp/"})
- rendered = render_task_definition(definition, service="api", image="repo:new", cluster=cluster)
- environment = {
- item["name"]: item["value"] for item in rendered["containerDefinitions"][0]["environment"]
- }
- assert environment["MCP_SERVER_URL"] == url
- assert environment["KEEP"] == "yes"
-
-
def test_running_container_without_health_or_current_revision_is_not_ready():
service = {
"desiredCount": 1,
@@ -209,31 +185,39 @@ def test_a_release_builds_on_the_latest_revision_of_the_family(monkeypatch, defi
[release] = registered
assert release["taskRoleArn"] == "arn:aws:iam::123:role/latest"
assert release["containerDefinitions"][0]["environment"] == [
- {"name": "FROM", "value": "terraform"},
- {"name": "RUN_DB_BOOTSTRAP", "value": "0"},
+ {"name": "FROM", "value": "terraform"}
]
assert release["containerDefinitions"][0]["image"] == "repo:new"
-def test_document_parser_keeps_main_isolation_command_and_health(definition):
+def test_document_parser_runs_the_reviewed_sandbox_command(definition):
definition["containerDefinitions"][0]["name"] = "sandbox"
- rendered = render_task_definition(
- definition, service="sandbox", image="repo:new", cluster="test"
- )
- container = rendered["containerDefinitions"][0]
- assert container["command"] == ["python", "-m", "sandbox"]
- assert container["linuxParameters"]["initProcessEnabled"] is True
- assert container["linuxParameters"]["capabilities"]["add"] == ["SYS_PTRACE"]
- assert "NET_RAW" in container["linuxParameters"]["capabilities"]["drop"]
- assert "/health" in container["healthCheck"]["command"][-1]
+ rendered = render_task_definition(definition, service="sandbox", image="repo:new")
+ assert rendered["containerDefinitions"][0]["command"] == ["python", "-m", "sandbox"]
def test_dedicated_workshop_controller_has_no_deployable_command(definition):
definition["containerDefinitions"][0]["name"] = "workshop-runner"
with pytest.raises(ValueError, match="No reviewed command"):
- render_task_definition(
- definition, service="workshop-runner", image="repo:new", cluster="test"
- )
+ render_task_definition(definition, service="workshop-runner", image="repo:new")
+
+
+def test_migrate_waits_past_ten_minutes_for_a_running_migration(monkeypatch, definition, service):
+ definition["containerDefinitions"][0]["name"] = "api"
+ polls = iter(["RUNNING"] * 120 + ["STOPPED"])
+
+ def fake_aws(*args, payload=None):
+ if args[:2] == ("ecs", "run-task"):
+ return {"tasks": [{"taskArn": "migration"}]}
+ status = next(polls)
+ return {"tasks": [{"lastStatus": status, "containers": [{"name": "api", "exitCode": 0}]}]}
+
+ monkeypatch.setattr(deploy_ecs, "preflight", lambda cluster: None)
+ monkeypatch.setattr(deploy_ecs, "register", lambda *_: (service, definition))
+ monkeypatch.setattr(deploy_ecs, "aws", fake_aws)
+ monkeypatch.setattr(deploy_ecs.time, "sleep", lambda seconds: None)
+ deploy_ecs.migrate("test", "repo:new")
+ assert next(polls, "done") == "done"
def test_deploy_does_not_guess_capacity_for_a_service_scaled_to_zero(monkeypatch):
diff --git a/tests/test_eval_generation_admission.py b/tests/test_eval_generation_admission.py
index efd13e31..c755eca0 100644
--- a/tests/test_eval_generation_admission.py
+++ b/tests/test_eval_generation_admission.py
@@ -124,19 +124,36 @@ def test_a_stale_task_id_cannot_claim_the_row(limits):
assert generation.claim(row_id, task_id) is False
-def test_lost_running_work_is_recorded_unknown_and_not_replayed(limits):
+def test_lost_running_work_runs_once_more_under_a_new_token_then_is_unknown(limits):
+ make_run(count=1)
+ published = Published()
+ published.tick()
+ for _ in range(generation.GENERATION_ATTEMPTS):
+ row_id, task_id = published.rows[-1]
+ assert generation.claim(row_id, task_id)
+ EvalRunRow.objects.filter(pk=row_id).update(
+ expires_at=timezone.now() - timedelta(seconds=1)
+ )
+ assert published.tick()["expired"] == 1
+ assert not generation.claim(row_id, task_id)
+ row = EvalRunRow.objects.get(pk=row_id)
+ assert row.state == EvalRunRow.State.UNKNOWN
+ assert row.attempts == generation.GENERATION_ATTEMPTS
+ assert "unknown" in row.error
+ assert len(published.rows) == generation.GENERATION_ATTEMPTS
+
+
+def test_a_message_lost_before_its_claim_waits_again_without_an_attempt(limits):
make_run(count=1)
published = Published()
published.tick()
row_id, task_id = published.rows[0]
- generation.claim(row_id, task_id)
EvalRunRow.objects.filter(pk=row_id).update(expires_at=timezone.now() - timedelta(seconds=1))
-
- assert published.tick()["expired"] == 1
+ published.tick()
row = EvalRunRow.objects.get(pk=row_id)
- assert row.state == EvalRunRow.State.UNKNOWN
- assert "not replayed" in row.error
- assert len(published.rows) == 1
+ assert (row.state, row.attempts, row.error) == (EvalRunRow.State.QUEUED, 0, "")
+ assert not generation.claim(row_id, task_id)
+ assert generation.claim(*published.rows[-1])
def test_a_saved_result_survives_worker_loss_without_replay(limits):
diff --git a/tests/test_eval_recovery.py b/tests/test_eval_recovery.py
new file mode 100644
index 00000000..5f6d0b6e
--- /dev/null
+++ b/tests/test_eval_recovery.py
@@ -0,0 +1,110 @@
+"""An evaluation outlives the worker that runs it: a lost scorer is replaced and keeps
+the scores already saved, and a run whose start was lost is sent again."""
+
+import uuid
+from datetime import timedelta
+from types import SimpleNamespace
+
+import pytest
+from conftest import frozen_dataset
+from django.utils import timezone
+from factories import make_matrix_row, make_project
+
+from overbae.innermind import dataset, generation, runs
+from overbae.models import EvalMatrix, EvalRun, EvalScore
+from overbae.tasks import innermind as tasks
+
+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("recovery")]
+
+ROWS = [{"input": f"q{index}", "expected_output": f"a{index}"} for index in range(3)]
+
+
+def scored_run():
+ project = make_project()
+ matrix = make_matrix_row(
+ project,
+ type=EvalMatrix.Type.DETERMINISTIC,
+ source="def evaluate(span):\n return 1.0\n",
+ )
+ run = runs.create_run(
+ project=project,
+ name="recorded",
+ cell=frozen_dataset(project, ROWS).active_cell,
+ mode=EvalRun.Mode.RECORDED,
+ matrix=[matrix.snapshot()],
+ )
+ assert runs.start(run.pk) == "score"
+ return EvalRun.objects.get(pk=run.pk)
+
+
+def handed(run):
+ published = []
+ generation.dispatch(lambda *_: None, lambda run_id, token: published.append(token))
+ return published[-1]
+
+
+def silence(run):
+ EvalRun.objects.filter(pk=run.pk).update(
+ updated_at=timezone.now() - runs.SCORER_STALE - timedelta(seconds=1)
+ )
+
+
+def test_a_lost_scorer_is_replaced_and_keeps_the_scores_it_saved():
+ run = scored_run()
+ lost = handed(run)
+ assert generation.begin_scoring(run.pk, lost)
+ first = run.rows.order_by("row_index").first()
+ dataset._save(
+ EvalScore(project=run.project, run=run, source_id=f"{run.cell_id}:{first.row_index}"),
+ lost,
+ )
+ silence(run)
+
+ runs.reap_stalled()
+
+ with pytest.raises(dataset.ScoringLostError):
+ dataset._save(EvalScore(project=run.project, run=run, source_id="late"), lost)
+ with pytest.raises(dataset.ScoringLostError):
+ dataset._row_failed(first, lost, "late judge error")
+ replacement = handed(run)
+ assert replacement != lost
+ assert runs.score(run.pk, replacement)
+ run.refresh_from_db()
+ assert run.status == EvalRun.Status.COMPLETED
+ assert run.scoring_attempts == 2
+ assert sorted(run.scores.values_list("source_id", flat=True)) == sorted(
+ f"{run.cell_id}:{index}" for index in range(len(ROWS))
+ )
+
+
+def test_a_hand_off_that_waited_in_the_queue_starts_with_a_fresh_heartbeat():
+ run = scored_run()
+ token = handed(run)
+ silence(run)
+ assert generation.begin_scoring(run.pk, token)
+ runs.reap_stalled()
+ assert EvalRun.objects.get(pk=run.pk).scoring_task_id == token
+
+
+def test_a_run_whose_start_was_lost_is_sent_again_then_failed(monkeypatch):
+ sent = []
+ monkeypatch.setattr(
+ tasks.run_eval_run,
+ "delay",
+ lambda **kwargs: sent.append(kwargs) or SimpleNamespace(id=str(uuid.uuid4())),
+ )
+ run = EvalRun.objects.create(project=make_project(), name="lost start")
+ EvalRun.objects.filter(pk=run.pk).update(
+ updated_at=timezone.now() - runs.PENDING_RESEND - timedelta(seconds=1)
+ )
+ runs.reap_stalled()
+ assert sent == [{"eval_run_id": str(run.pk)}]
+ assert EvalRun.objects.get(pk=run.pk).status == EvalRun.Status.PENDING
+
+ EvalRun.objects.filter(pk=run.pk).update(
+ updated_at=timezone.now() - runs.PENDING_LIMIT - timedelta(seconds=1)
+ )
+ runs.reap_stalled()
+ run.refresh_from_db()
+ assert run.status == EvalRun.Status.FAILED
+ assert "never started" in run.error
diff --git a/tests/test_landing_admission.py b/tests/test_landing_admission.py
index b484d508..3b62b6d0 100644
--- a/tests/test_landing_admission.py
+++ b/tests/test_landing_admission.py
@@ -216,3 +216,90 @@ def test_publication_allows_its_independent_heartbeat_and_still_rejects_expired_
publication.apply(task_id=str(work.pk), headers={admission.HEADER: str(work.owner)}).get(
propagate=True
)
+
+
+def admitted_upload(monkeypatch, filename, content):
+ from functools import partial
+
+ from overbae.models import DatasetImport
+ from overbae.services.datasets import dispatch, files
+ from overbae.tasks.datasets import LandingTask
+
+ # Submissions go through admission, as on a deployed worker.
+ monkeypatch.setattr(land, "apply_async", partial(LandingTask.apply_async, land))
+ upload_id, _ = files.begin_upload(filename)
+ files.append_chunk(upload_id, 0, content)
+ files.inspect_upload(upload_id, size=files.upload_received(upload_id))
+ dataset = dispatch.create_dataset(
+ project=make_project(), user=None, name="P", source={"uploads": [upload_id]}, intent="train"
+ )
+ return dataset, DatasetImport.objects.get(dataset=dataset), upload_id
+
+
+def lapse(run):
+ from overbae.models import DatasetImport
+
+ lapsed = timezone.now() - timedelta(seconds=1)
+ DatasetLandingWork.objects.filter(pk=run.pk).update(lease_until=lapsed)
+ DatasetImport.objects.filter(pk=run.pk).update(lease_until=lapsed)
+
+
+def test_a_lost_upload_retries_under_a_new_owner_until_its_attempt_limit(monkeypatch):
+ from factories import make_user
+
+ from overbae.services.assistant import threads
+ from overbae.services.datasets import files, imports
+ from overbae.tasks.assistant import run_turn
+
+ dataset, run, upload_id = admitted_upload(
+ monkeypatch, "passengers.csv", b"passenger_id,survived\n1,0\n2,1\n"
+ )
+ woken = []
+ monkeypatch.setattr(run_turn, "delay", woken.append)
+ conversation = threads.open_thread(dataset)
+ threads.send(conversation, make_user(), request_key="sent", text="Prepare it.")
+ messages = []
+ admission.dispatch(lambda **message: messages.append(message))
+ owners = []
+ for attempt in range(1, imports.MAX_ATTEMPTS + 1):
+ owner = messages[-1]["headers"][admission.HEADER]
+ owners.append(owner)
+ assert admission.claim(run.pk, owner)
+ assert imports.claim(run.pk) is not None
+ lapse(run)
+ imports.reconcile()
+ admission.reconcile(lambda **message: messages.append(message))
+ run.refresh_from_db()
+ dataset.refresh_from_db()
+ if attempt < imports.MAX_ATTEMPTS:
+ assert (run.state, dataset.state) == ("queued", "landing")
+ assert len(messages) == attempt + 1
+ assert run.state == "blocked" and run.failure_code == "attempts_exhausted"
+ assert dataset.state == "error"
+ assert DatasetLandingWork.objects.get(pk=run.pk).state == "failed"
+ assert files.upload_data_path(upload_id).exists()
+ # The message sent with the upload no longer waits for a source that will not land.
+ assert woken == [str(conversation.pk)]
+ stale = land.apply(
+ kwargs=messages[0]["kwargs"], task_id=str(run.pk), headers={admission.HEADER: owners[0]}
+ )
+ assert stale.get() == {"status": "not_claimed"}
+
+
+def test_a_document_read_cut_by_a_sandbox_restart_is_retried(monkeypatch, settings):
+ from pathlib import Path
+
+ settings.SANDBOX_URL = "http://127.0.0.1:9"
+ scanned = (Path(__file__).parent / "fixtures/documents/scanned.pdf").read_bytes()
+ dataset, run, _ = admitted_upload(monkeypatch, "scanned.pdf", scanned)
+ messages = []
+ admission.dispatch(lambda **message: messages.append(message))
+ [message] = messages
+ assert land.apply(**message).get()["status"] == "retry"
+ run.refresh_from_db()
+ dataset.refresh_from_db()
+ assert (run.state, dataset.state) == ("running", "landing")
+ lapse(run)
+ admission.reconcile(lambda **message: messages.append(message))
+ run.refresh_from_db()
+ assert run.state == "queued" and len(messages) == 2
diff --git a/tests/test_otlp_dialects.py b/tests/test_otlp_dialects.py
index d1e0f900..9b8c6d4e 100644
--- a/tests/test_otlp_dialects.py
+++ b/tests/test_otlp_dialects.py
@@ -219,3 +219,37 @@ def test_a_span_names_the_attributes_holding_its_input_and_output(
input_attribute,
output_attribute,
)
+
+
+def test_a_name_longer_than_its_column_does_not_reject_the_batch():
+ project = make_project()
+ span_id = uuid.uuid4().hex[:16]
+ ingest_spans(
+ project,
+ [{"name": "n" * 4000, "attributes": {}, "span_id": span_id}],
+ resource={"service.name": "s" * 4000},
+ )
+ span = Span.objects.get(project=project, span_id=span_id)
+ assert span.name == "n" * 255
+ assert span.service_name == "s" * 255
+
+
[email protected]("gzipped", [False, True])
+def test_an_export_over_the_size_limit_is_refused_before_parsing(gzipped):
+ import gzip
+
+ from overbae.api.otlp import MAX_EXPORT_BYTES
+
+ owner = make_user()
+ project = make_project(member=owner)
+ body = b"\0" * (MAX_EXPORT_BYTES + 1)
+ headers = {}
+ if gzipped:
+ body = gzip.compress(body)
+ assert len(body) < MAX_EXPORT_BYTES
+ headers["HTTP_CONTENT_ENCODING"] = "gzip"
+ response = api_key_client(owner, project).post(
+ "/api/v1/traces", data=body, content_type="application/x-protobuf", **headers
+ )
+ assert response.status_code == 413
+ assert not Span.objects.filter(project=project).exists()
diff --git a/tests/test_queue_metrics.py b/tests/test_queue_metrics.py
index 1e827578..c3378413 100644
--- a/tests/test_queue_metrics.py
+++ b/tests/test_queue_metrics.py
@@ -273,3 +273,50 @@ def test_landing_metrics_distinguish_user_data_failures_and_current_retry_age():
measured = read_workloads()["landing"]
assert measured["blocked"] == 0
assert measured["oldest"] == now
+
+
+def test_a_recycled_scoring_row_waits_from_its_recycle_not_its_creation():
+ from overbae.innermind import admission
+ from overbae.models import LiveScoringWork, Project
+
+ project = Project.objects.create(name="recycled", slug="recycled-age")
+ admission.enqueue(project.pk, "span", ["a"])
+ month_ago = timezone.now() - timedelta(days=30)
+ LiveScoringWork.objects.update(state="done", created_at=month_ago, waiting_since=month_ago)
+ admission.enqueue(project.pk, "span", ["a"])
+ oldest = read_workloads()["io_traces"]["oldest"]
+ assert timezone.now() - oldest < timedelta(minutes=1)
+
+
+def test_eval_demand_counts_only_rows_admission_can_start(settings):
+ import uuid
+
+ from overbae.models import EvalRun, EvalRunRow, Project
+
+ settings.EVAL_MAX_IN_FLIGHT = 12
+ settings.EVAL_MAX_IN_FLIGHT_PER_RUN = 2
+ settings.EVAL_MAX_IN_FLIGHT_PER_PROJECT = 4
+
+ def run(project, rows, scoring=""):
+ made = EvalRun.objects.create(
+ project=project,
+ name="run",
+ status=EvalRun.Status.RUNNING,
+ mode=EvalRun.Mode.GENERATE,
+ model_name="openai/gpt-5-mini",
+ scoring_task_id=scoring,
+ )
+ EvalRunRow.objects.bulk_create(
+ [EvalRunRow(run=made, row_index=index) for index in range(rows)]
+ )
+
+ big = Project.objects.create(name="big", slug=uuid.uuid4().hex)
+ for _ in range(3):
+ run(big, 5000)
+ run(Project.objects.create(name="small", slug=uuid.uuid4().hex), 1)
+ run(big, 0, scoring=str(uuid.uuid4()))
+ workload = read_workloads()["batch"]
+ assert workload["waiting"] == 15001
+ assert workload["scaling_demand"] == 4 + 1 + 1
diff --git a/tests/test_workshop_preparation_journey.py b/tests/test_workshop_preparation_journey.py
index fd50cd51..36af2b65 100644
--- a/tests/test_workshop_preparation_journey.py
+++ b/tests/test_workshop_preparation_journey.py
@@ -412,3 +412,45 @@ def test_workshop_surfaces_omit_retired_checks_but_keep_execution_receipts():
assert "preparation_status" not in process
assert len(process["preparation"]["nodes"]) == 2
assert process["current_pipeline"] == recipe["id"]
+
+
[email protected]("recovery")
+def test_a_running_script_holds_a_lease_a_lost_worker_lets_lapse_within_minutes():
+ from datetime import timedelta
+
+ from django.utils import timezone
+
+ from overbae.services.datasets import heartbeat
+
+ project, client, context = workspace()
+ dataset = source(client, project, "Leased source", [{"value": 1}])
+ recipe = call(
+ context,
+ "save_dataset_pipeline",
+ name="Leased decisions",
+ request_key="leased-recipe",
+ package=retained_package(project, context.user, [decision_step()]),
+ )["pipeline"]
+ receipt = call(
+ context,
+ "run_dataset_pipeline",
+ dataset=str(dataset.pk),
+ pipeline=recipe["id"],
+ source_cell=str(dataset.active_cell.pk),
+ source_fingerprint=dataset.active_cell.fingerprint,
+ request_key="leased-run",
+ )
+ DatasetPipelineRun.objects.filter(pk=receipt["run"]["id"], state="running").update(
+ state="queued"
+ )
+ left = []
+
+ def observing(run, *args, **kwargs):
+ lease = DatasetPipelineRun.objects.get(pk=run.pk).lease_until
+ left.append(lease - timezone.now())
+ return execute_fixture(run, *args, **kwargs)
+
+ workbench.execute(receipt["run"]["id"], script_executor=observing)
+ assert left
+ assert all(timedelta(0) < lease <= timedelta(seconds=heartbeat.STALE_SECONDS) for lease in left)
+ assert DatasetPipelineRun.objects.get(pk=receipt["run"]["id"]).state == "completed"