Skip to content

The platform for continuously improving AI agents.

Make training and inference execution reliable (#311)

Tyler-Edwards114a363f782c
diff --git a/.agents/skills/backend-architecture/references/data-first.md b/.agents/skills/backend-architecture/references/data-first.md
index 289f6328..d7afc6d1 100644
--- a/.agents/skills/backend-architecture/references/data-first.md
+++ b/.agents/skills/backend-architecture/references/data-first.md
@@ -20,7 +20,7 @@ Data-first projects start from uploaded data and the original task brief (`Datas
- Experiments prepare a configuration-bound forecast before launch and may enforce user-defined planning constraints. Unmeasured or over-budget quotes do not recommend launch. Constraints are not an invoice cap.
- Native comparisons save a draft, prepare immutable suites in the background and launch explicitly. Calibration is a barrier: it is fitted (global, then per kind, by local L-BFGS-B) before final predictions, and stays separate from final scoring. References stay local and never enter a worker.
- Every paid call is journaled. Unacknowledged native submissions and bare external intents are never replayed; a paused native collector resumes only with its exact recorded `call_id`. Explicit resume of a local stage (`verify_inputs`, `fit_calibration`, `score`) fences the interrupted lease and reuses saved inputs without provider calls. Pause stops new claims; it does not cancel remote work.
-- Transient stage failures retry with 15/30-second backoff, at most three attempts. External timeouts and 429/5xx responses retry only missing rows, keeping uncertain costs in the attempt ledger.
+- Transient stage failures retry with 15/30-second backoff, at most three attempts. Explicit 429/5xx responses retry only rejected rows. External timeouts retain `submission_unknown` without replay; uncertain costs stay in the attempt ledger.
- Exhausted collection scores the verified predictions that exist. Results report `completion.status`, per-suite coverage and issues; partial results are `completed_with_issues`, never silent success or zero-filled scores.
- Database receipts keep aggregate and per-benchmark metrics; complete diagnostic slices live in the checksum-bound downloadable report.
- Benchmark workers publish checksum-bound prediction chunks under the exact call ID. The collector verifies runtime, input and artifact identity before indexing into a local SQLite projection beside the suite. Missing indexes rebuild from retained predictions, never from new inference.
diff --git a/frontend/src/components/entity-ref/cards.tsx b/frontend/src/components/entity-ref/cards.tsx
index 2e317f87..f39c720b 100644
--- a/frontend/src/components/entity-ref/cards.tsx
+++ b/frontend/src/components/entity-ref/cards.tsx
@@ -29,7 +29,7 @@ function livePoll(status: unknown) {
}
function pct(value: number | null | undefined) {
- return value == null ? null : `${Math.round(value * 100)}%`;
+ return value == null ? null : `${Math.round(value)}%`;
}
function isTerminal(status: unknown) {
diff --git a/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx b/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx
index 2ab9c75c..6755053f 100644
--- a/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx
+++ b/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx
@@ -423,3 +423,22 @@ it("uses the same standard validation split for checks, estimates and launch", a
}),
]);
});
+
+it("keeps an external benchmark selected after the training base model", async () => {
+ const { result } = renderHook(() => useTrainWizard(args));
+ await waitFor(() => expect(result.current.canLaunch).toBe(true));
+ act(() => {
+ result.current.setEvaluationEnabled(true);
+ result.current.setBenchmarkingEnabled(true);
+ result.current.toggleBenchmarkModel("model");
+ result.current.toggleBenchmarkModel("anthropic/claude-sonnet-5");
+ });
+ await act(() => result.current.launch());
+ expect(mocks.create).toHaveBeenCalledWith([
+ expect.objectContaining({
+ baselineModel: "anthropic/claude-sonnet-5",
+ benchmarkModels: ["anthropic/claude-sonnet-5"],
+ evalIncumbentBefore: true,
+ }),
+ ]);
+});
diff --git a/frontend/src/components/finetuning/train/use-train-wizard.ts b/frontend/src/components/finetuning/train/use-train-wizard.ts
index 290b64eb..a43363b1 100644
--- a/frontend/src/components/finetuning/train/use-train-wizard.ts
+++ b/frontend/src/components/finetuning/train/use-train-wizard.ts
@@ -152,7 +152,10 @@ export function useTrainWizard({
}, [capability?.model, benchmarksQuery.data, evaluationCatalogQuery.data]);
const benchmarkModels =
benchmarkSelection ?? (capability?.model?.trim() ? [capability.model.trim()] : []);
- const benchmarkModel = benchmarkModels[0] ?? "";
+ const eligibleBenchmarkModels = benchmarkModels.filter((id) =>
+ benchmarkOptions.some((option) => option.value === id)
+ );
+ const benchmarkModel = eligibleBenchmarkModels[0] ?? "";
const selectedBenchmark = benchmarkOptions.find((option) => option.value === benchmarkModel);
const nativeDecision = validation?.format === "decision";
const hasIncumbent =
@@ -623,7 +626,7 @@ export function useTrainWizard({
...(evaluationPlan.evalIncumbentBefore && benchmarkModel
? { baselineModel: benchmarkModel }
: {}),
- benchmarkModels: evaluationPlan.evalIncumbentBefore ? benchmarkModels : [],
+ benchmarkModels: evaluationPlan.evalIncumbentBefore ? eligibleBenchmarkModels : [],
capability: capabilityId || null,
cell: dataset?.active ?? undefined,
dataset: datasetId,
@@ -678,7 +681,7 @@ export function useTrainWizard({
evalDataset?.active,
nativeDecision,
benchmarkModel,
- benchmarkModels,
+ eligibleBenchmarkModels,
capabilityId,
catalogModelById,
computedName,
diff --git a/frontend/src/hooks/use-optimizer.ts b/frontend/src/hooks/use-optimizer.ts
index 2a435c09..c42d2999 100644
--- a/frontend/src/hooks/use-optimizer.ts
+++ b/frontend/src/hooks/use-optimizer.ts
@@ -6,10 +6,17 @@ import { isExperimentLive } from "@/components/optimiser/experiment-status";
export const useOptimizerExperimentsQuery = (projectId: string | undefined) =>
useQuery({
enabled: !!projectId,
- queryFn: () =>
- apiClient.optimizerExperiments.optimizerExperimentsList({
- pageSize: 100,
- }),
+ queryFn: async ({ signal }) => {
+ const results = [];
+ for (let page = 1; ; page++) {
+ const data = await apiClient.optimizerExperiments.optimizerExperimentsList(
+ { page, pageSize: 100, project: projectId },
+ { signal }
+ );
+ results.push(...data.results);
+ if (!data.next) return { ...data, next: null, previous: null, results };
+ }
+ },
queryKey: ["optimizer-experiments", projectId],
refetchInterval: (query) => {
const rows = query.state.data?.results ?? [];
diff --git a/frontend/src/openapi/apis/OptimizerExperimentsApi.ts b/frontend/src/openapi/apis/OptimizerExperimentsApi.ts
index 442469bf..24c4f4fa 100644
--- a/frontend/src/openapi/apis/OptimizerExperimentsApi.ts
+++ b/frontend/src/openapi/apis/OptimizerExperimentsApi.ts
@@ -100,6 +100,7 @@ export interface OptimizerExperimentsListRequest {
ordering?: string;
page?: number;
pageSize?: number;
+ project?: string;
search?: string;
}
@@ -640,6 +641,10 @@ export class OptimizerExperimentsApi extends runtime.BaseAPI {
queryParameters['page_size'] = requestParameters['pageSize'];
}
+ if (requestParameters['project'] != null) {
+ queryParameters['project'] = requestParameters['project'];
+ }
+
if (requestParameters['search'] != null) {
queryParameters['search'] = requestParameters['search'];
}
diff --git a/modal_shared/chat_checkpoint.py b/modal_shared/chat_checkpoint.py
new file mode 100644
index 00000000..10628584
--- /dev/null
+++ b/modal_shared/chat_checkpoint.py
@@ -0,0 +1,57 @@
+import json
+from pathlib import Path
+
+from modal_shared.serving.artifacts import (
+ atomic_json,
+ digest_file,
+ digest_json,
+ file_state,
+ validate_files,
+)
+
+MANIFEST = "checkpoint.json"
+
+
+def read_checkpoint(directory: Path) -> dict:
+ manifest = json.loads((directory / MANIFEST).read_text())
+ if manifest["identity"] != digest_json(manifest["files"]):
+ raise ValueError("Checkpoint manifest identity mismatch")
+ validate_files(directory, manifest["files"])
+ return manifest
+
+
+def seal_checkpoint(directory: Path) -> dict:
+ adapter = (directory / "adapter_config.json").is_file()
+ config = "adapter_config.json" if adapter else "config.json"
+ json.loads((directory / config).read_text())
+ json.loads((directory / "tokenizer_config.json").read_text())
+ if not any(
+ (directory / name).is_file() for name in ("tokenizer.json", "tokenizer.model", "vocab.json")
+ ):
+ raise ValueError("Checkpoint has no tokenizer vocabulary")
+ prefix = "adapter_model" if adapter else "model"
+ index = directory / f"{prefix}.safetensors.index.json"
+ weights = (
+ set(json.loads(index.read_text())["weight_map"].values())
+ if index.exists()
+ else {f"{prefix}.safetensors"}
+ )
+ if not weights:
+ raise ValueError("Checkpoint has no weights")
+ for name in weights:
+ if Path(name).name != name or not name.endswith(".safetensors"):
+ raise ValueError("Checkpoint has an invalid weight shard path")
+ if file_state(directory / name)["size"] == 0:
+ raise ValueError("Checkpoint has an empty weight shard")
+ files = {}
+ for path in sorted(directory.iterdir()):
+ if path.name == MANIFEST or path.name.startswith(".") or path.is_dir():
+ continue
+ before = file_state(path)
+ checksum = digest_file(path)
+ if file_state(path) != before:
+ raise ValueError("Checkpoint changed during publication")
+ files[path.name] = {**before, "sha256": checksum}
+ manifest = {"files": files, "identity": digest_json(files)}
+ atomic_json(directory / MANIFEST, manifest)
+ return manifest
diff --git a/modal_shared/serving/decision_http.py b/modal_shared/serving/decision_http.py
index 8956dfc3..7ef86132 100644
--- a/modal_shared/serving/decision_http.py
+++ b/modal_shared/serving/decision_http.py
@@ -81,7 +81,11 @@ def decision_base_vllm_command(
def systemone_question(request: dict) -> dict:
kind = request["kind"]
if kind == "noul":
- return {"type": "noul", "instructions": request["question"]}
+ return {
+ "type": "noul",
+ "instructions": request["question"],
+ "criteria": {"false": request["options"][0], "true": request["options"][1]},
+ }
if kind == "score":
return {
"type": "score",
diff --git a/overbae/api/completions.py b/overbae/api/completions.py
index 1c01ed45..f856388b 100644
--- a/overbae/api/completions.py
+++ b/overbae/api/completions.py
@@ -323,7 +323,7 @@ def _resolve_alias(request: Request, model_id: str) -> tuple[DeployedModel | Non
)
if deployed.inference_contract == "decision":
- return Response(
+ return None, Response(
{
"error": {
"message": "This model returns decision probabilities. Call POST /api/v1/systemone.",
diff --git a/overbae/api/optimizer.py b/overbae/api/optimizer.py
index 0473c426..2fc915e4 100644
--- a/overbae/api/optimizer.py
+++ b/overbae/api/optimizer.py
@@ -224,7 +224,10 @@ class OptimizerExperimentCreateSerializer(serializers.ModelSerializer):
location=OpenApiParameter.QUERY,
required=False,
description="Only return experiments for this capability.",
- )
+ ),
+ OpenApiParameter(
+ name="project", type=OpenApiTypes.UUID, location=OpenApiParameter.QUERY
+ ),
]
)
)
@@ -240,6 +243,9 @@ class OptimizerExperimentViewSet(viewsets.ModelViewSet):
qs = OptimizerExperiment.objects.filter(
project_id__in=project_ids_for(self.request.user, self.request.auth)
).select_related("capability", "dataset", "cell", "eval_set")
+ project_id = self.request.query_params.get("project")
+ if project_id:
+ qs = qs.filter(project_id=project_id)
capability_id = self.request.query_params.get("capability")
if capability_id:
qs = qs.filter(capability_id=capability_id)
diff --git a/overbae/core/llms.py b/overbae/core/llms.py
index aae6dc34..450932ae 100644
--- a/overbae/core/llms.py
+++ b/overbae/core/llms.py
@@ -397,11 +397,13 @@ def _cached_tokens(usage: Any) -> int:
def _extract_llm_response(response) -> tuple[str, dict]:
message = response.choices[0].message
content = message.content
- if content is None:
- tool_calls = getattr(message, "tool_calls", None)
- if tool_calls:
- content = json.dumps({"tool_calls": [tc.model_dump() for tc in tool_calls]})
- elif getattr(response.choices[0], "finish_reason", None) in INCOMPLETE_FINISH_REASONS:
+ tool_calls = getattr(message, "tool_calls", None)
+ if tool_calls:
+ content = json.dumps(
+ {"content": content, "tool_calls": [tc.model_dump() for tc in tool_calls]}
+ )
+ elif content is None:
+ if getattr(response.choices[0], "finish_reason", None) in INCOMPLETE_FINISH_REASONS:
content = ""
else:
raise ValueError("No content or tool calls received from LLM")
diff --git a/overbae/innermind/replay.py b/overbae/innermind/replay.py
index 87853509..a334e755 100644
--- a/overbae/innermind/replay.py
+++ b/overbae/innermind/replay.py
@@ -492,7 +492,9 @@ def _parse_assistant(raw: str) -> tuple[dict[str, Any], list[dict[str, Any]]]:
parsed = chatml.maybe_parse_json(raw)
if isinstance(parsed, dict) and "tool_calls" in parsed:
calls = chatml.normalize_tool_calls(parsed["tool_calls"])
- return _assistant_with_calls(calls), calls
+ assistant = _assistant_with_calls(calls)
+ assistant["content"] = parsed.get("content") or ""
+ return assistant, calls
calls = normalizer.parse_text_tool_calls(raw)
if calls:
return _assistant_with_calls(calls), calls
diff --git a/overbae/modal/modal_sft_worker.py b/overbae/modal/modal_sft_worker.py
index 04f8e57d..23953a05 100644
--- a/overbae/modal/modal_sft_worker.py
+++ b/overbae/modal/modal_sft_worker.py
@@ -36,6 +36,7 @@ from pathlib import Path
import modal
+from modal_shared.chat_checkpoint import read_checkpoint, seal_checkpoint
from modal_shared.compute_usage import ComputeMeter
from modal_shared.decision_artifact import read_artifact, seal_artifact
from modal_shared.decisions import DECISION_OBJECTIVES
@@ -115,7 +116,7 @@ def _run_training(run_id: str, env: dict[str, str], *, gpu_type="H100", gpu_coun
run_dir.mkdir(parents=True, exist_ok=True)
final_dir = run_dir / "final"
native = env.get("TRAINING_OBJECTIVE") in DECISION_OBJECTIVES
- candidate_dir = run_dir / "candidate" if native else final_dir
+ candidate_dir = run_dir / "candidate"
result = {
"run_id": run_id,
"status": "succeeded",
@@ -126,11 +127,15 @@ def _run_training(run_id: str, env: dict[str, str], *, gpu_type="H100", gpu_coun
usage_path = run_dir / "compute-usage.json"
previous_usage = json.loads(usage_path.read_text()) if usage_path.exists() else []
- if native and final_dir.exists():
- result["artifact_identity"] = read_artifact(final_dir)["identity"]
+ if final_dir.exists():
+ checkpoint = read_artifact(final_dir) if native else read_checkpoint(final_dir)
+ result["artifact_identity"] = checkpoint["identity"]
_write_meta(run_dir, status="succeeded", finished_at=time.time())
sft_vol.commit()
return result
+ # A failed process may leave shards behind. A new attempt publishes only its own files.
+ if candidate_dir.exists():
+ shutil.rmtree(candidate_dir)
weights_vol.reload()
record_heartbeat(run_dir, new_attempt=True)
record_stage(run_dir, "staging_training_files")
@@ -210,7 +215,9 @@ def _run_training(run_id: str, env: dict[str, str], *, gpu_type="H100", gpu_coun
if native:
report = json.loads((run_dir / "decision-reload-verification.json").read_text())
result["artifact_identity"] = seal_artifact(candidate_dir, report)["identity"]
- candidate_dir.rename(final_dir)
+ else:
+ result["artifact_identity"] = seal_checkpoint(candidate_dir)["identity"]
+ candidate_dir.rename(final_dir)
status = "succeeded"
except Exception:
if local_log.exists():
@@ -332,9 +339,16 @@ def get_progress(run_id: str) -> dict:
else:
out["metrics"] = []
final_dir = run_dir / "final"
- out["has_final_checkpoint"] = final_dir.is_dir() and any(final_dir.iterdir())
+ out["has_final_checkpoint"] = False
+ if (final_dir / "checkpoint.json").is_file():
+ try:
+ read_checkpoint(final_dir)
+ out["has_final_checkpoint"] = True
+ except (OSError, ValueError, KeyError):
+ logging.getLogger(__name__).warning("Invalid final checkpoint for %s", run_id)
if (final_dir / "artifact.json").is_file():
artifact = read_artifact(final_dir)
+ out["has_final_checkpoint"] = True
out["native_artifact"] = {
"artifact_identity": artifact["identity"],
"reload_verification": artifact["verification"],
diff --git a/overbae/models/optimizer.py b/overbae/models/optimizer.py
index f926c3a7..b2786ade 100644
--- a/overbae/models/optimizer.py
+++ b/overbae/models/optimizer.py
@@ -935,22 +935,21 @@ def on_candidate_eval_finished(run) -> None:
)
if candidate is None:
return
- experiment = candidate.experiment
- if experiment.status in experiment.TERMINAL:
- return
- experiment._fold_candidate_eval_scores(candidate)
- iteration_order = candidate.iteration.order
-
with transaction.atomic():
- experiment.refresh_from_db()
+ experiment = OptimizerExperiment.objects.select_for_update().get(pk=candidate.experiment_id)
+ if experiment.status in experiment.TERMINAL:
+ return
pending = dict(experiment.state.get("eval_pending", {}))
- pending.pop(str(candidate.id), None)
+ if str(candidate.id) not in pending:
+ return
+ experiment._fold_candidate_eval_scores(candidate)
+ iteration_order = candidate.iteration.order
+ pending.pop(str(candidate.id))
experiment.state["eval_pending"] = pending
experiment.save(update_fields=["state", "updated_at"])
-
- if not experiment._iteration_eval_pending(iteration_order):
- experiment.on_iteration_eval_complete(iteration_order)
- run_experiment_advance.delay(str(experiment.id))
+ if not experiment._iteration_eval_pending(iteration_order):
+ experiment.on_iteration_eval_complete(iteration_order)
+ transaction.on_commit(lambda: run_experiment_advance.delay(str(experiment.id)))
@shared_task(name="overbae.models.optimizer.run_experiment_advance")
diff --git a/overbae/services/decision_performance.py b/overbae/services/decision_performance.py
index 2c997e9e..1785fb34 100644
--- a/overbae/services/decision_performance.py
+++ b/overbae/services/decision_performance.py
@@ -455,7 +455,7 @@ def advance(run_id):
if r.position > 0
and r.latency_ms is not None
and first_instance
- and r.response.get("worker_instance") == first_instance
+ and (r.response or {}).get("worker_instance") == first_instance
]
job = (
FinetuningJob.objects.filter(
@@ -471,7 +471,7 @@ def advance(run_id):
float(job.cost_usd) if job and job.cost_usd is not None else 0 if not job else None
)
compute = (
- estimate_usage([r.response.get("compute_usage", {}) for r in requests])
+ estimate_usage([(r.response or {}).get("compute_usage", {}) for r in requests])
if native
else None
)
@@ -503,7 +503,7 @@ def advance(run_id):
{
r.response["worker_instance"]
for r in valid
- if r.response.get("worker_instance")
+ if (r.response or {}).get("worker_instance")
}
),
"recorded_cost_usd": sum(r.usage.get("response_cost") or 0 for r in requests),
diff --git a/overbae/services/decision_providers.py b/overbae/services/decision_providers.py
index 2b4b9cb3..7e988cb2 100644
--- a/overbae/services/decision_providers.py
+++ b/overbae/services/decision_providers.py
@@ -40,8 +40,7 @@ def recover_request(record):
elif (
record.state == "submission_unknown"
and record.attempts
- and record.attempts[-1].get("error")
- in {"submission_unknown", "capacity_timeout", "capacity_unavailable"}
+ and record.attempts[-1].get("error") in {"capacity_timeout", "capacity_unavailable"}
):
# Only a completed transport attempt can be repeated. A bare submission
# intent may still have a live owner and is not evidence of a timeout.
@@ -399,11 +398,10 @@ def external_step(plan, role, participant):
complete_response(record, request, participant)
except decisions.DecisionError as exc:
code = exc.stats.get("status_code")
- retryable = (
+ retryable = exc.reason != "submission_unknown" and (
code == 429
or (isinstance(code, int) and 500 <= code < 600)
- or exc.reason
- in {"submission_unknown", "capacity_timeout", "capacity_unavailable"}
+ or exc.reason in {"capacity_timeout", "capacity_unavailable"}
)
record.attempts[-1].update(
error=exc.reason,
@@ -414,7 +412,9 @@ def external_step(plan, role, participant):
finished_at=timezone.now().isoformat(),
)
record.state = (
- "retryable"
+ "submission_unknown"
+ if exc.reason == "submission_unknown"
+ else "retryable"
if retryable and len(record.attempts) < 3
else "failed"
if retryable
diff --git a/overbae/services/dedicated.py b/overbae/services/dedicated.py
index 18ba9e8c..cb8aeecd 100644
--- a/overbae/services/dedicated.py
+++ b/overbae/services/dedicated.py
@@ -225,7 +225,7 @@ def update(
def stop(row: DedicatedDeployment):
- if row.status in (DedicatedDeployment.Status.OFFLINE, DedicatedDeployment.Status.FAILED):
+ if row.status == DedicatedDeployment.Status.OFFLINE:
return row
DedicatedDeployment.objects.filter(pk=row.pk).update(
status=DedicatedDeployment.Status.SHUTTING_DOWN,
@@ -274,10 +274,8 @@ def _broke(row: DedicatedDeployment) -> bool:
def _fail(row: DedicatedDeployment, message: str, now) -> None:
_meter(row, now)
- row.status = DedicatedDeployment.Status.FAILED
+ row.status = DedicatedDeployment.Status.SHUTTING_DOWN
row.error_message = message
- row.stopped_at = now
- row.running_replicas = 0
def advance(deployment_id: str) -> None:
@@ -331,7 +329,11 @@ def advance(deployment_id: str) -> None:
row.running_replicas = count
_meter(row, now)
if stopping and count == 0:
- row.status = DedicatedDeployment.Status.OFFLINE
+ row.status = (
+ DedicatedDeployment.Status.FAILED
+ if row.error_message
+ else DedicatedDeployment.Status.OFFLINE
+ )
row.stopped_at = now
elif not stopping and _broke(row):
row.status = DedicatedDeployment.Status.SHUTTING_DOWN
diff --git a/overbae/services/finetuning_eval.py b/overbae/services/finetuning_eval.py
index ac34fabd..e6ddd730 100644
--- a/overbae/services/finetuning_eval.py
+++ b/overbae/services/finetuning_eval.py
@@ -522,7 +522,7 @@ def baseline_needs_base_deploy(job) -> bool:
return target is not None and target.kind == "base_deploy"
-def _sibling_baseline_eval(job, *, model_id: str, kind: str):
+def _sibling_baseline_eval(job, *, model_id: str, kind: str, cell, matrix, params):
"""Reuse a group-mate's baseline EvalRun when it scores the same target.
Wizard multi-model launches share ``group_id`` + eval set/dataset and one
@@ -534,7 +534,7 @@ def _sibling_baseline_eval(job, *, model_id: str, kind: str):
gid = getattr(job, "group_id", None)
if not gid or not model_id or not job.eval_dataset_id or not job.eval_set_id:
return None
- return (
+ candidates = (
FinetuningJobEval.objects.filter(
job__group_id=gid,
job__eval_dataset_id=job.eval_dataset_id,
@@ -545,6 +545,9 @@ def _sibling_baseline_eval(job, *, model_id: str, kind: str):
eval_run_id__isnull=False,
eval_run__max_items=0,
eval_run__sampling=1.0,
+ eval_run__cell=cell,
+ eval_run__matrix=matrix,
+ eval_run__judge_model=job.eval_judge_model,
)
.exclude(job_id=job.id)
.exclude(
@@ -556,8 +559,14 @@ def _sibling_baseline_eval(job, *, model_id: str, kind: str):
)
.select_related("eval_run")
.order_by("created_at")
- .first()
)
+ for candidate in candidates:
+ effective = {
+ key: value for key, value in (candidate.eval_run.params or {}).items() if key != "label"
+ }
+ if effective == params:
+ return candidate
+ return None
def _attach_shared_baseline(job, shared):
@@ -818,11 +827,6 @@ def _launch_eval(
model_id=model_id,
error_message="The eval set has no enabled eval matrix rows.",
)
- if kind in (FinetuningJobEval.Kind.BASELINE, FinetuningJobEval.Kind.COMPARATOR):
- shared = _sibling_baseline_eval(job, model_id=model_id, kind=kind)
- if shared is not None:
- return _attach_shared_baseline(job, shared)
-
from overbae.services.datasets import use as dataset_use
# Same pin the eval-run API applies: generate scoring reads ``run.cell``.
@@ -850,6 +854,12 @@ def _launch_eval(
if job.capability_id
else {}
)
+ if kind in (FinetuningJobEval.Kind.BASELINE, FinetuningJobEval.Kind.COMPARATOR):
+ shared = _sibling_baseline_eval(
+ job, model_id=model_id, kind=kind, cell=cell, matrix=matrix, params=params
+ )
+ if shared is not None:
+ return _attach_shared_baseline(job, shared)
params["label"] = label[:255]
try:
run = runs.create_run(
diff --git a/overbae/services/inference_requests.py b/overbae/services/inference_requests.py
index ebc9b868..12fe290a 100644
--- a/overbae/services/inference_requests.py
+++ b/overbae/services/inference_requests.py
@@ -197,6 +197,9 @@ def advance(request_id):
elif request.state == "queued" and request.payload.get("dedicated_id"):
from overbae.services.dedicated import complete_request
+ # Persist the intent before HTTP. Its acknowledgement cannot be recovered
+ # from the Modal request store, so an expired owner must never replay it.
+ owned.update(state="submitting", claim_until=request.deadline, updated_at=now)
try:
result = complete_request(request.payload)
result = {
@@ -219,9 +222,8 @@ def advance(request_id):
except Exception:
logger.warning("Dedicated inference failed for %s", request.pk, exc_info=False)
changes = {
- "state": "failed",
- "error_code": "provider_failed",
- "completed_at": now,
+ "state": "submission_unknown",
+ "error_code": "acknowledgement_unknown",
}
elif request.state == "queued":
owned.update(state="submitting", updated_at=now)
@@ -232,6 +234,8 @@ def advance(request_id):
changes = {"remote_id": handle, "state": "running"}
except Exception:
changes = {"state": "submission_unknown", "error_code": "acknowledgement_unknown"}
+ elif request.payload.get("dedicated_id") and not request.remote_id:
+ changes = {"state": "submission_unknown", "error_code": "acknowledgement_unknown"}
elif not request.remote_id:
handle = recover(request)
changes = (
diff --git a/overbae/services/mcp/tools_model_catalog.py b/overbae/services/mcp/tools_model_catalog.py
index 2fff8ebc..bbf66e34 100644
--- a/overbae/services/mcp/tools_model_catalog.py
+++ b/overbae/services/mcp/tools_model_catalog.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+from asgiref.sync import sync_to_async
+
from overbae.services.finetuning_catalog import fetch_finetuning_model_catalog
from overbae.services.mcp.contracts.model_catalog import (
GetModelCatalogInput,
@@ -9,6 +11,7 @@ from overbae.services.mcp.contracts.model_catalog import (
)
+@sync_to_async(thread_sensitive=True)
def _get_model_catalog(payload, _context):
catalog = fetch_finetuning_model_catalog(
has_tool_calling=payload.has_tool_calling,
diff --git a/overbae/services/sft_assets/gpt_oss_templates/gpt_oss_unsloth_training.jinja b/overbae/services/sft_assets/gpt_oss_templates/gpt_oss_unsloth_training.jinja
index 57b9fdc7..f17e71c5 100644
--- a/overbae/services/sft_assets/gpt_oss_templates/gpt_oss_unsloth_training.jinja
+++ b/overbae/services/sft_assets/gpt_oss_templates/gpt_oss_unsloth_training.jinja
@@ -261,8 +261,11 @@
{#- At this point only assistant/user/tool messages should remain #}
{%- if message.role == 'assistant' -%}
{%- generation %}
- {%- if "tool_calls" in message %}
- {#- We assume max 1 tool call per message, and so we infer the tool call name #}
+ {%- if message.tool_calls %}
+ {%- if message.tool_calls|length > 1 %}
+ {{- raise_exception("GPT-OSS training requires one tool call per assistant message; parallel tool calls cannot be represented.") }}
+ {%- endif %}
+ {#- Tool replies carry the most recent assistant tool call name. #}
{#- in "tool" messages from the most recent assistant tool call name #}
{%- set tool_call = message.tool_calls[0] %}
{%- if tool_call.function %}
diff --git a/tests/load/isolation.py b/tests/load/isolation.py
index 560eb645..5d8f033e 100644
--- a/tests/load/isolation.py
+++ b/tests/load/isolation.py
@@ -12,7 +12,7 @@ from overbae.models import APIToken, Dataset, DatasetPipelineRun
from overbae.services.datasets import pipeline_runner
from tests.workshop_script_fixtures import identity_script, retained_package, script_step
-pytestmark = pytest.mark.django_db(transaction=True)
+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("capacity")]
def test_slow_project_cannot_occupy_all_interactive_workers(live_api, profile_workers):
diff --git a/tests/load/landing.py b/tests/load/landing.py
index 1fd3989e..d1b3836c 100644
--- a/tests/load/landing.py
+++ b/tests/load/landing.py
@@ -13,7 +13,7 @@ from factories import make_project, make_user
from overbae.models import APIToken, Dataset
from tests.load.processes import landing_workers
-pytestmark = pytest.mark.django_db(transaction=True)
+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("capacity")]
def test_noisy_import_burst_leaves_a_landing_worker_for_another_project(
diff --git a/tests/load/landing_burst.py b/tests/load/landing_burst.py
index e3bccd98..dfc2f706 100644
--- a/tests/load/landing_burst.py
+++ b/tests/load/landing_burst.py
@@ -13,7 +13,7 @@ from factories import make_project, make_user
from overbae.models import APIToken, Dataset, DatasetLandingWork
from tests.load.processes import landing_workers
-pytestmark = pytest.mark.django_db(transaction=True)
+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("capacity")]
def test_thousand_queued_imports_do_not_flood_the_broker_or_delay_another_project(
diff --git a/tests/load/mixed.py b/tests/load/mixed.py
index 71d4f3f9..08335aa4 100644
--- a/tests/load/mixed.py
+++ b/tests/load/mixed.py
@@ -19,9 +19,9 @@ from celery.contrib.testing.worker import start_worker
from celery.signals import before_task_publish, task_postrun
from django.db import close_old_connections, connection
from factories import make_capability, make_project, make_user
+from journeys.otlp import Trace
from journeys.stack import TaskLedger
from journeys.surfaces import McpSurface
-from journeys.test_live_scoring import Trace
from overbae.celery import app
from overbae.models import (
@@ -42,7 +42,7 @@ from overbae.tasks.training_preparation import reconcile as reconcile_preparatio
from tests.load.processes import ProcessWorker, drain_process_results
from tests.workshop_script_fixtures import identity_script, retained_package
-pytestmark = pytest.mark.django_db(transaction=True)
+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("capacity")]
def percentiles(values):
diff --git a/tests/load/query_capacity.py b/tests/load/query_capacity.py
index 4938a47e..4e499d26 100644
--- a/tests/load/query_capacity.py
+++ b/tests/load/query_capacity.py
@@ -11,7 +11,7 @@ from overbae.services.datasets import land
from tests.journeys.surfaces import McpSurface
from tests.load.processes import ProcessAPI
-pytestmark = pytest.mark.django_db(transaction=True)
+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("capacity")]
def test_cpu_heavy_queries_cannot_take_another_projects_sql_capacity(settings, tmp_path):
diff --git a/tests/load/reads.py b/tests/load/reads.py
index d053166e..d4ab9658 100644
--- a/tests/load/reads.py
+++ b/tests/load/reads.py
@@ -10,7 +10,7 @@ from factories import make_project, make_user
from overbae.models import APIToken
-pytestmark = pytest.mark.django_db(transaction=True)
+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("capacity")]
def test_concurrent_read_sessions_preserve_quiet_project_response(process_api, tmp_path):
diff --git a/tests/load/recovery.py b/tests/load/recovery.py
index 568eae18..ed9ee0e8 100644
--- a/tests/load/recovery.py
+++ b/tests/load/recovery.py
@@ -13,7 +13,7 @@ from overbae.services.datasets import land, pipeline_runner, workbench
from tests.load.processes import ProcessWorker
from tests.workshop_script_fixtures import identity_script, retained_package, script_step
-pytestmark = pytest.mark.django_db(transaction=True)
+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("capacity")]
def wait_until(condition, timeout=30):
diff --git a/tests/load/transfers.py b/tests/load/transfers.py
index 1f20d88b..e5a38a53 100644
--- a/tests/load/transfers.py
+++ b/tests/load/transfers.py
@@ -7,7 +7,7 @@ from factories import make_project, make_user
from overbae.models import APIToken
from overbae.services.datasets import files
-pytestmark = pytest.mark.django_db(transaction=True)
+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("capacity")]
def test_interrupted_chunk_sequence_resumes_without_duplicating_bytes(live_api):
diff --git a/tests/test_chat_checkpoint.py b/tests/test_chat_checkpoint.py
new file mode 100644
index 00000000..aa0e99a3
--- /dev/null
+++ b/tests/test_chat_checkpoint.py
@@ -0,0 +1,29 @@
+import json
+
+import pytest
+
+from modal_shared.chat_checkpoint import read_checkpoint, seal_checkpoint
+
+pytestmark = pytest.mark.covers("model-runtime")
+
+
[email protected]("adapter", [False, True])
+def test_checkpoint_publication_requires_all_shards_and_tokenizer(tmp_path, adapter):
+ config = "adapter_config.json" if adapter else "config.json"
+ prefix = "adapter_model" if adapter else "model"
+ (tmp_path / config).write_text("{}")
+ (tmp_path / "tokenizer_config.json").write_text("{}")
+ (tmp_path / "tokenizer.json").write_text("{}")
+ (tmp_path / f"{prefix}.safetensors.index.json").write_text(
+ json.dumps({"weight_map": {"a": "first.safetensors", "b": "second.safetensors"}})
+ )
+ (tmp_path / "first.safetensors").write_bytes(b"first weights")
+ with pytest.raises(ValueError, match="regular immutable file"):
+ seal_checkpoint(tmp_path)
+ assert not (tmp_path / "checkpoint.json").exists()
+ (tmp_path / "second.safetensors").write_bytes(b"second weights")
+ manifest = seal_checkpoint(tmp_path)
+ assert read_checkpoint(tmp_path)["identity"] == manifest["identity"]
+ (tmp_path / "second.safetensors").write_bytes(b"truncated")
+ with pytest.raises(ValueError, match="changed"):
+ read_checkpoint(tmp_path)
diff --git a/tests/test_decision_performance_workflow.py b/tests/test_decision_performance_workflow.py
index 3e7a00c1..7dbbc82a 100644
--- a/tests/test_decision_performance_workflow.py
+++ b/tests/test_decision_performance_workflow.py
@@ -131,7 +131,8 @@ def test_native_performance_rejects_changed_model_and_runtime():
)
-def test_native_measurement_collects_saved_calls_and_reports_observer_latency_unknown():
[email protected]("failed", [False, True])
+def test_native_measurement_collects_saved_calls_and_reports_observer_latency_unknown(failed):
plan, _, decision = fixture()
native_evaluation.seal_suite(plan, "final")
@@ -171,7 +172,10 @@ def test_native_measurement_collects_saved_calls_and_reports_observer_latency_un
"worker_instance": "worker-1",
}
call = Mock(object_id="fc-existing")
- call.get.side_effect = [TimeoutError("observer timeout"), reply]
+ call.get.side_effect = [
+ TimeoutError("observer timeout"),
+ RuntimeError("worker failed") if failed else reply,
+ ]
worker = Mock()
worker.predict.spawn.side_effect = AssertionError("never repeat a submitted call")
with (
@@ -190,8 +194,8 @@ def test_native_measurement_collects_saved_calls_and_reports_observer_latency_un
run.refresh_from_db()
assert run.state == "completed"
measurement = run.results["participants"]["base"]
- assert measurement["valid_decisions"] == 1
- assert measurement["unmeasured_latency_requests"] == 1
+ assert measurement["valid_decisions"] == (0 if failed else 1)
+ assert measurement["unmeasured_latency_requests"] == (0 if failed else 1)
assert measurement["latency_ms"]["p50"] is None
assert measurement["marginal_recorded_usd_per_valid_decision"] is None
assert measurement["amortized_recorded_component_usd_per_decision"] is None
diff --git a/tests/test_dedicated_deployment.py b/tests/test_dedicated_deployment.py
index 81092e72..21e85f1e 100644
--- a/tests/test_dedicated_deployment.py
+++ b/tests/test_dedicated_deployment.py
@@ -3,11 +3,15 @@
from __future__ import annotations
import json
+import threading
import uuid
+from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
+import httpx
import pytest
from conftest import drain_stream
+from django.db import close_old_connections
from django.utils import timezone
from rest_framework.test import APIClient
from rest_framework_simplejwt.tokens import RefreshToken
@@ -16,7 +20,7 @@ from overbae.core.errors import InputValidationError
from overbae.models import BillingTelemetry, DedicatedDeployment, InferenceCall, Project, User
from overbae.models.billing import BillingService
from overbae.models.inference import DeployedModel
-from overbae.services import dedicated
+from overbae.services import dedicated, inference_requests
from overbae.services.provider_pricing import refresh_rates
from tests.fakes.modal import open_chat_tunnel
@@ -309,3 +313,120 @@ def test_dedicated_list_returns_the_latest_row_for_each_model():
assert listed["gpu_type"] == "H100"
assert listed["model_name"] == first.model_id
assert listed["model_id"] == f"dedicated/{first.model_id}"
+
+
+def test_failed_warmup_releases_the_remote_floor_before_becoming_terminal(fake_modal):
+ refresh_rates()
+ user = _user()
+ project = Project.objects.create(name="Failure cleanup")
+ deployed = _ready(project)
+ fake_modal.deploy(
+ "overmind-dedicated", "H100_vllm_dedicated.infer", lambda **kwargs: {"status": 503}
+ )
+ row = dedicated.start(deployed, user, gpu_type="H100")
+ dedicated.advance(str(row.pk))
+ dedicated.advance(str(row.pk))
+ row.refresh_from_db()
+ assert row.status == "shutting_down"
+ assert row.stopped_at is None
+ assert dedicated.due().filter(pk=row.pk).exists() is False # Next observation is scheduled.
+ fake_modal.worker_stats = {"num_total_runners": 1}
+ dedicated.advance(str(row.pk))
+ row.refresh_from_db()
+ assert row.status == "shutting_down"
+ assert row.running_replicas == 1
+ assert any(
+ kind == "autoscaler" and kwargs.get("min_containers") == 0
+ for kind, _, _, kwargs in fake_modal.log
+ )
+ fake_modal.worker_stats = {"num_total_runners": 0}
+ dedicated.advance(str(row.pk))
+ row.refresh_from_db()
+ assert row.status == "failed"
+ assert row.stopped_at is not None
+
+
[email protected]_db(transaction=True)
[email protected]("work-once")
+def test_dedicated_request_holds_its_claim_while_the_provider_runs(fake_modal, scripted):
+ user = _user()
+ project = Project.objects.create(name="Dedicated request")
+ model = _ready(project)
+ refresh_rates()
+ row = dedicated.start(model, user, gpu_type="H100")
+ row.status = "online"
+ row.save(update_fields=["status"])
+ fake_modal.deploy(
+ "overmind-dedicated",
+ "H100_vllm_dedicated.direct_url",
+ lambda **kwargs: "https://audit-dedicated.test",
+ )
+ started, release = threading.Event(), threading.Event()
+
+ def respond(call):
+ started.set()
+ assert release.wait(10)
+ result = _ok()
+ return result["status"], result["headers"], result["body"]
+
+ provider = scripted("https://audit-dedicated.test").then(respond)
+ request = inference_requests.submit(
+ model,
+ user,
+ "slow",
+ {"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 32},
+ dedicated=row,
+ )
+
+ def advance():
+ try:
+ inference_requests.advance(request.pk)
+ finally:
+ close_old_connections()
+
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ future = executor.submit(advance)
+ try:
+ assert started.wait(10)
+ request.refresh_from_db()
+ assert request.state == "submitting"
+ assert request.claim_until >= timezone.now() + timedelta(seconds=300)
+ inference_requests.advance(request.pk)
+ assert len(provider.calls) == 1
+ finally:
+ release.set()
+ future.result(timeout=10)
+ request.refresh_from_db()
+ assert request.state == "succeeded"
+ assert request.result["content"] == "hi"
+
+
[email protected]("work-once")
+def test_dedicated_unknown_acknowledgement_is_never_replayed(fake_modal, scripted):
+ user = _user()
+ project = Project.objects.create(name="Unknown dedicated acknowledgement")
+ model = _ready(project)
+ refresh_rates()
+ row = dedicated.start(model, user, gpu_type="H100")
+ row.status = "online"
+ row.save(update_fields=["status"])
+ fake_modal.deploy(
+ "overmind-dedicated",
+ "H100_vllm_dedicated.direct_url",
+ lambda **kwargs: "https://audit-dedicated.test",
+ )
+ provider = scripted("https://audit-dedicated.test").fail(
+ httpx.ReadTimeout("acknowledgement lost")
+ )
+ request = inference_requests.submit(
+ model,
+ user,
+ "unknown",
+ {"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 32},
+ dedicated=row,
+ )
+ inference_requests.advance(request.pk)
+ inference_requests.advance(request.pk)
+ request.refresh_from_db()
+ assert request.state == "submission_unknown"
+ assert len(provider.calls) == 1
diff --git a/tests/test_eval_context_warnings.py b/tests/test_eval_context_warnings.py
index 06cb17aa..743f106e 100644
--- a/tests/test_eval_context_warnings.py
+++ b/tests/test_eval_context_warnings.py
@@ -183,3 +183,42 @@ def test_exhausted_judge_does_not_retry_without_known_extra_capacity(fake_llm, l
assert outcome.parsed is None
assert outcome.stats["error_kind"] == "output_limit"
assert "output token limit" in funnel.failure_reason(outcome)
+
+
+def test_replay_preserves_text_and_executes_tools_from_the_same_message(fake_llm):
+ calls = [
+ {
+ "id": "call-1",
+ "type": "function",
+ "function": {"name": "lookup", "arguments": '{"id":1}'},
+ }
+ ]
+ replies = iter(
+ [{"content": "I will check the record.", "tool_calls": calls}, "The record is active."]
+ )
+ fake_llm.on(lambda r: r.model == "openai/gpt-4.1", lambda r: next(replies))
+ result = replay.run_capability(
+ input_messages=[{"role": "user", "content": "Check record 1"}],
+ tool_provider=replay.ReplayToolProvider(
+ recorded_calls=[{"name": "lookup", "arguments": {"id": 1}, "result": "active"}],
+ tool_defs=[
+ {
+ "name": "lookup",
+ "parameters": {"type": "object", "properties": {"id": {"type": "integer"}}},
+ }
+ ],
+ ),
+ model="gpt-4.1",
+ )
+ sent = _sent(fake_llm, "openai/gpt-4.1")
+ assert len(sent) == 2
+ assistant = next(
+ message for message in sent[1].body["messages"] if message["role"] == "assistant"
+ )
+ assert assistant["content"] == "I will check the record."
+ assert assistant["tool_calls"][0]["id"] == "call-1"
+ assert any(
+ message["role"] == "tool" and "active" in message["content"]
+ for message in sent[1].body["messages"]
+ )
+ assert result.output_messages[-1]["content"] == "The record is active."
diff --git a/tests/test_finetuning_eval_schedule.py b/tests/test_finetuning_eval_schedule.py
index 72802c0e..49c2c198 100644
--- a/tests/test_finetuning_eval_schedule.py
+++ b/tests/test_finetuning_eval_schedule.py
@@ -1,3 +1,4 @@
+import shutil
from itertools import product
from types import SimpleNamespace
from unittest.mock import Mock
@@ -21,6 +22,8 @@ from overbae.models import (
User,
)
from overbae.services import deployment, finetuning_eval, training_preparation, training_release
+from overbae.services.datasets import paths as dataset_paths
+from overbae.services.datasets import rows as dataset_rows
from overbae.services.finetuning_eval import (
baseline_needs_base_deploy,
reset_before_evals_for_retry,
@@ -819,3 +822,53 @@ def test_disabled_evaluations_do_not_require_evaluation_inputs(job, field):
serializer = serializer_for(job, **dict.fromkeys(FIELDS, False))
serializer.initial_data.pop(field)
assert serializer.is_valid(), serializer.errors
+
+
[email protected]("changed", [None, "cell", "matrix", "prompt"])
+def test_shared_baseline_requires_identical_pinned_inputs(job, changed):
+ job.group_id = job.id
+ job.eval_judge_model = "gpt-5.6-luna"
+ job.save(update_fields=["group_id", "eval_judge_model"])
+ tick_job_evals(job)
+ baseline = job.job_evals.get(kind="baseline").eval_run_id
+ sibling = FinetuningJob.objects.create(
+ project=job.project,
+ capability=job.capability,
+ dataset=job.dataset,
+ cell=job.cell,
+ eval_dataset=job.eval_dataset,
+ eval_cell=job.eval_cell,
+ eval_set=job.eval_set,
+ group_id=job.group_id,
+ base_model=job.base_model,
+ provider=job.provider,
+ baseline_model=job.baseline_model,
+ eval_incumbent_before=True,
+ eval_model_before=False,
+ status=job.status,
+ eval_judge_model=job.eval_judge_model,
+ )
+ if changed == "cell":
+ cell = job.eval_cell
+ source = dataset_rows.frame_path(cell)
+ cell.pk = None
+ cell.position += 1
+ cell.save()
+ destination = dataset_paths.cell_path(cell.dataset_id, cell.id)
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source, destination)
+ sibling.eval_cell = cell
+ sibling.save(update_fields=["eval_cell"])
+ elif changed == "matrix":
+ matrix = job.eval_set.rows.first()
+ matrix.name = "Changed rubric"
+ matrix.save(update_fields=["name"])
+ elif changed == "prompt":
+ baseline_run = job.job_evals.get(kind="baseline").eval_run
+ baseline_run.params = {
+ **baseline_run.params,
+ "system_prompt": "Different pinned instructions",
+ }
+ baseline_run.save(update_fields=["params"])
+ tick_job_evals(sibling)
+ assert (sibling.job_evals.get(kind="baseline").eval_run_id == baseline) is (changed is None)
diff --git a/tests/test_mcp_catalog_concurrency.py b/tests/test_mcp_catalog_concurrency.py
new file mode 100644
index 00000000..ca5cebf1
--- /dev/null
+++ b/tests/test_mcp_catalog_concurrency.py
@@ -0,0 +1,47 @@
+import asyncio
+import json
+import threading
+
+import pytest
+from django.core.cache import cache
+
+from overbae.models import APIToken, Project, User
+from overbae.services.mcp.catalog import CATALOG
+from overbae.services.mcp.context import MCPContext
+
+pytestmark = pytest.mark.covers("capacity")
+
+
+def test_uncached_catalog_fetch_leaves_the_event_loop_available(scripted):
+ cache.clear()
+ started, release = threading.Event(), threading.Event()
+ observed = []
+
+ def response(call):
+ started.set()
+ observed.append(release.wait(3))
+ return 200, {"content-type": "application/json"}, json.dumps({"data": []}).encode()
+
+ scripted("https://openrouter.ai/api/v1/models").then(response)
+ context = MCPContext(
+ user=User(email="[email protected]"),
+ token=APIToken(scope={"permission": ["read"]}),
+ project=Project(name="Catalog"),
+ )
+
+ async def check():
+ async def heartbeat():
+ assert await asyncio.to_thread(started.wait, 3)
+ release.set()
+
+ result, _ = await asyncio.gather(
+ CATALOG.call("get_model_catalog", {}, context), heartbeat()
+ )
+ assert not result.isError
+
+ try:
+ asyncio.run(check())
+ assert observed == [True]
+ finally:
+ release.set()
+ cache.clear()
diff --git a/tests/test_native_evaluation_recovery.py b/tests/test_native_evaluation_recovery.py
index f9011607..7c8c8770 100644
--- a/tests/test_native_evaluation_recovery.py
+++ b/tests/test_native_evaluation_recovery.py
@@ -95,10 +95,10 @@ def retry_due(plan, stage="final_external"):
plan.save()
-def test_transport_interruption_recovers_only_missing_prediction_and_finishes(evaluation, scripted):
+def test_explicit_rate_limit_retries_only_rejected_prediction_and_finishes(evaluation, scripted):
plan = evaluation
provider = scripted("https://openrouter.ai/api/v1/systemone")
- provider.fail(httpx.ReadTimeout("response lost")).reply(json_body=answer())
+ provider.reply(429).reply(json_body=answer())
native_evaluation.advance(plan.pk, stage="final_external")
plan.refresh_from_db()
assert plan.state == "running"
@@ -118,13 +118,13 @@ def test_transport_interruption_recovers_only_missing_prediction_and_finishes(ev
assert len(provider.calls) == 3
assert plan.requests.filter(state="completed").count() == 2
assert sorted(len(r.attempts) for r in plan.requests.all()) == [1, 2]
- assert plan.results["costs"]["external"]["unknown_api_attempts"] == 1
+ assert plan.results["costs"]["external"]["unknown_api_attempts"] == 0
assert plan.results["costs"]["external"]["recorded_evaluation_api_usd"] == pytest.approx(0.004)
def test_exhausted_recovery_completes_with_missing_coverage(evaluation, scripted):
plan = evaluation
- provider = scripted("https://openrouter.ai/api/v1/systemone").fail(httpx.ReadTimeout("offline"))
+ provider = scripted("https://openrouter.ai/api/v1/systemone").reply(429)
for _ in range(3):
native_evaluation.advance(plan.pk, stage="final_external")
retry_due(plan)
@@ -170,13 +170,13 @@ def test_partial_baseline_keeps_other_scores_and_only_pairs_available_rows(
)
plan.save()
provider = scripted("https://openrouter.ai/api/v1/systemone")
- provider.fail(httpx.ReadTimeout("offline"))
+ provider.reply(429)
if baseline_success:
provider.reply(json_body=answer())
else:
- provider.fail(httpx.ReadTimeout("offline"))
+ provider.reply(429)
native_evaluation.advance(plan.pk, stage="final_external")
- provider.fail(httpx.ReadTimeout("offline")).fail(httpx.ReadTimeout("offline"))
+ provider.reply(429).reply(429)
for _ in range(2):
retry_due(plan)
native_evaluation.advance(plan.pk, stage="final_external")
@@ -195,7 +195,7 @@ def test_partial_baseline_keeps_other_scores_and_only_pairs_available_rows(
assert len(provider.calls) == 8 - 2 * int(baseline_success)
-def test_saved_timeout_receipt_can_resume_without_repeating_successes(evaluation, scripted):
+def test_saved_timeout_receipt_resumes_other_inputs_without_replaying_unknown(evaluation, scripted):
plan = evaluation
source = native_evaluation.seal_suite(plan, "final")
request = next(native_evaluation.records(source))
@@ -222,7 +222,8 @@ def test_saved_timeout_receipt_can_resume_without_repeating_successes(evaluation
native_evaluation.advance(plan.pk, stage="final_external")
plan.refresh_from_db()
assert plan.calls["final_external"]["state"] == "completed"
- assert len(provider.calls) == 2
+ assert plan.requests.filter(state="submission_unknown").count() == 1
+ assert len(provider.calls) == 1
assert (
plan.requests.get(input_sha256=input_digest(request["decision"])).attempts[0]["usage"][
"response_cost"
@@ -388,7 +389,7 @@ def test_failed_input_does_not_skip_later_chunks(evaluation, scripted):
counts = evaluation.results["completion"]["coverage"]["final"]["external"]
assert counts["scored"] == 129
assert counts["missing_predictions"] == 1
- assert len(provider.calls) == 132
+ assert len(provider.calls) == 130
def test_exhausted_native_preparation_does_not_submit_dependent_work(evaluation, fake_modal):
@@ -421,7 +422,7 @@ def test_partial_export_keeps_external_responses_not_yet_in_monitor(evaluation,
def test_paused_retry_does_not_restart(evaluation, scripted):
- provider = scripted("https://openrouter.ai/api/v1/systemone").fail(httpx.ReadTimeout("offline"))
+ provider = scripted("https://openrouter.ai/api/v1/systemone").reply(429)
native_evaluation.advance(evaluation.pk, stage="final_external")
retry_due(evaluation)
native_evaluation.pause(evaluation)
@@ -436,9 +437,7 @@ def test_retry_does_not_block_an_independent_participant(evaluation, scripted):
)
plan.save()
provider = scripted("https://openrouter.ai/api/v1/systemone")
- provider.fail(httpx.ReadTimeout("offline")).fail(httpx.ReadTimeout("offline")).reply(
- json_body=answer()
- )
+ provider.reply(429).reply(429).reply(json_body=answer())
native_evaluation.advance(plan.pk, stage="final_external")
native_evaluation.advance(plan.pk, stage="final_other")
plan.refresh_from_db()
diff --git a/tests/test_optimizer_fsm.py b/tests/test_optimizer_fsm.py
index 781e6434..1ad031f2 100644
--- a/tests/test_optimizer_fsm.py
+++ b/tests/test_optimizer_fsm.py
@@ -3,11 +3,14 @@ parks for the client. Driven through the ledger, the eval chord and the tasks.""
from __future__ import annotations
+import threading
import uuid
+from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
import pytest
from conftest import frozen_dataset
+from django.db import close_old_connections
from django.urls import reverse
from factories import auth_client, make_matrix_row, make_project, make_user
@@ -15,6 +18,7 @@ from overbae.models import (
Capability,
EvalMatrix,
EvalRun,
+ EvalScore,
OptimizerCandidate,
OptimizerCommand,
OptimizerExperiment,
@@ -320,3 +324,49 @@ def test_optimize_capability_schedules_without_dispatch(monkeypatch):
assert experiment.status == S.SCHEDULED
assert experiment.entrypoint == "trigger"
assert dispatched == []
+
+
[email protected]_db(transaction=True)
+def test_concurrent_candidate_completions_keep_all_scores_and_clear_pending(monkeypatch):
+ exp = _experiment()
+ iteration = OptimizerIteration.objects.create(experiment=exp, order=1, status="evaluating")
+ candidates = []
+ for index, score in enumerate([0.2, 0.8]):
+ run = EvalRun.objects.create(
+ project=exp.project, name=f"Candidate {index}", status="completed", max_items=1
+ )
+ EvalScore.objects.create(
+ project=exp.project,
+ run=run,
+ source_type="dataset_row",
+ source_id=f"{run.pk}:0",
+ score=score,
+ )
+ candidates.append(
+ OptimizerCandidate.objects.create(
+ experiment=exp, iteration=iteration, candidate_index=index, eval_run=run
+ )
+ )
+ exp.state = {"eval_pending": {str(c.pk): str(c.eval_run_id) for c in candidates}}
+ exp.status = S.EVALUATING_CANDIDATE_OUTPUTS
+ exp.save()
+ dispatches = []
+ monkeypatch.setattr(run_experiment_advance, "delay", lambda *args: dispatches.append(args))
+ ready = threading.Barrier(2)
+
+ def finish(candidate):
+ try:
+ ready.wait(timeout=5)
+ on_candidate_eval_finished(candidate.eval_run)
+ finally:
+ close_old_connections()
+
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ list(executor.map(finish, candidates))
+ exp.refresh_from_db()
+ assert exp.state["eval_pending"] == {}
+ assert exp.status == S.EVALUATED_CANDIDATE_OUTPUTS
+ assert sorted(exp.scores["1"].values()) == [20, 80]
+ assert len(dispatches) == 1
+ on_candidate_eval_finished(candidates[0].eval_run)
+ assert len(dispatches) == 1
diff --git a/tests/test_serving_args.py b/tests/test_serving_args.py
index 342d0ab9..27d79717 100644
--- a/tests/test_serving_args.py
+++ b/tests/test_serving_args.py
@@ -368,6 +368,17 @@ def test_systemone_probabilities_follow_the_option_order() -> None:
assert probabilities_for(noul, {"noul": 0.75}) == [0.25, 0.75]
+def test_binary_serving_keeps_custom_false_and_true_criteria():
+ request = {"state": "state", "question": "Choose", "kind": "noul", "options": ["deny", "allow"]}
+ question = systemone_body(request, "decision")["questions"]["0"]
+ assert question["criteria"] == {"false": "deny", "true": "allow"}
+ request["options"] = ["allow", "deny"]
+ assert systemone_body(request, "decision")["questions"]["0"]["criteria"] == {
+ "false": "allow",
+ "true": "deny",
+ }
+
+
def test_nemotron_expert_lora_is_marked_3d() -> None:
from modal_shared.serving.nemotron_lora import mark
diff --git a/tests/test_sft_training_chat_template.py b/tests/test_sft_training_chat_template.py
index f74dd370..bd886f2f 100644
--- a/tests/test_sft_training_chat_template.py
+++ b/tests/test_sft_training_chat_template.py
@@ -80,6 +80,7 @@ def _generation_env():
lstrip_blocks=True,
)
env.globals["raise_exception"] = _raise
+ env.globals["strftime_now"] = lambda pattern: "2026-11-05"
return env
@@ -192,3 +193,28 @@ def test_unknown_template_is_left_alone() -> None:
tok = _Tok("{{ messages }}")
assert patch_known_training_template(tok) is False
assert tok.chat_template == "{{ messages }}"
+
+
[email protected]("count", [0, 1, 2])
+def test_gpt_oss_never_silently_drops_parallel_tool_calls(count):
+ template = _generation_env().from_string(
+ (_ASSETS / "gpt_oss_templates/gpt_oss_unsloth_training.jinja").read_text()
+ )
+ messages = [
+ {"role": "user", "content": "Look up both"},
+ {
+ "role": "assistant",
+ "content": "Looking up",
+ "tool_calls": [
+ {"function": {"name": f"lookup_{i}", "arguments": {}}} for i in range(count)
+ ],
+ },
+ ]
+ if count > 1:
+ with pytest.raises(ValueError, match="parallel tool calls"):
+ template.render(messages=messages, tools=None, add_generation_prompt=False)
+ else:
+ rendered = template.render(messages=messages, tools=None, add_generation_prompt=False)
+ assert "Looking up" in rendered
+ if count:
+ assert "functions.lookup_0" in rendered