The platform for continuously improving AI agents.
Finish the rebuild: tool-call probes, full cancellation, CLI experiments, save-time flow checks (#371)
Freyam Mehtad54634329a98
diff --git a/.agents/skills/backend-architecture/references/assistant.md b/.agents/skills/backend-architecture/references/assistant.mdindex 8d94d57e..4339ce2c 100644--- a/.agents/skills/backend-architecture/references/assistant.md+++ b/.agents/skills/backend-architecture/references/assistant.md@@ -4,7 +4,7 @@ The Console's assistant is a second author beside a customer's coding agent, and## Turn-- An experiment has one `AssistantThread` (`experiment.assistant_thread`; references/experiments.md; the `dataset` column is unused and goes in a later migration) 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.+- An experiment has one `AssistantThread` (`experiment.assistant_thread`; references/experiments.md) 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 that fails before it delivers its message leaves the message queued and does not wake itself: the next message starts the turn.- 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, 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 takes at least its first message. One that reaches `TURN_SECONDS` queues a `continue` input and ends; `turn.CONTINUES` (8) continues since a person last wrote bound unattended work, then it fails. Turns no person started (run ends, triggers, continues) run at most `turn.UNATTENDED_TURNS` (3) at once per project; a person's message queued anywhere in the thread never waits. A held-back thread logs a `waiting` status; a turn that ends, and `resume_lost_turns`, wake each thread whose newest event is that status (`turn.waiting`), so a thread whose turn failed since waits for a person. A deleted experiment's thread takes no notice and starts no turn.@@ -38,4 +38,4 @@ The Console's assistant is a second author beside a customer's coding agent, and## Live updates-The dataset page holds one stream, `GET /api/datasets/{id}/events/`. It carries signals only: `connected` with the dataset's `updated_at`, the `land_*` progress of its source, `dataset_changed`, `assistant` (the conversation changed: read `GET /api/assistant-threads/{id}/events/?after=N`) and `assistant.draft` (text a reply gained after position `at`, and the summaries of the calls being written). Postgres is the record; the draft key in Redis holds the reply so far for a page that opens in the middle. Members share one conversation: the thread names its `participants`, and the Console labels a teammate's message with it. `log.append` stores what jsonb refuses (a NUL character, a number that is not finite) as a replacement character and null.+The dataset page holds one stream, `GET /api/datasets/{id}/events/`. It carries signals only: `connected` with the dataset's `updated_at`, the `land_*` progress of its source and `dataset_changed`. The experiment page's stream, `GET /api/experiments/{id}/stream/`, carries the conversation's signals: `assistant` (the conversation changed: read `GET /api/assistant-threads/{id}/events/?after=N`) and `assistant.draft` (text a reply gained after position `at`, and the summaries of the calls being written). Postgres is the record; the draft key in Redis holds the reply so far for a page that opens in the middle. Members share one conversation: the thread names its `participants`, and the Console labels a teammate's message with it. `log.append` stores what jsonb refuses (a NUL character, a number that is not finite) as a replacement character and null.diff --git a/.agents/skills/backend-architecture/references/evaluation.md b/.agents/skills/backend-architecture/references/evaluation.mdindex 9a217a6e..e7c87611 100644--- a/.agents/skills/backend-architecture/references/evaluation.md+++ b/.agents/skills/backend-architecture/references/evaluation.md@@ -2,7 +2,7 @@## Runs-An `EvalRun` scores one target (`mode` `recorded` or `generate`) 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.+An `EvalRun` scores one target (`mode` `recorded` or `generate`) 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` and takes an optional project-scoped `request_key`: an identical retry returns the same group, a changed request conflicts; MCP `run_evaluation` uses the catalog mutation receipt. 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.- `create_run` pins `EvalRun.judge_context`: the Jev decision model, the explanation chain (the run's `judge_model` first) and the capability description as the fallback intent. Scoring reads only these; a relaunch keeps them.diff --git a/.agents/skills/backend-architecture/references/experiments.md b/.agents/skills/backend-architecture/references/experiments.mdindex 0b43b565..d526fd5f 100644--- a/.agents/skills/backend-architecture/references/experiments.md+++ b/.agents/skills/backend-architecture/references/experiments.md@@ -5,7 +5,7 @@ An experiment is a saved flow of stages with its own conversation. The Console,## Records- `Experiment` holds the name, objective and `version`, the newest revision's number. `records.revise` saves the next immutable `ExperimentRevision` only from `expected_version`: a save over a newer one is refused, so neither the user nor the agent overwrites the other's change unseen. The same request key returns the first save.-- The flow document (`document.py`) holds `parameters`, retained `outputs` and `nodes` with `inputs` bound as `stage.port`. `normalize` refuses an unknown kind or port, a binding between types, a loop, and a read of a Partition's `final` output by anything but one Qualify stage that nothing trains or selects after. `problems` lists what a run still needs; a saved revision may be unfinished. `apply` performs stage edits (`set`, `remove`, `parameters`, `outputs`).+- The flow document (`document.py`) holds `parameters`, retained `outputs` and `nodes` with `inputs` bound as `stage.port`. `normalize` refuses an unknown kind or port, a binding between types, a loop, a setting its kind's schema does not allow (unknown key, type, enum, range; null, blank text and `$parameter` pass), and a read of a final holdout by anything but one Qualify stage that nothing trains or selects after. A final holdout is a Partition's `final` output, or a Data stage that pins one: `records.revise` checks the saved cell and `runs.plan` the resolved one. `problems` lists what a run still needs, such as required settings; a saved revision may be unfinished. `apply` performs stage edits (`set`, `remove`, `parameters`, `outputs`).- `catalog.py` is the one stage catalogue: kinds, typed ports, settings as JSON Schema, and the platform tool each calls. The Console reads it from `GET /api/experiments/catalog/`; agents from `inspect_experiment(catalog=true)`.- `ExperimentEvent` is the sequenced log of revisions, runs, stage transitions and trigger fires. Every change publishes on `experiment:<id>`, which the page streams from `GET /api/experiments/{id}/stream/`, together with its conversation's `assistant` and `assistant.draft` events.diff --git a/.agents/skills/backend-architecture/references/serving.md b/.agents/skills/backend-architecture/references/serving.mdindex e093f406..68136fc2 100644--- a/.agents/skills/backend-architecture/references/serving.md+++ b/.agents/skills/backend-architecture/references/serving.md@@ -34,7 +34,7 @@ MCP `run_inference` and REST `POST /api/deployed-models/{id}/inference/` (chat o- `services/serving_context.py` sizes serving context from the pinned evaluation inputs, references and output headroom, independently of training `context_length`. Overflow warns; it never excludes a candidate.- `modal_shared/context_budget.py` reserves a positive output budget (default 8,192 tokens) and rejects prompt truncation. Requests never shrink silently to the remaining context; MCP returns `context_length_exceeded`.- Token-limited generations keep their finish reason and stop before tool execution or parsing.-- `services/inference_metrics.py` and `inference_live.py` serve metrics and worker state without invoking inference. Zero measured runners means asleep; unavailable counts stay unknown.+- `services/inference_metrics.py` and `inference_live.py` serve metrics and worker state without invoking inference. Measured runners decide warm or asleep before recent requests; zero means asleep. Unavailable counts stay unknown, and only then do warm-up and recent requests decide.## Native decision servingdiff --git a/.agents/skills/backend-architecture/references/training.md b/.agents/skills/backend-architecture/references/training.mdindex 897dd33f..ab9cb4a9 100644--- a/.agents/skills/backend-architecture/references/training.md+++ b/.agents/skills/backend-architecture/references/training.md@@ -35,10 +35,10 @@ The no-progress observer compares native stage, completed work, attempt and chec- `TrainingValidationRun` and `TrainingCheckpoint` keep failures, sample and artifact fingerprints, reload verification and evidence from cancelled runs.- Status observation ingests metrics without downloading examples. The per-job IO collector reads each sealed artifact once with checksum verification; reads (MCP `inspect_training_progress`, REST monitoring evidence) never invoke a worker. MCP evidence over 128 KiB fails explicitly; `field` JSON Pointers page exact values.-- Generation checks need agent-declared labels, exact matching, a JSON Schema or `json_fields` pointers. `json_fields` compares declared JSON Pointers with type- and precision-preserving equality and ordered arrays; per-field coverage and whole-example pass rates are separate. Missing references are unscorable; invalid or missing predictions fail. Generation never executes tools. Metered judges, challenge suites and declared-strata sampling are rejected as unsupported.-- Development-loss selection and early stopping are explicit opt-ins. Classification `facts.assessment` compares the same scored subset with its majority-label baseline during collection, never on reads, and triggers no training action. Compact MCP summaries keep the latest generation check even when newer checks have loss only.+- Generation checks need agent-declared labels, exact matching, a JSON Schema, `json_fields` pointers or `tool_calls`. `tool_calls` generates the first supervised turn that calls a tool and passes on the reference tool name with object arguments; a row whose reference call does not parse (Hermes, Llama or Mistral JSON, Qwen XML) is unscorable. `json_fields` compares declared JSON Pointers with type- and precision-preserving equality and ordered arrays; per-field coverage and whole-example pass rates are separate. Missing references are unscorable; invalid or missing predictions fail. Generation never executes tools. Metered judges, challenge suites and declared-strata sampling are rejected as unsupported.+- Development-loss selection, generation selection (best probe pass rate, probed at every check) and early stopping are explicit opt-ins. Classification `facts.assessment` compares the same scored subset with its majority-label baseline during collection, never on reads, and triggers no training action. Compact MCP summaries keep the latest generation check even when newer checks have loss only.- Optional PostHog events (`training_result_available`, `training_check_finished`, `training_checkpoint_available`) fire after commit and carry counts and timings, never examples, labels or paths. Analytics failure cannot fail training.-- `cancel_finetune` and REST record cancellation intent before provider requests.+- `cancel_finetune` and REST record cancellation intent before provider requests. Cancel also stops the job's preparation and its Modal call when no other live job waits on it, and a deployment still publishing the model; both end `cancelled`. A later request for the same preparation queues it again.## Native decision trainingdiff --git a/.agents/skills/data-workshop/SKILL.md b/.agents/skills/data-workshop/SKILL.mdindex f9938c96..ba52b6fb 100644--- a/.agents/skills/data-workshop/SKILL.md+++ b/.agents/skills/data-workshop/SKILL.md@@ -66,7 +66,7 @@ External results arrive inline (at most 2,000 rows or 4 MiB) or as a project-sco- Frames are Parquet at `MEDIA_ROOT/datasets/<dataset>/cells/<cell>.parquet`. Cell IDs bind versions; version labels are derived. Source identity is `source_row`, not display position.- Lineage lives in a key file beside each frame (`<cell>.keys.parquet`, `lineage.py`): every row's `source_row` and its contamination keys, its own and its parents'. Leakage counts, partitions and validation splits read it; key strings must stay byte-identical across releases. Frames written before key files carry lineage in `_overmind_provenance`, and their key file is derived from it on first read. Document rows keep page regions and extraction method in `_overmind_evidence`.-- A frame is measured once, in one pass (`measure.describe_frame`): format fit for SFT training, decision training and evaluation, the training stats, decision analytics, column null rates and examples, and the key file. A dataset's intent is train (with `train_format` sft or decision), eval, or pending; publication sets it from a declared final consumer when it is pending.+- A frame is measured once, in one pass (`measure.describe_frame`): format fit for SFT training, decision training and evaluation, the training stats, the analytics checks, column null rates and examples, and the key file. A dataset's intent is train (with `train_format` sft or decision), eval, or pending; publication sets it from a declared final consumer when it is pending.- A column becomes JSON when it mixes kinds, holds an integer outside signed 64-bit range, or mixes floats with an integer a float cannot represent exactly (`store.py`). Shared pandas readers must not coerce these values again.- `query_dataset` caps output at 100 rows and 32 KiB and returns `query_result_too_large` without clipping; a configurable ten-second deadline returns `query_timeout`. Redis admission bounds MCP SQL globally and per project; busy admission returns a retryable error with the cell and retry delay.- `overmind dataset export --source SHA256` downloads retained originals with byte verification.diff --git a/.agents/skills/mcp/SKILL.md b/.agents/skills/mcp/SKILL.mdindex 134326c0..0edf27c9 100644--- a/.agents/skills/mcp/SKILL.md+++ b/.agents/skills/mcp/SKILL.md@@ -96,7 +96,7 @@ Tools call the domain layer directly. They may share serializers or entity-resol1. For background work, return a `JobReceipt` with `kind`, `id`, `status` and an `overmind://jobs/{kind}/{id}` resource, and teach `get_job` and the resource reader that kind.1. Operations that start paid or long work take a stable `request_key`; an identical retry returns the original receipt and a changed payload conflicts. The catalog adds an optional `request_key` to other project mutations (`services/mcp/mutations.py`): it stores the response, a retryable `MCPError` releases the key, and an unexpected failure leaves the receipt `unknown`.1. Bump `CONTRACT_VERSION` in `services/mcp/__init__.py` with every contract change. `overmind://interface/current` publishes it with the catalog fingerprint.-1. Keep `tools/list` within `MAX_MANIFEST_BYTES` (`tests/mcp_fixtures.py`); output schemas and secrets stay out of discovery.+1. Keep `tools/list` within `MAX_MANIFEST_BYTES` (`tests/mcp_fixtures.py`); output schemas and secrets stay out of discovery. `ToolDefinition.as_mcp_tool` inlines single-use `$defs`, folds nullable pairs and leaves out annotation hints equal to the specification's defaults; tool titles stay, since removing them is a major contract change.Keep handlers thin. Never copy a Console view's business logic into `tools_*.py`.diff --git a/frontend/src/components/capability-detail/ModelsTab.test.tsx b/frontend/src/components/capability-detail/ModelsTab.test.tsxindex 8573ec4a..50529ffd 100644--- a/frontend/src/components/capability-detail/ModelsTab.test.tsx+++ b/frontend/src/components/capability-detail/ModelsTab.test.tsx@@ -144,12 +144,13 @@ describe("ModelsTab alias routing", () => {* control out of the tab order and `title` never fires on focus. */it("exposes every blocked row's reason as a focusable control's name", () => {renderTab({- count: 2,- results: [model("m-2", "failed"), model("m-3", "deploying")],+ count: 3,+ results: [model("m-2", "failed"), model("m-3", "deploying"), model("m-4", "cancelled")],});for (const reason of ["This deployment failed, so it can't serve the alias.",+ "This deployment was cancelled, so it can't serve the alias.","Still deploying — it can serve the alias once it is ready.","The alias only routes to deployed fine-tunes.",]) {diff --git a/frontend/src/components/capability-detail/ModelsTab.tsx b/frontend/src/components/capability-detail/ModelsTab.tsxindex 4c4e148e..0845401b 100644--- a/frontend/src/components/capability-detail/ModelsTab.tsx+++ b/frontend/src/components/capability-detail/ModelsTab.tsx@@ -399,6 +399,7 @@ export function ModelsTab({ capability, capabilityId, projectId }: ModelsTabProp<SelectItem value="warming">Warming</SelectItem><SelectItem value="ready">Ready</SelectItem><SelectItem value="failed">Failed</SelectItem>+ <SelectItem value="cancelled">Cancelled</SelectItem><SelectItem value="deleting">Deleting</SelectItem></SelectContent></Select>diff --git a/frontend/src/components/evaluations/create-run-dialog.tsx b/frontend/src/components/evaluations/create-run-dialog.tsxindex 078a5c9b..1d31bce1 100644--- a/frontend/src/components/evaluations/create-run-dialog.tsx+++ b/frontend/src/components/evaluations/create-run-dialog.tsx@@ -143,6 +143,8 @@ function CreateRunForm({retry: false,staleTime: 30_000,});+ // One key per dialog: a retry after a lost response returns the runs it already started.+ const [requestKey] = useState(() => crypto.randomUUID());const create = useMutation({mutationFn: () =>api.evalRuns.evalRunsCreate({@@ -154,6 +156,7 @@ function CreateRunForm({maxItems,name: name.trim(),project: projectId,+ requestKey,sampling: 1,targets,},diff --git a/frontend/src/components/inference/model-card.tsx b/frontend/src/components/inference/model-card.tsxindex 74df9f94..8915b885 100644--- a/frontend/src/components/inference/model-card.tsx+++ b/frontend/src/components/inference/model-card.tsx@@ -22,6 +22,7 @@ import {} from "@/components/ui/dropdown-menu";import { GraphTooltip } from "@/components/ui/graph-tooltip";import { Icon } from "@/components/ui/icons";+import { Skeleton } from "@/components/ui/skeleton";import {useModelActivityQuery,useModelLiveQuery,@@ -159,6 +160,29 @@ export function InferenceModelCard({);}+const QUICK_METRICS = ["Requests", "Success rate", "Latency · p50", "Generation speed"];++/** Holds a card's place while the first page loads: the header row, then the four metrics. */+export function InferenceModelCardSkeleton() {+ return (+ <Card aria-hidden className="overflow-hidden">+ <div className="flex items-center gap-3 border-b border-border/70 px-4 py-2">+ <Skeleton className="h-8 w-56" />+ <Skeleton className="h-5 w-20" />+ <Skeleton className="ml-auto h-8 w-32" />+ </div>+ <div className="grid grid-cols-2 divide-x divide-border/70 md:grid-cols-4">+ {QUICK_METRICS.map((label) => (+ <div className="min-w-0 px-4 py-3" key={label}>+ <p className="text-xs text-muted-foreground">{label}</p>+ <Skeleton className="mt-2 h-8 w-full" />+ </div>+ ))}+ </div>+ </Card>+ );+}+const integer = (value: number) => value.toLocaleString();const percent = (value: number) => `${value.toFixed(1)}%`;const latency = (value: number) => `${Math.round(value)} ms`;@@ -212,9 +236,13 @@ function QuickMetrics({ modelId }: { modelId: string }) {<span>24h</span></div><div className="mt-2 flex items-center gap-3">- <span className="shrink-0 text-sm tabular-nums">- {item.value == null ? "—" : item.format(item.value)}- </span>+ {metrics.isPending ? (+ <Skeleton aria-hidden className="h-5 w-12 shrink-0" />+ ) : (+ <span className="shrink-0 text-sm tabular-nums">+ {item.value == null ? "—" : item.format(item.value)}+ </span>+ )}<div aria-label={`${item.label} trend`} className="h-8 min-w-0 flex-1" role="img">{points.some((point) => point[item.key] != null) ? (<ResponsiveContainer height="100%" width="100%">@@ -240,13 +268,11 @@ function QuickMetrics({ modelId }: { modelId: string }) {/></LineChart></ResponsiveContainer>+ ) : activity.isPending ? (+ <Skeleton aria-hidden className="h-full w-full" />) : (<span className="text-xs text-muted-foreground">- {activity.isPending- ? "Loading"- : activity.error- ? "Unavailable"- : "No measurements"}+ {activity.error ? "Unavailable" : "No measurements"}</span>)}</div>diff --git a/frontend/src/components/inference/model-performance.tsx b/frontend/src/components/inference/model-performance.tsxindex 6a3f96fa..3766160d 100644--- a/frontend/src/components/inference/model-performance.tsx+++ b/frontend/src/components/inference/model-performance.tsx@@ -34,6 +34,7 @@ import {useModelMetricsQuery,} from "@/hooks/use-inference";import { TITLE } from "@/lib/typography";+import { cn } from "@/lib/utils";import type { InferenceActivityPoint } from "@/openapi";const PERIODS: { value: InferencePeriod; label: string; granularity: "minute" | "hour" | "day" }[] =@@ -59,6 +60,8 @@ export function ModelPerformance({ modelId }: { modelId: string }) {const metrics = metricsQuery.data;const points = activityQuery.data?.points ?? [];const loading = metricsQuery.isPending;+ // A new period or source keeps the previous measurements visible, dimmed, until it loads.+ const stale = metricsQuery.isPlaceholderData || activityQuery.isPlaceholderData;const error = metricsQuery.error ?? activityQuery.error;const refresh = () => {void metricsQuery.refetch();@@ -128,7 +131,10 @@ export function ModelPerformance({ modelId }: { modelId: string }) {fallback="Couldn't load inference performance."/>) : (- <>+ <div+ aria-busy={stale}+ className={cn("space-y-4 transition-opacity", stale && "opacity-60")}+ ><Card className="overflow-hidden"><div className="grid grid-cols-2 divide-x divide-border/70 lg:grid-cols-4"><Metric@@ -254,9 +260,9 @@ export function ModelPerformance({ modelId }: { modelId: string }) {</Tabs></Card>) : null}- </>+ {metrics ? <ModelUsage metrics={metrics} /> : null}+ </div>)}- {metrics ? <ModelUsage metrics={metrics} /> : null}</section>);}diff --git a/frontend/src/hooks/use-capability-active-model.tsx b/frontend/src/hooks/use-capability-active-model.tsxindex 4b47ef45..663f5627 100644--- a/frontend/src/hooks/use-capability-active-model.tsx+++ b/frontend/src/hooks/use-capability-active-model.tsx@@ -12,6 +12,7 @@ import { ResponseError } from "@/openapi";export function blockedReason(status: string): string | null {if (status === "ready") return null;if (status === "failed") return "This deployment failed, so it can't serve the alias.";+ if (status === "cancelled") return "This deployment was cancelled, so it can't serve the alias.";if (status === "deleting" || status === "deleted") return "This deployment has been torn down.";return "Still deploying — it can serve the alias once it is ready.";}diff --git a/frontend/src/hooks/use-inference.scope.test.tsx b/frontend/src/hooks/use-inference.scope.test.tsxindex 46bfdafa..476428ef 100644--- a/frontend/src/hooks/use-inference.scope.test.tsx+++ b/frontend/src/hooks/use-inference.scope.test.tsx@@ -70,6 +70,26 @@ describe("useDeployedModelsQuery", () => {expect(result.current.data).toEqual(page);});++ it("keeps the previous page while the next loads, but never another project's", async () => {+ const first = { count: 30, results: [{ id: "m-1", status: "ready" }] };+ mocks.deployedModelsList.mockResolvedValueOnce(first);+ mocks.deployedModelsList.mockReturnValue(new Promise(() => {}));+ const { result, rerender } = renderHook(+ (params: Parameters<typeof useDeployedModelsQuery>[0]) => useDeployedModelsQuery(params),+ { initialProps: { page: 1, projectId: "proj-1" }, wrapper }+ );+ await waitFor(() => {+ expect(result.current.isSuccess).toBe(true);+ });++ rerender({ page: 2, projectId: "proj-1" });+ expect(result.current.data).toEqual(first);+ expect(result.current.isPlaceholderData).toBe(true);++ rerender({ page: 2, projectId: "proj-2" });+ expect(result.current.data).toBeUndefined();+ });});describe("deployedModelsPollInterval", () => {diff --git a/frontend/src/hooks/use-inference.ts b/frontend/src/hooks/use-inference.tsindex 821829c5..acc4a851 100644--- a/frontend/src/hooks/use-inference.ts+++ b/frontend/src/hooks/use-inference.ts@@ -39,6 +39,11 @@ export const useDeployedModelsQuery = ({}: DeployedModelsQueryParams = {}) =>useQuery({enabled: !!projectId,+ // A new page, filter or sort keeps the previous page on screen until it arrives.+ placeholderData: (previous, query) =>+ query?.queryKey[3] === (projectId || null) && query?.queryKey[4] === (capability || null)+ ? previous+ : undefined,queryFn: () =>apiClient.deployedModels.deployedModelsList({capability: capability || undefined,@@ -87,6 +92,7 @@ export const useModelMetricsQuery = () =>useQuery({enabled: !!id,+ placeholderData: (previous, query) => (query?.queryKey[1] === id ? previous : undefined),queryFn: () =>apiClient.deployedModels.deployedModelsMetricsRetrieve({ id: id!, period, source }),queryKey: ["model-metrics", id, period, source],@@ -101,6 +107,7 @@ export const useModelActivityQuery = () =>useQuery({enabled: !!id,+ placeholderData: (previous, query) => (query?.queryKey[1] === id ? previous : undefined),queryFn: () =>apiClient.deployedModels.deployedModelsActivityRetrieve({granularity,diff --git a/frontend/src/openapi/apis/DeployedModelsApi.ts b/frontend/src/openapi/apis/DeployedModelsApi.tsindex 41bb110c..50018cb9 100644--- a/frontend/src/openapi/apis/DeployedModelsApi.ts+++ b/frontend/src/openapi/apis/DeployedModelsApi.ts@@ -1236,6 +1236,7 @@ export type DeployedModelsListDeploymentTypeEnum = typeof DeployedModelsListDepl* @export*/export const DeployedModelsListStatusEnum = {+ cancelled: 'cancelled',deleted: 'deleted',deleting: 'deleting',deploying: 'deploying',diff --git a/frontend/src/openapi/models/AssistantThread.ts b/frontend/src/openapi/models/AssistantThread.tsindex da3e3536..19c19a9b 100644--- a/frontend/src/openapi/models/AssistantThread.ts+++ b/frontend/src/openapi/models/AssistantThread.ts@@ -58,7 +58,7 @@ export interface AssistantThread {* @type {string}* @memberof AssistantThread*/- readonly experiment: string | null;+ readonly experiment: string;/**** @type {AssistantThreadStateEnum}diff --git a/frontend/src/openapi/models/Capability.ts b/frontend/src/openapi/models/Capability.tsindex dc1abe3b..699f9b43 100644--- a/frontend/src/openapi/models/Capability.ts+++ b/frontend/src/openapi/models/Capability.ts@@ -118,7 +118,7 @@ export interface Capability {* @type {CapabilityStatusEnum}* @memberof Capability*/- status?: CapabilityStatusEnum;+ readonly status: CapabilityStatusEnum;/**** @type {boolean}@@ -259,6 +259,7 @@ export function instanceOfCapability(value: object): value is Capability {if (!('flow' in value) || value['flow'] === undefined) return false;if (!('name' in value) || value['name'] === undefined) return false;if (!('slug' in value) || value['slug'] === undefined) return false;+ if (!('status' in value) || value['status'] === undefined) return false;if (!('observed' in value) || value['observed'] === undefined) return false;if (!('activeModelActivatedAt' in value) || value['activeModelActivatedAt'] === undefined) return false;if (!('firstApplicationRequestAt' in value) || value['firstApplicationRequestAt'] === undefined) return false;@@ -294,7 +295,7 @@ export function CapabilityFromJSONTyped(json: any, ignoreDiscriminator: boolean)'entrypointFn': json['entrypoint_fn'] == null ? undefined : json['entrypoint_fn'],'model': json['model'] == null ? undefined : json['model'],'cliVersion': json['cli_version'] == null ? undefined : json['cli_version'],- 'status': json['status'] == null ? undefined : CapabilityStatusEnumFromJSON(json['status']),+ 'status': CapabilityStatusEnumFromJSON(json['status']),'observed': json['observed'],'footprint': json['footprint'] == null ? undefined : json['footprint'],'inputSchema': json['input_schema'] == null ? undefined : json['input_schema'],@@ -323,7 +324,7 @@ export function CapabilityToJSON(json: any): Capability {return CapabilityToJSONTyped(json, false);}-export function CapabilityToJSONTyped(value?: Omit<Capability, 'id'|'activation'|'dataset_size'|'flow'|'slug'|'observed'|'active_model_activated_at'|'first_application_request_at'|'last_application_request_at'|'usage_stats'|'last_activity_at'|'created_at'|'updated_at'|'previous_active_model'> | null, ignoreDiscriminator: boolean = false): any {+export function CapabilityToJSONTyped(value?: Omit<Capability, 'id'|'activation'|'dataset_size'|'flow'|'slug'|'status'|'observed'|'active_model_activated_at'|'first_application_request_at'|'last_application_request_at'|'usage_stats'|'last_activity_at'|'created_at'|'updated_at'|'previous_active_model'> | null, ignoreDiscriminator: boolean = false): any {if (value == null) {return value;}@@ -337,7 +338,6 @@ export function CapabilityToJSONTyped(value?: Omit<Capability, 'id'|'activation''entrypoint_fn': value['entrypointFn'],'model': value['model'],'cli_version': value['cliVersion'],- 'status': CapabilityStatusEnumToJSON(value['status']),'footprint': value['footprint'],'input_schema': value['inputSchema'],'output_fields': value['outputFields'],diff --git a/frontend/src/openapi/models/CapabilityRequest.ts b/frontend/src/openapi/models/CapabilityRequest.tsindex 94930977..2bb9517f 100644--- a/frontend/src/openapi/models/CapabilityRequest.ts+++ b/frontend/src/openapi/models/CapabilityRequest.ts@@ -13,14 +13,6 @@*/import { mapValues } from '../runtime';-import type { CapabilityStatusEnum } from './CapabilityStatusEnum';-import {- CapabilityStatusEnumFromJSON,- CapabilityStatusEnumFromJSONTyped,- CapabilityStatusEnumToJSON,- CapabilityStatusEnumToJSONTyped,-} from './CapabilityStatusEnum';-/**** @export@@ -69,12 +61,6 @@ export interface CapabilityRequest {* @memberof CapabilityRequest*/cliVersion?: string;- /**- *- * @type {CapabilityStatusEnum}- * @memberof CapabilityRequest- */- status?: CapabilityStatusEnum;/**** @type {any}@@ -149,8 +135,6 @@ export interface CapabilityRequest {benchmarkModel?: string | null;}--/*** Check if a given object implements the CapabilityRequest interface.*/@@ -177,7 +161,6 @@ export function CapabilityRequestFromJSONTyped(json: any, ignoreDiscriminator: b'entrypointFn': json['entrypoint_fn'] == null ? undefined : json['entrypoint_fn'],'model': json['model'] == null ? undefined : json['model'],'cliVersion': json['cli_version'] == null ? undefined : json['cli_version'],- 'status': json['status'] == null ? undefined : CapabilityStatusEnumFromJSON(json['status']),'footprint': json['footprint'] == null ? undefined : json['footprint'],'inputSchema': json['input_schema'] == null ? undefined : json['input_schema'],'outputFields': json['output_fields'] == null ? undefined : json['output_fields'],@@ -211,7 +194,6 @@ export function CapabilityRequestToJSONTyped(value?: CapabilityRequest | null, i'entrypoint_fn': value['entrypointFn'],'model': value['model'],'cli_version': value['cliVersion'],- 'status': CapabilityStatusEnumToJSON(value['status']),'footprint': value['footprint'],'input_schema': value['inputSchema'],'output_fields': value['outputFields'],diff --git a/frontend/src/openapi/models/DeployedModelStatusEnum.ts b/frontend/src/openapi/models/DeployedModelStatusEnum.tsindex 6ca718e9..bf23e288 100644--- a/frontend/src/openapi/models/DeployedModelStatusEnum.ts+++ b/frontend/src/openapi/models/DeployedModelStatusEnum.ts@@ -20,6 +20,7 @@* * `warming` - Warming* * `ready` - Ready* * `failed` - Failed+ * * `cancelled` - Cancelled* * `deleting` - Deleting* * `deleted` - Deleted* @export@@ -31,6 +32,7 @@ export const DeployedModelStatusEnum = {warming: 'warming',ready: 'ready',failed: 'failed',+ cancelled: 'cancelled',deleting: 'deleting',deleted: 'deleted'} as const;diff --git a/frontend/src/openapi/models/EvalRunCreateRequest.ts b/frontend/src/openapi/models/EvalRunCreateRequest.tsindex d9b690c0..1e1058e2 100644--- a/frontend/src/openapi/models/EvalRunCreateRequest.ts+++ b/frontend/src/openapi/models/EvalRunCreateRequest.ts@@ -96,6 +96,12 @@ export interface EvalRunCreateRequest {* @memberof EvalRunCreateRequest*/sampling?: number;+ /**+ * Project-scoped. An identical retry returns the same group; a changed request under the same key is refused.+ * @type {string}+ * @memberof EvalRunCreateRequest+ */+ requestKey?: string;}@@ -146,6 +152,7 @@ export function EvalRunCreateRequestFromJSONTyped(json: any, ignoreDiscriminator'description': json['description'] == null ? undefined : json['description'],'maxItems': json['max_items'] == null ? undefined : json['max_items'],'sampling': json['sampling'] == null ? undefined : json['sampling'],+ 'requestKey': json['request_key'] == null ? undefined : json['request_key'],};}@@ -170,5 +177,6 @@ export function EvalRunCreateRequestToJSONTyped(value?: EvalRunCreateRequest | n'description': value['description'],'max_items': value['maxItems'],'sampling': value['sampling'],+ 'request_key': value['requestKey'],};}diff --git a/frontend/src/openapi/models/PatchedCapabilityRequest.ts b/frontend/src/openapi/models/PatchedCapabilityRequest.tsindex f17c2320..18f390f9 100644--- a/frontend/src/openapi/models/PatchedCapabilityRequest.ts+++ b/frontend/src/openapi/models/PatchedCapabilityRequest.ts@@ -13,14 +13,6 @@*/import { mapValues } from '../runtime';-import type { CapabilityStatusEnum } from './CapabilityStatusEnum';-import {- CapabilityStatusEnumFromJSON,- CapabilityStatusEnumFromJSONTyped,- CapabilityStatusEnumToJSON,- CapabilityStatusEnumToJSONTyped,-} from './CapabilityStatusEnum';-/**** @export@@ -69,12 +61,6 @@ export interface PatchedCapabilityRequest {* @memberof PatchedCapabilityRequest*/cliVersion?: string;- /**- *- * @type {CapabilityStatusEnum}- * @memberof PatchedCapabilityRequest- */- status?: CapabilityStatusEnum;/**** @type {any}@@ -149,8 +135,6 @@ export interface PatchedCapabilityRequest {benchmarkModel?: string | null;}--/*** Check if a given object implements the PatchedCapabilityRequest interface.*/@@ -175,7 +159,6 @@ export function PatchedCapabilityRequestFromJSONTyped(json: any, ignoreDiscrimin'entrypointFn': json['entrypoint_fn'] == null ? undefined : json['entrypoint_fn'],'model': json['model'] == null ? undefined : json['model'],'cliVersion': json['cli_version'] == null ? undefined : json['cli_version'],- 'status': json['status'] == null ? undefined : CapabilityStatusEnumFromJSON(json['status']),'footprint': json['footprint'] == null ? undefined : json['footprint'],'inputSchema': json['input_schema'] == null ? undefined : json['input_schema'],'outputFields': json['output_fields'] == null ? undefined : json['output_fields'],@@ -209,7 +192,6 @@ export function PatchedCapabilityRequestToJSONTyped(value?: PatchedCapabilityReq'entrypoint_fn': value['entrypointFn'],'model': value['model'],'cli_version': value['cliVersion'],- 'status': CapabilityStatusEnumToJSON(value['status']),'footprint': value['footprint'],'input_schema': value['inputSchema'],'output_fields': value['outputFields'],diff --git a/frontend/src/routes/_auth/inference.tsx b/frontend/src/routes/_auth/inference.tsxindex 4f5ff3da..a36b4185 100644--- a/frontend/src/routes/_auth/inference.tsx+++ b/frontend/src/routes/_auth/inference.tsx@@ -3,7 +3,7 @@ import { useEffect, useState } from "react";import { createFileRoute } from "@tanstack/react-router";import { InferenceToolbar } from "@/components/inference/inference-toolbar";-import { InferenceModelCard } from "@/components/inference/model-card";+import { InferenceModelCard, InferenceModelCardSkeleton } from "@/components/inference/model-card";import { ProjectRequiredEmptyState } from "@/components/project-required-empty-state";import { DetailErrorState } from "@/components/route-error";import { Button } from "@/components/ui/button";@@ -11,10 +11,10 @@ import { EmptyState } from "@/components/ui/empty-state";import { Icon } from "@/components/ui/icons";import { PageHeader } from "@/components/ui/page-header";import { PageShell } from "@/components/ui/page-shell";-import { LoadingState } from "@/components/ui/spinner";import { TablePagination } from "@/components/ui/table-pagination";import { useDeployedModelsQuery } from "@/hooks/use-inference";import { type InferenceSearch, inferenceSearchSchema } from "@/lib/schemas";+import { cn } from "@/lib/utils";const INFERENCE_HEADER = <PageHeader title="Inference" variant="workspace" />;@@ -53,7 +53,7 @@ function InferencePage() {setSearchText((cur) => (search === cur.trim() ? cur : search));}, [search]);- const { data, isLoading, error, refetch } = useDeployedModelsQuery({+ const { data, isLoading, isPlaceholderData, error, refetch } = useDeployedModelsQuery({capability: capability === "all" ? undefined : capability,deploymentType: deploymentType === "all" ? undefined : deploymentType,ordering,@@ -122,8 +122,20 @@ function InferencePage() {className="pointer-events-none absolute inset-x-0 top-full h-4 backdrop-blur-sm [mask-image:linear-gradient(to_bottom,black_0%,black_20%,transparent_100%)]"/></div>- <div className="flex-1 space-y-4 overflow-y-auto py-4">- {isLoading && <LoadingState label="Loading models" />}+ <div+ aria-busy={isLoading || isPlaceholderData}+ className={cn(+ "flex-1 space-y-4 overflow-y-auto py-4 transition-opacity",+ isPlaceholderData && "opacity-60"+ )}+ >+ {isLoading && (+ <div aria-label="Loading models" className="space-y-4" role="status">+ {[0, 1, 2].map((slot) => (+ <InferenceModelCardSkeleton key={slot} />+ ))}+ </div>+ )}{error && (<DetailErrorStateaction={@@ -138,7 +150,7 @@ function InferencePage() {{data?.results.map((model) => (<InferenceModelCard key={model.id} model={model} projectId={projectId} />))}- {!isLoading && !error && !data?.results.length && (+ {!isLoading && !isPlaceholderData && !error && !data?.results.length && (<EmptyStateaction={hasActiveFilters ? (diff --git a/modal_shared/training_monitoring.py b/modal_shared/training_monitoring.pyindex 813cf9e3..9428cb49 100644--- a/modal_shared/training_monitoring.py+++ b/modal_shared/training_monitoring.py@@ -1,3 +1,4 @@+import contextlibimport hashlibimport jsonimport math@@ -32,7 +33,13 @@ def capabilities(provider):return {"schedule_modes": ["adaptive", "steps", "epoch", "off"] if controlled else ["off"],"loss_metrics": controlled,- "generation_checks": ["classification", "exact_match", "json_schema", "json_fields"]+ "generation_checks": [+ "classification",+ "exact_match",+ "json_schema",+ "json_fields",+ "tool_calls",+ ]if provider == "modal"else [],"native_decisions": provider == "modal",@@ -40,7 +47,10 @@ def capabilities(provider):"optimizer_resume": "native_latest_state_only" if provider == "modal" else "not_qualified","runtime_qualification": "release_specific; CPU fixtures do not qualify GPU execution","limitations": [- "Generation references come from the final supervised answer, not tool execution",+ "Generation references come from the final supervised answer; tool_calls uses the "+ "first supervised turn that calls a tool. Tools never execute",+ "tool_calls reads Hermes, Llama and Mistral JSON calls and Qwen XML calls; a turn in "+ "another format is unscorable","Metered judges, challenge suites and declared slice sampling are not supported","Monitoring overhead target is not a spend limit",]@@ -109,8 +119,8 @@ def resolve_policy(value, *, has_development, provider):raise ValueError("Step monitoring requires interval_steps")if policy["mode"] != "steps" and policy["interval_steps"] is not None:raise ValueError("interval_steps requires steps mode")- if policy["selection"] not in {"last", "development_loss"}:- raise ValueError("Select last or development_loss")+ if policy["selection"] not in {"last", "development_loss", "generation"}:+ raise ValueError("Select last, development_loss or generation")if policy["failure_policy"] not in {"continue", "stop"}:raise ValueError("failure_policy must be continue or stop")generation = policy["generation"]@@ -131,9 +141,11 @@ def resolve_policy(value, *, has_development, provider):"exact_match","json_schema","json_fields",+ "tool_calls",}:raise ValueError(- "Generation probes support classification, exact_match, json_schema or json_fields"+ "Generation probes support classification, exact_match, json_schema, json_fields "+ "or tool_calls")if generation["normalization"] not in {"none", "strip", "strip_thinking"}:raise ValueError("Unknown output normalization")@@ -174,7 +186,15 @@ def resolve_policy(value, *, has_development, provider):)elif fields is not None:raise ValueError("fields requires json_fields generation")+ if generation["kind"] == "tool_calls" and (+ generation.get("schema") is not None or generation.get("labels") is not None+ ):+ raise ValueError(+ "tool_calls compares the first tool call; it takes no schema or labels"+ )policy["generation"] = generation+ if policy["selection"] == "generation" and generation is None:+ raise ValueError("Generation selection requires a generation probe")early = policy["early_stopping"]if early is not None:if not isinstance(early, dict) or set(early) - {"patience", "min_delta", "warmup_checks"}:@@ -553,6 +573,119 @@ def score_json_fields(prediction, reference, fields):}+def _tool_call(name, arguments):+ if not isinstance(name, str) or not name:+ return None+ if isinstance(arguments, str):+ # Arguments that do not parse stay a string, which scores as invalid.+ with contextlib.suppress(ValueError, RecursionError):+ arguments = _json_document(arguments)+ return {"name": name, "arguments": arguments}+++def _json_call(text, start, name=None):+ decoder = json.JSONDecoder(+ object_pairs_hook=_json_object, parse_float=Decimal, parse_constant=_invalid_constant+ )+ try:+ value, _ = decoder.raw_decode(text, start)+ except (ValueError, RecursionError):+ return None+ if name is not None:+ return _tool_call(name, value)+ if isinstance(value, list):+ value = value[0] if value else None+ if not isinstance(value, dict):+ return None+ if isinstance(value.get("function"), dict):+ value = value["function"]+ return _tool_call(value.get("name"), value.get("arguments", value.get("parameters")))+++def _xml_call(text):+ found = re.search(r"<function=([^>\s]+)>(.*?)(?:</function>|$)", text, re.DOTALL)+ if not found:+ return None+ parameters = re.findall(r"<parameter=([^>\s]+)>(.*?)</parameter>", found[2], re.DOTALL)+ if len(parameters) != found[2].count("<parameter="):+ # A cut-off parameter leaves the arguments a string, which scores as invalid.+ return _tool_call(found[1], found[2])+ arguments = {}+ for key, raw in parameters:+ try:+ arguments[key] = _json_document(raw.strip("\n"))+ except (ValueError, RecursionError):+ arguments[key] = raw.strip("\n")+ return _tool_call(found[1], arguments)+++def parse_tool_call(text):+ """The first tool call in a model's native output, or None for any other format."""+ tagged = re.search(r"<tool_call>(.*?)(?:</tool_call>|$)", text, re.DOTALL)+ if tagged:+ body = tagged[1]+ if re.match(r"\s*<function=", body):+ return _xml_call(body)+ start = body.find("{")+ return _json_call(body, start) if start >= 0 else None+ mistral = re.search(r"\[TOOL_CALLS\]\s*(?:([\w.-]+)\[ARGS\]\s*)?", text)+ if mistral:+ return _json_call(text, mistral.end(), name=mistral[1])+ start = re.search(r"[\[{]", text)+ xml = text.find("<function=")+ if xml >= 0 and (start is None or xml < start.start()):+ return _xml_call(text)+ return _json_call(text, start.start()) if start else None+++def first_tool_call(row, decode):+ """The prefix before the first supervised turn that calls a tool, that turn's tokens and+ its call; None when no supervised turn calls one. ``decode`` must keep the call markup."""+ ids, labels = row["input_ids"], row["labels"]+ if len(ids) != len(labels):+ raise ValueError("Token and label lengths differ")+ start = None+ for index, label in enumerate([*labels, -100]):+ if label != -100 and start is None:+ start = index+ elif label == -100 and start is not None:+ call = parse_tool_call(decode(ids[start:index]))+ # The first call is the reference even when its arguments are invalid.+ if call is not None:+ if not isinstance(call["arguments"], dict):+ return None+ if start == 0:+ raise ValueError("Generation requires an input-only prefix")+ return ids[:start], ids[start:index], call+ start = None+ return None+++def score_tool_call(prediction, reference):+ if reference is None:+ return {+ "scorer": "tool_calls:1",+ "scoring_status": "unscorable",+ "passed": None,+ "reason": "reference_has_no_tool_call",+ }+ predicted = parse_tool_call(prediction)+ name = predicted is not None and predicted["name"] == reference["name"]+ valid = predicted is not None and isinstance(predicted["arguments"], dict)+ return {+ "scorer": "tool_calls:1",+ "scoring_status": "completed",+ "passed": name and valid,+ "tool_call": {+ "name": predicted["name"] if predicted else None,+ "name_correct": name,+ "arguments_valid": valid,+ "arguments_equal": valid+ and _json_equal(predicted["arguments"], reference["arguments"]),+ },+ }++def contract_metrics(examples, policy):completed = [item for item in examples if item.get("status") == "completed"]@@ -576,4 +709,11 @@ def contract_metrics(examples, policy):)for pointer in policy["fields"]}+ if policy["kind"] == "tool_calls":+ result["scorer"] = "tool_calls:1"+ calls = [item["tool_call"] for item in completed if type(item.get("passed")) is bool]+ result["tool_call"] = {+ key: sum(call[key] for call in calls) / len(calls) if calls else None+ for key in ("name_correct", "arguments_valid", "arguments_equal")+ }return resultdiff --git a/modal_shared/training_monitoring_runtime.py b/modal_shared/training_monitoring_runtime.pyindex b81eaa34..baf58ad8 100644--- a/modal_shared/training_monitoring_runtime.py+++ b/modal_shared/training_monitoring_runtime.py@@ -26,6 +26,12 @@ def atomic_json(path, value):os.replace(temporary, path)+def probe_pass_rate(checkpoint):+ generation = checkpoint["metrics"].get("generation") or {}+ rate = generation.get("pass_rate", generation.get("accuracy"))+ return rate if type(rate) in {int, float} and math.isfinite(rate) else None++def freeze_run_files(run_dir, policy):root = Path(run_dir)rows = {}@@ -213,6 +219,7 @@ class Monitor:generation_due = (finalor step == 0+ or self.policy["selection"] == "generation"or (self.schedule.checks + 1) % self.policy["generation_every"] == 0)if self.policy["generation"] and generation_due:@@ -353,13 +360,26 @@ class Monitor:if item["state"] == "available"and item.get("verification", {}).get("reload_verified") is True]+ if self.policy["selection"] == "generation":+ candidates = [item for item in candidates if probe_pass_rate(item) is not None]if not candidates:return- selected = (- min(candidates, key=lambda item: (item["metrics"]["eval_loss"], item["step"]))- if self.policy["selection"] == "development_loss"- else max(candidates, key=lambda item: item["step"])- )+ if self.policy["selection"] == "development_loss":+ selected = min(+ candidates, key=lambda item: (item["metrics"]["eval_loss"], item["step"])+ )+ elif self.policy["selection"] == "generation":+ # Equal pass rates fall back to the lower development loss, then the earlier step.+ selected = max(+ candidates,+ key=lambda item: (+ probe_pass_rate(item),+ -item["metrics"]["eval_loss"],+ -item["step"],+ ),+ )+ else:+ selected = max(candidates, key=lambda item: item["step"])self.data["selected_checkpoint"] = selected["key"]for item in self.data["checkpoints"]:item["selected"] = item["key"] == selected["key"]diff --git a/overbae/api/eval_serializers.py b/overbae/api/eval_serializers.pyindex 8c604fb8..d4471e09 100644--- a/overbae/api/eval_serializers.py+++ b/overbae/api/eval_serializers.py@@ -10,6 +10,7 @@ from rest_framework.exceptions import PermissionDeniedfrom overbae.api.scoping import project_ids_forfrom overbae.core.errors import InputValidationErrorfrom overbae.core.model_registry import judge_picker_models+from overbae.core.utils import fingerprintfrom overbae.innermind import context, deterministic, generation, runsfrom overbae.innermind.definitions import DefinitionSource, definition_sourcefrom overbae.models import (@@ -346,6 +347,12 @@ class EvalRunCreateSerializer(EvaluationScopeSerializer):description = serializers.CharField(required=False, allow_blank=True, default="")max_items = serializers.IntegerField(required=False, min_value=0, default=0)sampling = serializers.FloatField(required=False, min_value=0.0, max_value=1.0, default=1.0)+ request_key = serializers.CharField(+ max_length=128,+ required=False,+ help_text="Project-scoped. An identical retry returns the same group; a changed "+ "request under the same key is refused.",+ )def validate(self, attrs):attrs = super().validate(attrs)@@ -366,9 +373,32 @@ class EvalRunCreateSerializer(EvaluationScopeSerializer):raise serializers.ValidationError({"dataset": reason})return attrs- def save(self, **kwargs) -> dict:- """One run per target in one group; each is launched once committed."""+ def save(self, gate=None, **kwargs) -> dict:+ """One run per target in one group; each is launched once committed. ``gate``+ runs only before new runs are created, so a keyed replay never hits it."""data = self.validated_data+ key = data.get("request_key", "")+ asked = fingerprint({k: v for k, v in self.initial_data.items() if k != "request_key"})+ with transaction.atomic():+ if key:+ # Serializes keyed creates so two identical retries cannot both create.+ Project.objects.select_for_update().get(pk=data["project"].pk)+ prior = list(+ EvalRun.objects.filter(project=data["project"], request_key=key)+ .select_related("dataset__capability", "cell")+ .order_by("created_at")+ )+ if prior:+ if prior[0].request_fingerprint != asked:+ raise serializers.ValidationError(+ {"request_key": "This key already identifies a different evaluation."}+ )+ return {"group": prior[0].group, "runs": prior}+ if gate:+ gate()+ return self._create(data, key, asked, **kwargs)++ def _create(self, data, key, asked, **kwargs) -> dict:matrix = self.matrix()if not matrix:raise serializers.ValidationError({"eval_set": "No enabled eval matrix rows apply."})@@ -400,6 +430,8 @@ class EvalRunCreateSerializer(EvaluationScopeSerializer):judge_model=data["judge_model"],max_items=data["max_items"],sampling=data["sampling"],+ request_key=key,+ request_fingerprint=asked if key else "",**kwargs,)runs.launch(run)diff --git a/overbae/api/eval_views.py b/overbae/api/eval_views.pyindex b7589b05..2a262c0f 100644--- a/overbae/api/eval_views.py+++ b/overbae/api/eval_views.py@@ -245,9 +245,10 @@ class EvalRunViewSet(def create(self, request):serializer = EvalRunCreateSerializer(data=request.data, context={"request": request})serializer.is_valid(raise_exception=True)- require_credits(request.user)try:- created = serializer.save(triggered_by=request.user)+ created = serializer.save(+ gate=lambda: require_credits(request.user), triggered_by=request.user+ )except runs.RunError as exc:raise ValidationError({"detail": str(exc)}) from excreturn Response(diff --git a/overbae/api/serializers.py b/overbae/api/serializers.pyindex e9bdf073..2d5e93ba 100644--- a/overbae/api/serializers.py+++ b/overbae/api/serializers.py@@ -172,28 +172,33 @@ def _usage_values(queryset, group_field: str):)+def _response_id(attrs: dict | None) -> str | None:+ value = (attrs or {}).get("gen_ai.response.id")+ return value if isinstance(value, str) and value else None++def _leaf_usage_rows(rows) -> list[tuple]:"""Double instrumentation (a framework instrumentor beside a provider one)reports the same call twice: as parent and child, or — because eachinstrumentor keeps its own context chain — as two spans anywhere in the- tree, from different scopes, with the same token total and overlapping- windows. Count each call once, preferring the row that carries cost and- model. Rows without a scope name never twin-merge: their identity is- unknowable."""+ tree. Two spans that both carry a provider response ID are one call exactly+ when the IDs match. Otherwise twins come from different scopes, with the same+ token total and overlapping windows; rows without a scope name never+ twin-merge on that evidence. Count each call once, preferring the row that+ carries cost and model."""entries = list(rows)- child_parents = {(e[0], e[2]) for e in entries if e[2]}+ # A child that carries only a response ID measures nothing, so its parent's report stays.+ child_parents = {+ (e[0], e[2])+ for e in entries+ if e[2]+ and (+ _total_tokens_from_span_attributes(e[7]) is not None+ or _total_cost_from_span_attributes(e[7]) is not None+ )+ }kept = [e for e in entries if (e[0], e[1]) not in child_parents]- twins: dict[tuple, list[tuple[int, tuple]]] = {}- solo: list[tuple[int, tuple]] = []- for idx, entry in enumerate(kept):- group, _sid, _parent, trace, scope, _start, _end, attrs = entry- tokens = _total_tokens_from_span_attributes(attrs)- if tokens is not None and scope:- twins.setdefault((group, trace, tokens), []).append((idx, entry))- else:- solo.append((idx, entry))-def _richness(entry) -> tuple:attrs = entry[7]start, end = entry[5] or 0, entry[6] or 0@@ -203,14 +208,56 @@ def _leaf_usage_rows(rows) -> list[tuple]:end - start,)- surviving = list(solo)+ calls: dict[tuple, tuple[int, tuple]] = {}+ candidates: list[tuple[int, tuple]] = []+ for idx, entry in enumerate(kept):+ response = _response_id(entry[7])+ if response is None:+ candidates.append((idx, entry))+ continue+ key = (entry[0], entry[3], response)+ if key not in calls:+ calls[key] = (idx, entry)+ continue+ first, prior = calls[key]+ best, other = (entry, prior) if _richness(entry) < _richness(prior) else (prior, entry)+ # A duplicate may report the tokens and the other the cost: keep both facts.+ calls[key] = (min(idx, first), (*best[:7], {**(other[7] or {}), **(best[7] or {})}))+ candidates.extend(calls.values())++ twins: dict[tuple, list[tuple[int, tuple]]] = {}+ surviving: list[tuple[int, tuple]] = []+ for idx, entry in candidates:+ group, _sid, _parent, trace, scope, _start, _end, attrs = entry+ tokens = _total_tokens_from_span_attributes(attrs)+ if tokens is not None and scope:+ twins.setdefault((group, trace, tokens), []).append((idx, entry))+ else:+ surviving.append((idx, entry))+for bucket in twins.values():keep: list[tuple[int, tuple]] = []+ # An ID-less span stands for one call, so it absorbs at most one response ID.+ absorbed: dict[int, str] = {}for idx, entry in sorted(bucket, key=lambda pair: _richness(pair[1])):scope, start, end = entry[4], entry[5] or 0, entry[6] or 0- if any(k[4] != scope and start < (k[6] or 0) and (k[5] or 0) < end for _i, k in keep):- continue- keep.append((idx, entry))+ response = _response_id(entry[7])+ twin = next(+ (+ i+ for i, k in keep+ if k[4] != scope+ and start < (k[6] or 0)+ and (k[5] or 0) < end+ and not (response and _response_id(k[7]))+ and not (response and i in absorbed)+ ),+ None,+ )+ if twin is None:+ keep.append((idx, entry))+ elif response:+ absorbed[twin] = responsesurviving.extend(keep)surviving.sort(key=lambda pair: pair[0])@@ -742,6 +789,8 @@ class CapabilitySerializer(serializers.ModelSerializer):"slug","created_at","updated_at",+ # Scans, sync and DELETE own the lifecycle.+ "status",# Measured by ingest; ``observed`` decides whether a scan may retire the row."usage_stats","last_activity_at",diff --git a/overbae/core/decisions.py b/overbae/core/decisions.pyindex fc795476..4756f34d 100644--- a/overbae/core/decisions.py+++ b/overbae/core/decisions.py@@ -195,7 +195,7 @@ def response_usage(payload: dict, elapsed: float) -> dict[str, Any]:def tokens(name):value = usage.get(name)- return value if type(value) is int and value >= 0 else 0+ return value if type(value) is int and value >= 0 else Nonereturn {"response_cost": cost,diff --git a/overbae/migrations/0075_drop_assistant_thread_dataset.py b/overbae/migrations/0075_drop_assistant_thread_dataset.pynew file mode 100644index 00000000..59488776--- /dev/null+++ b/overbae/migrations/0075_drop_assistant_thread_dataset.py@@ -0,0 +1,34 @@+import importlib++import django.db.models.deletion+from django.db import migrations, models++one_agent = importlib.import_module("overbae.migrations.0073_one_agent")+++def dataset_threads_to_experiments(apps, schema_editor):+ """A dataset conversation started after 0073 ran becomes an experiment the same way."""+ # Checked at once: the ALTER TABLE below refuses a table with pending foreign-key checks.+ schema_editor.execute("SET CONSTRAINTS ALL IMMEDIATE")+ one_agent.dataset_threads_to_experiments(apps, schema_editor)+++class Migration(migrations.Migration):+ dependencies = [("overbae", "0074_eval_judge_context_and_one_score_per_row")]++ operations = [+ migrations.RunPython(dataset_threads_to_experiments, migrations.RunPython.noop),+ migrations.RemoveConstraint(+ model_name="assistantthread", name="assistant_thread_one_subject"+ ),+ migrations.RemoveField(model_name="assistantthread", name="dataset"),+ migrations.AlterField(+ model_name="assistantthread",+ name="experiment",+ field=models.OneToOneField(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="assistant_thread",+ to="overbae.experiment",+ ),+ ),+ ]diff --git a/overbae/migrations/0076_eval_run_request_key.py b/overbae/migrations/0076_eval_run_request_key.pynew file mode 100644index 00000000..b6d4ca86--- /dev/null+++ b/overbae/migrations/0076_eval_run_request_key.py@@ -0,0 +1,27 @@+# Generated by Django 6.0.8 on 2026-12-02 10:20++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('overbae', '0075_drop_assistant_thread_dataset'),+ ]++ operations = [+ migrations.AddField(+ model_name='evalrun',+ name='request_fingerprint',+ field=models.CharField(blank=True, default='', max_length=64),+ ),+ migrations.AddField(+ model_name='evalrun',+ name='request_key',+ field=models.CharField(blank=True, default='', max_length=128),+ ),+ migrations.AddIndex(+ model_name='evalrun',+ index=models.Index(condition=models.Q(('request_key', ''), _negated=True), fields=['project', 'request_key'], name='eval_run_request'),+ ),+ ]diff --git a/overbae/migrations/0077_deployed_model_cancelled.py b/overbae/migrations/0077_deployed_model_cancelled.pynew file mode 100644index 00000000..4c84fea5--- /dev/null+++ b/overbae/migrations/0077_deployed_model_cancelled.py@@ -0,0 +1,18 @@+# Generated by Django 6.0.8 on 2026-12-02 10:22++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('overbae', '0076_eval_run_request_key'),+ ]++ operations = [+ migrations.AlterField(+ model_name='deployedmodel',+ name='status',+ field=models.CharField(choices=[('queued', 'Queued'), ('quantizing', 'Quantizing'), ('deploying', 'Deploying'), ('warming', 'Warming'), ('ready', 'Ready'), ('failed', 'Failed'), ('cancelled', 'Cancelled'), ('deleting', 'Deleting'), ('deleted', 'Deleted')], db_index=True, default='queued', max_length=20),+ ),+ ]diff --git a/overbae/models/assistant.py b/overbae/models/assistant.pyindex d84f535f..62140994 100644--- a/overbae/models/assistant.py+++ b/overbae/models/assistant.py@@ -19,8 +19,7 @@ class ThreadQuerySet(models.QuerySet):class AssistantThread(models.Model):"""An experiment's conversation, shared by the project's members. The event log is the- record: no process holds state between turns. ``dataset`` is unused since every- conversation became an experiment's; a later migration drops it."""+ record: no process holds state between turns."""class State(models.TextChoices):IDLE = "idle"@@ -29,11 +28,8 @@ class AssistantThread(models.Model):id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)project = models.ForeignKey("overbae.Project", on_delete=models.CASCADE)objects = ThreadQuerySet.as_manager()- dataset = models.OneToOneField(- "overbae.Dataset", on_delete=models.CASCADE, null=True, related_name="assistant_thread"- )experiment = models.OneToOneField(- "overbae.Experiment", on_delete=models.CASCADE, null=True, related_name="assistant_thread"+ "overbae.Experiment", on_delete=models.CASCADE, related_name="assistant_thread")state = models.CharField(max_length=16, choices=State, default=State.IDLE)# Counts turns. A turn writes only while it is the newest, so a turn that was taken@@ -44,14 +40,6 @@ class AssistantThread(models.Model):updated_at = models.DateTimeField(auto_now=True)created_at = models.DateTimeField(auto_now_add=True)- class Meta:- constraints = [- models.CheckConstraint(- condition=models.Q(dataset__isnull=True) ^ models.Q(experiment__isnull=True),- name="assistant_thread_one_subject",- )- ]-class AssistantEvent(models.Model):class Kind(models.TextChoices):diff --git a/overbae/models/inference.py b/overbae/models/inference.pyindex 42f30353..62c6e908 100644--- a/overbae/models/inference.py+++ b/overbae/models/inference.py@@ -21,6 +21,8 @@ class DeployedModel(models.Model):WARMING = "warming", "Warming"READY = "ready", "Ready"FAILED = "failed", "Failed"+ # Its training job was cancelled while the model was being published.+ CANCELLED = "cancelled", "Cancelled"DELETING = "deleting", "Deleting"DELETED = "deleted", "Deleted"diff --git a/overbae/models/innermind.py b/overbae/models/innermind.pyindex 91828c07..6bf6bd21 100644--- a/overbae/models/innermind.py+++ b/overbae/models/innermind.py@@ -265,6 +265,10 @@ class EvalRun(models.Model):params = models.JSONField(default=dict, blank=True)group = models.UUIDField(default=uuid.uuid4, db_index=True)is_baseline = models.BooleanField(default=False)+ # Shared by every run of the group the keyed request created; the fingerprint is what+ # it asked for, so a retry that asks for something else is refused.+ request_key = models.CharField(max_length=128, blank=True, default="")+ request_fingerprint = models.CharField(max_length=64, blank=True, default="")status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)celery_task_id = models.CharField(max_length=255, blank=True, default="")@@ -297,6 +301,11 @@ class EvalRun(models.Model):condition=models.Q(status="running"),name="eval_running_project",),+ models.Index(+ fields=["project", "request_key"],+ condition=~models.Q(request_key=""),+ name="eval_run_request",+ ),]def __str__(self) -> str:diff --git a/overbae/models/traces.py b/overbae/models/traces.pyindex b467b9e4..2582ba9f 100644--- a/overbae/models/traces.py+++ b/overbae/models/traces.py@@ -71,6 +71,8 @@ USAGE_ATTR_KEYS = ("genai.response.model","llm.model","model",+ # Two instrumentors reporting one call carry the same provider response ID.+ "gen_ai.response.id",)diff --git a/overbae/services/assistant/tools.py b/overbae/services/assistant/tools.pyindex 68eb2576..593f14da 100644--- a/overbae/services/assistant/tools.py+++ b/overbae/services/assistant/tools.py@@ -137,15 +137,20 @@ OWN_TOOLS = {class EvalSetDraft(BaseModel):- """Draft an eval set for the person to review. Nothing is saved: they edit the criteria,- then save or reject it, and their reply says which, with the new set's id. To change a- set, pass its id as `eval_set`: saving makes a new set, so earlier runs stay comparable.- Draft only in reply to a person's message."""+ """Show a proposed eval set to the person. They edit the criteria, then save or reject+ it, and their reply says which, with the new set's id. To change a set, pass its id as+ `eval_set`: saving makes a new set, so earlier runs stay comparable. Draft only in reply+ to a person's message."""model_config = ConfigDict(extra="forbid")name: str = Field(min_length=1, max_length=255)- description: str = Field(default="", max_length=2000)+ description: str = Field(+ default="",+ max_length=2000,+ description="What the set measures and on which data. Saved with the set as written: "+ "leave out that it is a draft or under review.",+ )criteria: list[EvalCriterionContract] = Field(min_length=1, max_length=200)eval_set: uuid.UUID | None = Nonediff --git a/overbae/services/assistant/turn.py b/overbae/services/assistant/turn.pyindex a71c3fd0..57a768a0 100644--- a/overbae/services/assistant/turn.py+++ b/overbae/services/assistant/turn.py@@ -196,8 +196,7 @@ def _begin(thread_id) -> tuple[AssistantThread | None, bool]:.select_related("project", "experiment").get(pk=thread_id))- if thread.experiment is None or thread.experiment.deleted_at is not None:- # A deleted experiment's turn ends; a thread without one has no subject.+ if thread.experiment.deleted_at is not None:if thread.state == State.RUNNING:_interrupt(thread)return None, Falsediff --git a/overbae/services/datasets/measure.py b/overbae/services/datasets/measure.pyindex 78c5d87b..2de2bd1a 100644--- a/overbae/services/datasets/measure.py+++ b/overbae/services/datasets/measure.py@@ -96,9 +96,7 @@ def describe_frame(keys.close()null_rates = store.null_rates(path)fingerprint = store.file_sha256(path)- stats = statistics.result()- if analytics.decisions:- stats["analytics"] = {**analytics.report(), "fingerprint": fingerprint}+ stats = {**statistics.result(), "analytics": {**analytics.report(), "fingerprint": fingerprint}}return dict(state=Cell.State.OK,error="",diff --git a/overbae/services/decision_providers.py b/overbae/services/decision_providers.pyindex cf4f4b41..e0bafbfc 100644--- a/overbae/services/decision_providers.py+++ b/overbae/services/decision_providers.py@@ -305,7 +305,8 @@ def usage(plan, participant, role):entries = DecisionProviderRequest.objects.filter(plan=plan, participant=participant, role=role)counts = dict(entries.values("state").annotate(count=Count("id")).values_list("state", "count"))measured = 0.0- unknown = tokens = 0+ unknown = 0+ tokens = 0for entry in entries.only("usage", "attempts").iterator():attempts = entry.attempts or [{"usage": entry.usage}]for attempt in attempts:@@ -313,7 +314,9 @@ def usage(plan, participant, role):cost = stats.get("response_cost")measured += cost or 0unknown += cost is None- tokens += (stats.get("prompt_tokens") or 0) + (stats.get("completion_tokens") or 0)+ pair = (stats.get("prompt_tokens"), stats.get("completion_tokens"))+ # One attempt without a reported count makes the total unknown, not smaller.+ tokens = None if tokens is None or None in pair else tokens + sum(pair)return {"requests": counts,"recorded_cost_usd": measured,diff --git a/overbae/services/deployment.py b/overbae/services/deployment.pyindex 52b1bf06..ecbb5f37 100644--- a/overbae/services/deployment.py+++ b/overbae/services/deployment.py@@ -304,6 +304,14 @@ def retry_baseline_deployments(job: FinetuningJob) -> None:_reset(row)+def stop_for_cancelled_job(job_id) -> None:+ """The controller stops the deployment and its remote call on its next tick, not after a+ backoff."""+ DeployedModel.objects.filter(finetuning_job_id=job_id, status__in=ACTIVE_STATUSES).update(+ deployment_next_poll_at=timezone.now()+ )++def retry_deployment(deployment_id) -> DeployedModel:with transaction.atomic():job_id = DeployedModel.objects.values_list("finetuning_job_id", flat=True).get(@@ -658,14 +666,16 @@ def _save(deployed: DeployedModel, **values) -> bool:def _finish(deployed: DeployedModel, *, error: str = "") -> None:now = timezone.now()+ status = "failed" if error else "ready"with transaction.atomic():if deployed.finetuning_job_id:job = FinetuningJob.objects.select_for_update().get(pk=deployed.finetuning_job_id)if job.status in ("failed", "cancelled"):error = "Deployment stopped: training job is " + job.status + "."+ status = job.status_save(deployed,- status="failed" if error else "ready",+ status=status,status_changed_at=now,error_message=error,deployment_dispatching=deployed.deployment_dispatching or not deployed.deployment_stage,@@ -980,7 +990,7 @@ def advance_deployment(deployment_id) -> None:).update(deployment_call_id=call_id,deployment_dispatching=False,- deployment_cancel_pending=Q(status__in=("failed", "deleting", "deleted")),+ deployment_cancel_pending=Q(status__in=("failed", "cancelled", "deleting", "deleted")),)except Exception:logger.exception(diff --git a/overbae/services/experiments/document.py b/overbae/services/experiments/document.pyindex 5853c5df..ee55ba97 100644--- a/overbae/services/experiments/document.py+++ b/overbae/services/experiments/document.py@@ -9,6 +9,7 @@ A saved revision may be unfinished; ``problems`` lists what a run needs first.""import mathimport re+import uuidfrom copy import deepcopyfrom overbae.core.errors import InputValidationError@@ -140,6 +141,7 @@ def _node(raw) -> dict:inputs = raw.get("inputs") or {}if not isinstance(settings, dict) or not isinstance(inputs, dict):_refuse(f"{node_id}: settings and inputs are JSON objects.")+ _settings(node_id, KINDS[kind], settings)bound = {}for port, sources in inputs.items():sources = [sources] if isinstance(sources, str) else sources@@ -165,6 +167,53 @@ def _node(raw) -> dict:}+SETTING_TYPES = {+ "string": ("text", lambda v: isinstance(v, str)),+ "number": ("a number", lambda v: isinstance(v, int | float) and not isinstance(v, bool)),+ "integer": ("a whole number", lambda v: isinstance(v, int) and not isinstance(v, bool)),+ "boolean": ("true or false", lambda v: isinstance(v, bool)),+ "object": ("a JSON object", lambda v: isinstance(v, dict)),+ "array": ("a list", lambda v: isinstance(v, list)),+}+++def _settings(node_id: str, kind, settings: dict) -> None:+ """Each setting against the catalogue's schema. A missing setting is left to ``problems``,+ so a draft saves; null and blank text mean unset, and a ``$parameter`` is typed by its+ parameter."""+ for key, value in settings.items():+ if key not in kind.settings:+ _refuse(f"{node_id}: {kind.label} has no setting {key}.")+ _setting(node_id, key, value, kind.settings[key])+++def _setting(node_id: str, path: str, value, schema: dict) -> None:+ if value is None or value == "" or (isinstance(value, dict) and set(value) == {"$parameter"}):+ return+ noun, check = SETTING_TYPES[schema["type"]]+ if not check(value):+ _refuse(f"{node_id}: {path} takes {noun}.")+ if "enum" in schema and value not in schema["enum"]:+ _refuse(f"{node_id}: {path} is one of {', '.join(map(str, schema['enum']))}.")+ if "minimum" in schema and value < schema["minimum"]:+ _refuse(f"{node_id}: {path} is at least {schema['minimum']}.")+ if "maximum" in schema and value > schema["maximum"]:+ _refuse(f"{node_id}: {path} is at most {schema['maximum']}.")+ if "maxItems" in schema and len(value) > schema["maxItems"]:+ _refuse(f"{node_id}: {path} lists at most {schema['maxItems']}.")+ if schema.get("format") == "uuid":+ try:+ uuid.UUID(value)+ except ValueError:+ _refuse(f"{node_id}: {path} takes an id.")+ for index, item in enumerate(value) if "items" in schema else ():+ _setting(node_id, f"{path}[{index}]", item, schema["items"])+ for key, item in value.items() if "properties" in schema else ():+ if key not in schema["properties"]:+ _refuse(f"{node_id}: {path} has no setting {key}.")+ _setting(node_id, f"{path}.{key}", item, schema["properties"][key])++def upstream(node) -> list[str]:return [binding(source)[0] for sources in node["inputs"].values() for source in sources]@@ -192,9 +241,16 @@ def order(nodes) -> list[dict]:return out-def _holdout(nodes, by_id) -> None:- """The final holdout is read once, by a qualify stage that nothing trains or selects- after."""+def holdout(document: dict, pinned: dict[str, str]) -> None:+ """The holdout rule over Data stages that pin a final holdout too: ``pinned`` maps+ each such stage to its version, which only the database knows."""+ _holdout(document["nodes"], {node["id"]: node for node in document["nodes"]}, pinned)+++def _holdout(nodes, by_id, pinned=None) -> None:+ """A final holdout, a Partition's or one a Data stage pins, is read once, by a qualify+ stage that nothing trains or selects after."""+ pinned = pinned or {}downstream: dict[str, set[str]] = {node["id"]: set() for node in nodes}for node in nodes:for source in upstream(node):@@ -207,22 +263,25 @@ def _holdout(nodes, by_id) -> None:after(child, seen)return seen+ def read(ref):+ source, port = binding(ref)+ if by_id[source]["kind"] == "split" and port == "final":+ return f"{source}'s final holdout"+ if source in pinned:+ return f"the final holdout {pinned[source]}"+ return None+readers: dict[str, str] = {}for node in nodes:- splits = {- binding(ref)[0]- for sources in node["inputs"].values()- for ref in sources- if by_id[binding(ref)[0]]["kind"] == "split" and binding(ref)[1] == "final"- }- if not splits:+ holdouts = {read(ref) for sources in node["inputs"].values() for ref in sources} - {None}+ if not holdouts:continueif node["kind"] != "qualify":_refuse(f"{node['id']}: only a Qualify stage reads the final holdout.")- for split in splits:- if split in readers:- _refuse(f"{node['id']}: {readers[split]} already reads {split}'s final holdout.")- readers[split] = node["id"]+ for name in holdouts:+ if name in readers:+ _refuse(f"{node['id']}: {readers[name]} already reads {name}.")+ readers[name] = node["id"]later = [by_id[i] for i in after(node["id"], set())]selecting = next((n for n in later if n["kind"] in SELECTING), None)if selecting is not None:diff --git a/overbae/services/experiments/records.py b/overbae/services/experiments/records.pyindex f76d0498..3ceff74a 100644--- a/overbae/services/experiments/records.py+++ b/overbae/services/experiments/records.py@@ -18,7 +18,7 @@ from overbae.models import (ExperimentRun,ExperimentStep,)-from overbae.services.datasets import events+from overbae.services.datasets import events, partition_plansfrom overbae.services.experiments import document as flowfrom overbae.services.experiments.stages import data_value@@ -124,6 +124,19 @@ def dataset_links(project_id) -> dict[str, dict]:return links+def pinned_holdouts(document: dict, settings: dict | None = None) -> dict[str, str]:+ """The Data stages that pin a final holdout, by stage id: from the saved settings, or+ from a run's resolved ``settings``."""+ pins = {}+ for node in document["nodes"]:+ if node["kind"] == "data":+ cell = (settings or {}).get(node["id"], node["settings"]).get("cell")+ if isinstance(cell, str) and (found := _uuids([cell])):+ pins[node["id"]] = str(found[0])+ sealed = set(map(str, partition_plans.sealed(pins.values())))+ return {node: cell for node, cell in pins.items() if cell in sealed}++def run_tree(roots) -> list:"""The runs and every child run their stages started, at any depth: a child run ofanother experiment's flow is still this work's."""@@ -262,6 +275,7 @@ def revise(if fingerprint(_unmarked(prior.document)) != fingerprint(_unmarked(normalized)):raise InputValidationError("This request key identifies a different save.")return prior+ flow.holdout(normalized, pinned_holdouts(normalized))if held.version != expected_version:raise InputValidationError(f"Revision {held.version} was saved after revision {expected_version}. "diff --git a/overbae/services/experiments/runs.py b/overbae/services/experiments/runs.pyindex e0214092..2ae08b99 100644--- a/overbae/services/experiments/runs.py+++ b/overbae/services/experiments/runs.py@@ -98,7 +98,9 @@ def plan()raise InputValidationError(f"Finish the flow first. {listed}")values = flow.run_parameters(document, parameters or {})- identities = _identities(document, _settings(experiment.project, document, values))+ settings = _settings(experiment.project, document, values)+ flow.holdout(document, records.pinned_holdouts(document, settings))+ identities = _identities(document, settings)unknown = set(rerun_from) - {node["id"] for node in document["nodes"]}if unknown:raise InputValidationError(f"There is no stage {sorted(unknown)[0]} to rerun from.")diff --git a/overbae/services/inference_live.py b/overbae/services/inference_live.pyindex 171d8478..99a34f54 100644--- a/overbae/services/inference_live.py+++ b/overbae/services/inference_live.py@@ -32,12 +32,13 @@ def worker_status(deployed: DeployedModel) -> dict:stats = live_worker_stats(deployed)state = "unknown"if deployed.status == "ready":- if stats["recently_active"]:- state = "warm"+ # Measured runners outrank recent requests: the pool may have scaled down since.+ if stats["available"] and stats["num_total_runners"] is not None:+ state = "warm" if stats["num_total_runners"] > 0 else "asleep"elif stats["warming"]:state = "warming"- elif stats["available"] and stats["num_total_runners"] is not None:- state = "warm" if stats["num_total_runners"] > 0 else "asleep"+ elif stats["recently_active"]:+ state = "warm"return {"state": state, **stats}diff --git a/overbae/services/mcp/__init__.py b/overbae/services/mcp/__init__.pyindex eaa74a32..045ffdd7 100644--- a/overbae/services/mcp/__init__.py+++ b/overbae/services/mcp/__init__.py@@ -1,3 +1,3 @@"""MCP protocol and catalog services."""-CONTRACT_VERSION = "12.5.0"+CONTRACT_VERSION = "12.6.0"diff --git a/overbae/services/mcp/annotations.py b/overbae/services/mcp/annotations.pyindex 03efe181..aaf6413e 100644--- a/overbae/services/mcp/annotations.py+++ b/overbae/services/mcp/annotations.py@@ -9,11 +9,22 @@ from mcp.types import ToolAnnotationsif TYPE_CHECKING:from overbae.services.mcp.catalog import ToolDefinition+# The MCP specification's value for an omitted hint; the manifest leaves those out.+SPEC_DEFAULTS = {+ "readOnlyHint": False,+ "destructiveHint": True,+ "idempotentHint": False,+ "openWorldHint": True,+}+def annotations_for(definition: ToolDefinition) -> ToolAnnotations:+ hints = {+ "readOnlyHint": definition.read_only,+ "destructiveHint": definition.destructive,+ "idempotentHint": definition.idempotent,+ "openWorldHint": definition.open_world,+ }return ToolAnnotations(- readOnlyHint=definition.read_only,- destructiveHint=definition.destructive,- idempotentHint=definition.idempotent,- openWorldHint=definition.open_world,+ **{key: value for key, value in hints.items() if value != SPEC_DEFAULTS[key]})diff --git a/overbae/services/mcp/catalog.py b/overbae/services/mcp/catalog.pyindex 3c72bc0e..ba2bb990 100644--- a/overbae/services/mcp/catalog.py+++ b/overbae/services/mcp/catalog.py@@ -133,7 +133,6 @@ class ToolDefinition(BaseModel):"type": "string","minLength": 1,"maxLength": 128,- "description": "An identical retry after completion returns the stored result.",}if self.project_scoped:schema.setdefault("properties", {})["project_id"] = {@@ -149,27 +148,67 @@ class ToolDefinition(BaseModel):)-def _compact_schema(value: Any) -> Any:+def _compact_schema(schema: dict[str, Any]) -> dict[str, Any]:+ """Inline single-use $defs and fold nullable anyOf pairs; validation stays identical."""+ defs = schema.get("$defs", {})+ uses = dict.fromkeys(defs, 0)+ _count_refs(schema, uses)+ inline = {name for name, count in uses.items() if count == 1}+ compacted = _compact_node({k: v for k, v in schema.items() if k != "$defs"}, defs, inline)+ shared = {name: _compact_node(defs[name], defs, inline) for name in defs if name not in inline}+ if shared:+ compacted["$defs"] = shared+ return compacted+++def _count_refs(value: Any, uses: dict[str, int]) -> None:+ if isinstance(value, list):+ for item in value:+ _count_refs(item, uses)+ elif isinstance(value, dict):+ name = _def_name(value.get("$ref"))+ if name in uses:+ uses[name] += 1+ for item in value.values():+ _count_refs(item, uses)+++def _def_name(ref: Any) -> str | None:+ if isinstance(ref, str) and ref.startswith("#/$defs/"):+ return ref.removeprefix("#/$defs/")+ return None+++def _compact_node(value: Any, defs: dict[str, Any], inline: set[str]) -> Any:if isinstance(value, list):- return [_compact_schema(item) for item in value]+ return [_compact_node(item, defs, inline) for item in value]if not isinstance(value, dict):return value- compacted = {- key: _compact_schema(item) for key, item in value.items() if key not in _SCHEMA_NOISE_KEYS- }+ name = _def_name(value.get("$ref"))+ if name in inline:+ siblings = {key: item for key, item in value.items() if key != "$ref"}+ value = {**defs[name], **siblings}++ compacted: dict[str, Any] = {}+ for key, item in value.items():+ if key in _SCHEMA_NOISE_KEYS or (key == "additionalProperties" and item is True):+ continue+ if key in {"properties", "$defs"}:+ compacted[key] = {+ field: _compact_node(child, defs, inline) for field, child in item.items()+ }+ else:+ compacted[key] = _compact_node(item, defs, inline)+any_of = compacted.get("anyOf")- if isinstance(any_of, list) and len(any_of) == 2:- null_schema = next((item for item in any_of if item == {"type": "null"}), None)- value_schema = next((item for item in any_of if item != {"type": "null"}), None)- if (- null_schema is not None- and isinstance(value_schema, dict)- and isinstance(value_schema.get("type"), str)- ):+ if isinstance(any_of, list) and len(any_of) == 2 and {"type": "null"} in any_of:+ value_schema = next(item for item in any_of if item != {"type": "null"})+ if isinstance(value_schema, dict) and isinstance(value_schema.get("type"), str):compacted.pop("anyOf")- compacted.update(value_schema)- compacted["type"] = [value_schema["type"], "null"]+ compacted = {**value_schema, **compacted, "type": [value_schema["type"], "null"]}+ if "enum" in value_schema:+ compacted["enum"] = [*value_schema["enum"], None]return compacteddiff --git a/overbae/services/mcp/contracts/training_monitoring.py b/overbae/services/mcp/contracts/training_monitoring.pyindex 811056f3..f218b0a5 100644--- a/overbae/services/mcp/contracts/training_monitoring.py+++ b/overbae/services/mcp/contracts/training_monitoring.py@@ -6,7 +6,7 @@ from overbae.services.mcp.contracts.common import MCPModelclass GenerationProbe(MCPModel):- kind: Literal["classification", "exact_match", "json_schema", "json_fields"]+ kind: Literal["classification", "exact_match", "json_schema", "json_fields", "tool_calls"]labels: list[str] | None = Nonesample: StrictInt = Field(default=256, ge=1, le=10000)max_new_tokens: StrictInt = Field(default=128, ge=1, le=4096)@@ -35,6 +35,6 @@ class TrainingMonitoringPolicy(MCPModel):max_checks: StrictInt = Field(default=12, ge=1, le=100)generation_every: StrictInt = Field(default=3, ge=1, le=100)generation: GenerationProbe | None = None- selection: Literal["last", "development_loss"] = "last"+ selection: Literal["last", "development_loss", "generation"] = "last"early_stopping: EarlyStopPolicy | None = Nonefailure_policy: Literal["continue", "stop"] | None = Nonediff --git a/overbae/services/mcp/prompts.py b/overbae/services/mcp/prompts.pyindex 791caa62..f22d9335 100644--- a/overbae/services/mcp/prompts.py+++ b/overbae/services/mcp/prompts.py@@ -285,6 +285,7 @@ PROMPTS = ("Choose one monitoring policy for readiness, estimate, preparation and launch. ""Declare task-specific generation labels, schema or json_fields JSON Pointers from evidence; the platform does not invent a rubric. ""json_fields compares only the declared fields against retained JSON references; missing references are unscorable, not model failures. "+ "For tool-use data, tool_calls scores the first tool call's name and argument validity; selection=generation keeps the checkpoint with the best probe pass rate. ""Use inspect_training_progress for passive check, coverage, failure and checkpoint inspection. ""Page native per-question collections using their field JSON Pointers; append escaped keys or indices for nested retained values. ""get_job retains latest_generation_check independently of newer loss-only checks. "diff --git a/overbae/services/mcp/server.py b/overbae/services/mcp/server.pyindex 7fe9d799..179ebcd6 100644--- a/overbae/services/mcp/server.py+++ b/overbae/services/mcp/server.py@@ -76,7 +76,7 @@ mcp_server = Server("The Console has its own assistant that uses these same tools; it never acts for an MCP connection. Retain scripts automatically with save_dataset_pipeline(dataset=..., package=...); never ask users whether to keep them. Retain scoped uncertainties and their evidence in the script and output; successful formatting and execution do not establish suitability. Discover reusable project revisions with inspect_dataset_workbench; prefer reuse or an attributed derived_from variant. Upload original source bytes once, pin upstream dataset revisions, and retain transformation code before full-data processing. Never upload locally transformed derivatives as unrelated source datasets. New transformations require a retained Python package; package-free historical revisions are read-only. Upload scripts using overmind dataset pipeline-upload, register with save_dataset_pipeline, validate_dataset_pipeline, preview then run_dataset_pipeline. Each successful run replaces the displayed preparation with its selected end-to-end process. Corrections update the same recipe family and rerun from its original source; do not append repair cells or create prepared-v2 datasets. Pinned consumer inputs remain immutable internally. Enable saved source bindings explicitly for repeated snapshot rebuilds. import_dataset_version is for genuine external results, not a substitute for retaining transformation code. ""When asked to prepare data in Overmind, local files alone are not completion: publish and inspect the requested dataset or report an explicit blocker. Inspect the named capability's contract and examples before choosing target semantics; link it explicitly. Preserve unknown meaning rather than inventing task labels. Separate meaningful preparation stages and review branches from final formatting. Use the returned upload argv and identifiers verbatim, replacing only documented placeholders. ""Declare the final step consumer (decision_train, decision_eval, chat_train or model_eval) so previews validate nested targets. Use batch_rows only for row-independent steps; sorting, grouping and deduplication require the full population. Preserve evidenced target semantics and structured provenance; never remove them to bypass a validator. Preview defers absolute min_rows/max_rows bounds to publication; lineage and preserve_rows checks remain enforced. Inspect deferred checks before publishing. Follow poll_after_seconds; queued work alone is not a failure or reason to resubmit. Report format compatibility separately from task suitability, which remains unmeasured without attributable evidence. "- "Author explicit step IDs and input dependencies. Converge intended branches with inputs=[earlier IDs]; disjoint rows concatenate in declared order, overlapping source_row identities fail. The last step is the output: inspect flow.unconsumed_steps before publication. Training preparation should end in trainable examples with review metadata, not disconnected inspection tables; never invent targets or treat flags as resolved. Script conditions cite their entrypoint line and describe code, not independently verified semantics. Receipts record actual parent cells, counts and fingerprints. Pin sources and use stable request keys. "+ "Author explicit step IDs and input dependencies. Converge intended branches with inputs=[earlier IDs]; disjoint rows concatenate in declared order, overlapping source_row identities fail. The last step is the output: inspect flow.unconsumed_steps before publication. Training preparation should end in trainable examples with review metadata, not disconnected inspection tables; never invent targets or treat flags as resolved. Script conditions cite their entrypoint line and describe code, not independently verified semantics. Receipts record actual parent cells, counts and fingerprints. Pin sources and use stable request keys: an identical retry with a mutation's request_key returns its stored result once the first call finishes; until then it returns request_in_progress, so never resubmit under a new key. ""Use author-dataset-transformation for conditional authoring, retrieval and adaptation. inspect_dataset_workbench(pipeline=revision ID) retrieves an exact recipe and its family history. Only retained packages execute in the approved isolated runtime; other code and semantic/provider work stay in the native environment. Technical format checks do not prove semantic quality or exhaustive/exclusive branches. ""When submit_feedback is listed and an Overmind operation fails, contradicts its ""description or needs repeated attempts, report it once with submit_feedback. "diff --git a/overbae/services/sft_assets/training_monitor.py b/overbae/services/sft_assets/training_monitor.pyindex 5cd1a9d8..7176a231 100644--- a/overbae/services/sft_assets/training_monitor.py+++ b/overbae/services/sft_assets/training_monitor.py@@ -17,9 +17,11 @@ from transformers import TrainerCallbackfrom modal_shared.training_monitoring import (fingerprint,+ first_tool_call,generation_tokens,resolve_policy,score_json_fields,+ score_tool_call,)from modal_shared.training_monitoring_runtime import Monitor, atomic_jsonfrom modal_shared.training_telemetry import read_telemetry, record_stage@@ -204,61 +206,13 @@ class TrainingMonitorCallback(TrainerCallback):return metricsdef generate(self, indices):- policy = self.policy["generation"]- model = self.trainer.model- device = model.get_input_embeddings().weight.deviceexamples = []- eos_ids = model.generation_config.eos_token_id or self.tokenizer.eos_token_id- eos_ids = {eos_ids} if isinstance(eos_ids, int) else set(eos_ids or [])for ordinal, index in enumerate(indices):row = self.development_rows[index]record = {"row": index, "key": row["key"], "status": "failed"}started = time.monotonic()try:- prompt, answer = generation_tokens(row)- if len(prompt) + policy["max_new_tokens"] > int(os.environ["MAX_LENGTH"]):- raise ValueError("Generation output reservation exceeds the pinned context")- tensor = torch.tensor([prompt], dtype=torch.long, device=device)- with torch.inference_mode():- output = model.generate(- input_ids=tensor,- attention_mask=torch.ones_like(tensor),- max_new_tokens=policy["max_new_tokens"],- do_sample=False,- pad_token_id=self.tokenizer.pad_token_id,- use_cache=True,- )- tokens = output[0, len(prompt) :].tolist()- output_text = self.tokenizer.decode(tokens, skip_special_tokens=True)- reference = self.tokenizer.decode(answer, skip_special_tokens=True)- prediction = normalize_output(output_text, policy["normalization"])- reference = normalize_output(reference, policy["normalization"])- finish_reason = "stop" if tokens and tokens[-1] in eos_ids else "length"- record.update(- input=self.tokenizer.decode(prompt),- output=output_text,- reference=reference,- prediction=prediction,- input_tokens=len(prompt),- output_tokens=len(tokens),- finish_reason=finish_reason,- status="completed" if finish_reason == "stop" else "failed",- )- if finish_reason != "stop":- record["error"] = {- "code": "output_limit",- "message": "Generation exhausted its output reservation",- }- if policy["kind"] == "exact_match":- record["passed"] = prediction == reference- elif policy["kind"] == "json_schema":- try:- jsonschema.validate(json.loads(prediction), policy["schema"])- record["passed"] = True- except (json.JSONDecodeError, jsonschema.ValidationError):- record["passed"] = False- elif policy["kind"] == "json_fields":- record.update(score_json_fields(prediction, reference, policy["fields"]))+ self.generate_example(row, record)except Exception as exc:record["error"] = {"code": type(exc).__name__, "message": str(exc)}record["latency_seconds"] = time.monotonic() - started@@ -272,6 +226,71 @@ class TrainingMonitorCallback(TrainerCallback):)return examples+ def generate_example(self, row, record):+ policy = self.policy["generation"]+ model = self.trainer.model+ tool_calls = policy["kind"] == "tool_calls"+ # Tool-call markup can be special tokens, and the scorer reads it.+ skip_special = not tool_calls+ if tool_calls:+ found = first_tool_call(+ row, lambda ids: self.tokenizer.decode(ids, skip_special_tokens=False)+ )+ if found is None:+ record.update(status="completed", **score_tool_call("", None))+ return+ prompt, answer, reference_call = found+ else:+ prompt, answer = generation_tokens(row)+ if len(prompt) + policy["max_new_tokens"] > int(os.environ["MAX_LENGTH"]):+ raise ValueError("Generation output reservation exceeds the pinned context")+ eos_ids = model.generation_config.eos_token_id or self.tokenizer.eos_token_id+ eos_ids = {eos_ids} if isinstance(eos_ids, int) else set(eos_ids or [])+ device = model.get_input_embeddings().weight.device+ tensor = torch.tensor([prompt], dtype=torch.long, device=device)+ with torch.inference_mode():+ output = model.generate(+ input_ids=tensor,+ attention_mask=torch.ones_like(tensor),+ max_new_tokens=policy["max_new_tokens"],+ do_sample=False,+ pad_token_id=self.tokenizer.pad_token_id,+ use_cache=True,+ )+ tokens = output[0, len(prompt) :].tolist()+ output_text = self.tokenizer.decode(tokens, skip_special_tokens=skip_special)+ reference = self.tokenizer.decode(answer, skip_special_tokens=skip_special)+ prediction = normalize_output(output_text, policy["normalization"])+ reference = normalize_output(reference, policy["normalization"])+ finish_reason = "stop" if tokens and tokens[-1] in eos_ids else "length"+ record.update(+ input=self.tokenizer.decode(prompt),+ output=output_text,+ reference=reference,+ prediction=prediction,+ input_tokens=len(prompt),+ output_tokens=len(tokens),+ finish_reason=finish_reason,+ status="completed" if finish_reason == "stop" else "failed",+ )+ if finish_reason != "stop":+ record["error"] = {+ "code": "output_limit",+ "message": "Generation exhausted its output reservation",+ }+ if policy["kind"] == "exact_match":+ record["passed"] = prediction == reference+ elif policy["kind"] == "json_schema":+ try:+ jsonschema.validate(json.loads(prediction), policy["schema"])+ record["passed"] = True+ except (json.JSONDecodeError, jsonschema.ValidationError):+ record["passed"] = False+ elif policy["kind"] == "json_fields":+ record.update(score_json_fields(prediction, reference, policy["fields"]))+ elif tool_calls:+ record.update(score_tool_call(prediction, reference_call))+def reload_checkpoint(self, directory):model = self.trainer.modelif hasattr(model, "peft_config"):@@ -347,9 +366,9 @@ class TrainingMonitorCallback(TrainerCallback):selected = next((item for item in self.monitor.data["checkpoints"] if item.get("selected")), None)- if self.policy["selection"] == "development_loss":+ if self.policy["selection"] != "last":if selected is None:- raise ValueError("Development checkpoint selection has no verified checkpoint")+ raise ValueError("Checkpoint selection has no verified, scored checkpoint")self.reload_checkpoint(self.run_dir / selected["manifest"]["path"])if self.policy["final"]:self.run_check(selected["step"] if selected else state.global_step, final=True)diff --git a/overbae/services/training_cancellation.py b/overbae/services/training_cancellation.pyindex a9ece6b4..e605b202 100644--- a/overbae/services/training_cancellation.py+++ b/overbae/services/training_cancellation.py@@ -5,7 +5,7 @@ from django.utils import timezonefrom overbae.celery import app as celery_appfrom overbae.models import FinetuningJob, FinetuningJobEvent-from overbae.services import training_monitoring+from overbae.services import deployment, training_monitoring, training_preparationfrom overbae.services.activity import asset, record, update_taskfrom overbae.services.finetuning_eval import cancel_related_evalsfrom overbae.services.finetuning_runner import get_runner@@ -56,6 +56,8 @@ def cancel(job):error_message=f"Cancelled (remote cancel warning: {remote_error})")job.refresh_from_db()+ training_preparation.cancel_for_job(job)+ deployment.stop_for_cancelled_job(job.pk)training_monitoring.interrupt(job, reason="cancelled")if job.remote_job_id:# Import after service initialization: the task imports the shared training lifecycle.diff --git a/overbae/services/training_preparation.py b/overbae/services/training_preparation.pyindex faa4630e..ec702566 100644--- a/overbae/services/training_preparation.py+++ b/overbae/services/training_preparation.py@@ -4,6 +4,7 @@ import gzipimport hashlibimport ioimport json+import loggingimport mathimport tempfileimport uuid@@ -44,6 +45,14 @@ from overbae.services.finetuning_policy import (from overbae.services.finetuning_validator import row_to_finetuning_linefrom overbae.services.training_contract import dataset_objective+logger = logging.getLogger(__name__)++FINISHED_JOBS = (+ FinetuningJob.Status.SUCCEEDED,+ FinetuningJob.Status.FAILED,+ FinetuningJob.Status.CANCELLED,+)+def processor_fingerprint():return asset_fingerprint(Path(__file__).parent / "sft_assets")@@ -127,9 +136,58 @@ def request_preparation("deadline": timezone.now() + timedelta(hours=24),},)+ if preparation.state == "cancelled":+ if preparation.remote_id and not stop_remote(preparation):+ raise InputValidationError(+ "The cancelled preprocessing call has not stopped yet. Try again shortly."+ )+ # A cancelled preparation stopped its remote call; a new request starts it again.+ TrainingPreparation.objects.filter(pk=preparation.pk, state="cancelled").update(+ state="queued",+ remote_id="",+ report={},+ error="",+ deadline=timezone.now() + timedelta(hours=24),+ touched_at=timezone.now(),+ )+ preparation.refresh_from_db()return preparation+def cancel_for_job(job) -> TrainingPreparation | None:+ """Stops the job's preparation and its remote call, unless another live job waits on it."""+ if not job.preparation_id:+ return None+ with transaction.atomic():+ prep = TrainingPreparation.objects.select_for_update().get(pk=job.preparation_id)+ waiting = prep.training_jobs.exclude(pk=job.pk).exclude(status__in=FINISHED_JOBS).exists()+ if prep.state not in {"queued", "starting", "running"} or waiting:+ return None+ prep.state = "cancelled"+ prep.save(update_fields=["state", "touched_at"])+ if prep.remote_id:+ stop_remote(prep)+ operational_progress.preparation(prep)+ return prep+++def stop_remote(prep) -> bool:+ """Cancels a cancelled preparation's remote call and forgets it once Modal acknowledges.+ An unacknowledged cancel keeps the call id, so the reconciler tries again."""+ try:+ modal.FunctionCall.from_id(prep.remote_id).cancel()+ except NotFoundError:+ pass+ except Exception:+ logger.warning("Preparation %s remote cancel was not acknowledged", prep.pk)+ return False+ TrainingPreparation.objects.filter(+ pk=prep.pk, state="cancelled", remote_id=prep.remote_id+ ).update(remote_id="")+ prep.remote_id = ""+ return True++def retry_preparation(preparation):if preparation.state != "failed" or not preparation.report.get("retryable"):raise InputValidationError("This preprocessing operation cannot be retried safely.")@@ -154,7 +212,7 @@ def retry_preparation(preparation):def begin_preparation(cell, model, context_length, *, user, **kwargs):Project.objects.select_for_update().get(pk=cell.dataset.project_id)prep = request_preparation(cell, model, context_length, **kwargs)- if not prep.training_jobs.exists():+ if not prep.training_jobs.exclude(status=FinetuningJob.Status.CANCELLED).exists():FinetuningJob.objects.create(project_id=prep.cell.dataset.project_id,dataset=prep.cell.dataset,@@ -362,7 +420,9 @@ def advance(preparation_id):.select_related("cell", "validation_cell").get(pk=preparation_id))- if prep.state in {"ready", "incompatible", "failed"}:+ if prep.state in {"ready", "incompatible", "failed", "cancelled"}:+ if prep.state == "cancelled" and prep.remote_id:+ stop_remote(prep)returnif prep.deadline <= now:prep.report = {"retryable": prep.state == "queued" or bool(prep.remote_id)}@@ -491,9 +551,11 @@ def advance(preparation_id):call = function.spawn(str(prep.id), {**prep.config, "rows_path": "/data" + remote, "rows_sha256": digest})- TrainingPreparation.objects.filter(+ if not TrainingPreparation.objects.filter(pk=prep.pk, state="starting", attempt=prep.attempt- ).update(state="running", remote_id=call.object_id, touched_at=timezone.now())+ ).update(state="running", remote_id=call.object_id, touched_at=timezone.now()):+ # Cancelled during submission: nothing else holds this call's ID.+ call.cancel()else:report = validate_preparation_report(modal.FunctionCall.from_id(prep.remote_id).get(timeout=0)diff --git a/overbae/tasks/training_preparation.py b/overbae/tasks/training_preparation.pyindex 5f6f6030..58f0eeba 100644--- a/overbae/tasks/training_preparation.py+++ b/overbae/tasks/training_preparation.py@@ -1,4 +1,5 @@from celery import shared_task+from django.db.models import Qfrom overbae.models import TrainingPreparationfrom overbae.services import operational_progress@@ -7,9 +8,11 @@ from overbae.services.training_preparation import advance, sync_setup_jobs@shared_taskdef reconcile():- for preparation in TrainingPreparation.objects.filter(- state__in=["queued", "starting", "running"]- ).values_list("id", flat=True)[:100]:+ live = Q(state__in=["queued", "starting", "running"])+ unstopped = Q(state="cancelled") & ~Q(remote_id="")+ for preparation in TrainingPreparation.objects.filter(live | unstopped).values_list(+ "id", flat=True+ )[:100]:inspect_preparation.delay(str(preparation))diff --git a/overmind/CHANGELOG.md b/overmind/CHANGELOG.mdindex aaa3dcd5..c45a82c9 100644--- a/overmind/CHANGELOG.md+++ b/overmind/CHANGELOG.md@@ -6,25 +6,48 @@ entries here cover the SDK surface.## Unreleased+### Added++- `overmind experiment` drives experiments from scripts over the REST API: `list`, `show`,+ `create --flow FILE`, `revise`, `plan`, `start`, `status`, `stop` and `message`, with+ `--json` on every command. `start --watch` and `status --watch` wait for the run and exit 1 unless it+ completed; a refused save prints the platform's reason, naming the stage and setting.+- `overmind dataset list` and `overmind dataset show DATASET` read the project's datasets+ and a dataset's versions.+### Fixed+- `overmind dataset upload --wait` refuses a redirect instead of sending the API key on to+ another host.+- Refuse `overmind chassis --root` on a missing directory with a usage error, nota traceback.+- Bind saved SDK credentials to their API endpoint. `init()` disables tracingwith a warning when they meet another endpoint, and raises in strict mode.+- Preserve tool calls in SDK chat responses. `CompletionMessage.content` is`None` when the model returns only tool calls.+- Restore SDK compatibility with Python 3.10.+- Exclude freeform CLI arguments from analytics.+- Redact secret fields in traced dataclass values.+- Restore the outer conversation after an SDK run.+- Scope turn reuse to capability identity.+- Preserve captured tool call identity and arguments.+- Preserve constructor aliases in OpenRouter rewrites.+- `convert_json_to_toml` keeps the scan's `modes` and `llm_utilities` (in thecapability card, utilities under their `called_by` parent) and its`decision_logic` and `policy_markdown`; `overmind sync` sends and round-tripsthem.+- The dataset skills cancel a script run with `run`, call a stopped import`stopped`, and poll `get_job(kind=dataset_run)`. Skills version 1.5.1.diff --git a/overmind/README.md b/overmind/README.mdindex d5b13552..3d14221c 100644--- a/overmind/README.md+++ b/overmind/README.md@@ -375,6 +375,12 @@ overmind chassis [--root PATH] Record scan provenance and print the AST chaovermind dataset upload FILE Upload a local dataset and start a build(--split PERCENT lands a train and an eval dataset)overmind dataset export DATASET Download committed rows as JSONL or CSV+overmind dataset list | show DATASET+ List the project's datasets; show one with its versions+overmind experiment COMMAND list, show, create --flow FILE, revise, plan, start,+ status, stop and message an experiment+overmind run --step STEP --entry module:function+ Answer a Your-system stage's rows with your own codeovermind connector add TYPE Add a tracing connector from env or a TTY promptovermind model download-checkpoint DEPLOYMENTDownload an archived fine-tuned checkpointdiff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.pyindex f103d09e..8c513e1d 100644--- a/overmind/overmind/__init__.py+++ b/overmind/overmind/__init__.py@@ -9,7 +9,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any-__version__ = "0.1.134"+__version__ = "0.1.135"from .client import Client, ModelDeleted, OvermindInferenceErrordiff --git a/overmind/overmind/__main__.py b/overmind/overmind/__main__.pyindex 2f02ff74..f85c41cb 100644--- a/overmind/overmind/__main__.py+++ b/overmind/overmind/__main__.py@@ -6,6 +6,8 @@ Commands:chassis Print the deterministic AST digest the local scan uses as ground truth.dataset upload FILE Upload a local dataset and start a build.dataset export DATASET Download a committed dataset locally.+ dataset list | show List the project's datasets or show one with its versions.+ experiment … Create, plan, start, watch and stop experiments.connector add TYPE Add a tracing connector from env or a TTY prompt.model download-checkpoint DEPLOYMENTDownload a deployed model checkpoint locally.@@ -27,6 +29,7 @@ try:from overmind.connection_cmd import connection_appfrom overmind.connector_cmd import connector_appfrom overmind.dataset_cmd import dataset_app+ from overmind.experiment_cmd import experiment_appfrom overmind.finetune_cmd import finetune as finetune_cmdfrom overmind.init_cmd import init as init_cmdfrom overmind.model_cmd import model_app@@ -85,6 +88,7 @@ def common(app.add_typer(skills_app, name="skills")app.add_typer(dataset_app, name="dataset")+app.add_typer(experiment_app, name="experiment")app.add_typer(connection_app, name="connection")app.add_typer(connector_app, name="connector")app.add_typer(model_app, name="model")diff --git a/overmind/overmind/dataset_cmd.py b/overmind/overmind/dataset_cmd.pyindex 7a9c463a..f3d4a330 100644--- a/overmind/overmind/dataset_cmd.py+++ b/overmind/overmind/dataset_cmd.py@@ -20,6 +20,7 @@ from requests.structures import CaseInsensitiveDictfrom rich.console import Consolefrom overmind.config import DEFAULT_PATH, load+from overmind.rest import Api, ApiKey, ApiUrl, AsJson, CommandError, ConfigPath, ProjectId, emit, failfrom overmind.transfer_connection import TransferError, check_connection, request_json, resolve_transfer_connectionTRANSFER_PATH = "/api/dataset-transfers/"@@ -214,17 +215,6 @@ def _raise_for_status(response: requests.Response) -> None:raise DatasetUploadError(f"HTTP {response.status_code}: {_response_detail(response)}")-def _json(response: requests.Response, operation: str) -> dict[str, Any]:- _raise_for_status(response)- try:- payload = response.json()- except (TypeError, ValueError) as exc:- raise DatasetUploadError(f"{operation} returned invalid JSON.") from exc- if not isinstance(payload, dict):- raise DatasetUploadError(f"{operation} returned invalid JSON.")- return payload--def _required_int(payload: dict[str, Any], key: str, operation: str) -> int:value = payload.get(key)if isinstance(value, bool) or not isinstance(value, int) or value <= 0:@@ -282,11 +272,10 @@ def wait_until_ready(deadline = time.monotonic() + timeouttry:while True:- try:- response = client.get(f"{api_url.rstrip('/')}/api/datasets/{dataset_id}/", timeout=30)- except requests.RequestException as exc:- raise DatasetUploadError(f"read dataset failed: {exc}") from exc- dataset = _json(response, "read dataset")+ # Redirects are refused: the session's key would follow them to another host.+ dataset = request_json(+ client, "GET", f"{api_url.rstrip('/')}/api/datasets/{dataset_id}/", stage="read_dataset"+ )state = str(dataset.get("state") or "")if state == "error":raise DatasetUploadError(str(dataset.get("error") or "The dataset failed."))@@ -757,3 +746,53 @@ def export(meta = " ".join(f"{key}={result[key]}" for key, _header in EXPORT_HEADERS if result.get(key))if meta:console.print(meta)+++@dataset_app.command("list")+def list_datasets(+ search: Annotated[str, typer.Option("--search", help="Text the name contains")] = "",+ intent: Annotated[str, typer.Option("--intent", help="train, eval or pending")] = "",+ page: Annotated[int, typer.Option("--page", min=1, help="100 datasets a page, newest change first")] = 1,+ project_id: ProjectId = "",+ api_key: ApiKey = "",+ api_url: ApiUrl = "",+ path: ConfigPath = DEFAULT_PATH,+ as_json: AsJson = False,+) -> None:+ """List the project's datasets with their active version."""+ try:+ api = Api(api_key, api_url, path)+ params = {"project": api.project(project_id), "page": page, "page_size": 100}+ params |= {key: value for key, value in (("search", search), ("intent", intent)) if value}+ found = api.call("GET", "/api/datasets/", params=params)+ except (CommandError, OSError, ValueError) as exc:+ fail(exc, as_json)+ rows = [+ f"{item['id']} {item['name']} {item['intent']} {item['state']} "+ f"v{item['active_version'] or '-'} {item['rows']} rows"+ for item in found["results"]+ ]+ more = f"\nMore on --page {page + 1}." if found.get("next") else ""+ emit(found, ("\n".join(rows) or "No datasets.") + more, as_json)+++@dataset_app.command("show")+def show_dataset(+ dataset: Annotated[str, typer.Argument(help="Dataset id")],+ api_key: ApiKey = "",+ api_url: ApiUrl = "",+ path: ConfigPath = DEFAULT_PATH,+ as_json: AsJson = False,+) -> None:+ """Show a dataset and each of its versions."""+ try:+ found = Api(api_key, api_url, path).call("GET", f"/api/datasets/{dataset}/")+ except (CommandError, OSError, ValueError) as exc:+ fail(exc, as_json)+ lines = [f"{found['name']} ({found['id']}): {found['intent']}, {found['state']}"]+ lines += [+ f" v{cell.get('version') or '-'} {cell['id']} {cell['state']} {cell['rows']} rows"+ + (" active" if cell["id"] == found["active_cell"] else "")+ for cell in found["cells"]+ ]+ emit(found, "\n".join(lines), as_json)diff --git a/overmind/overmind/experiment_cmd.py b/overmind/overmind/experiment_cmd.pynew file mode 100644index 00000000..6f06ab9f--- /dev/null+++ b/overmind/overmind/experiment_cmd.py@@ -0,0 +1,319 @@+"""``overmind experiment``: create, plan, start, watch and stop experiments from scripts."""++from __future__ import annotations++import json+import time+import uuid+from pathlib import Path+from typing import Annotated, Any++import typer++from overmind.config import DEFAULT_PATH+from overmind.rest import Api, ApiKey, ApiUrl, AsJson, CommandError, ConfigPath, ProjectId, emit, fail++experiment_app = typer.Typer(help="Create, plan, start, watch and stop experiments.", no_args_is_help=True)++ENDED = {"completed", "unmet", "stopped"}+Params = Annotated[+ list[str] | None,+ typer.Option("--param", help="A run parameter as name=value; the value is read as JSON when it parses."),+]+++def _parameters(given: list[str] | None) -> dict[str, Any]:+ values = {}+ for item in given or []:+ name, sep, raw = item.partition("=")+ if not sep or not name:+ raise CommandError(f"Write --param as name=value, not {item!r}.", "invalid_parameter")+ try:+ values[name] = json.loads(raw)+ except ValueError:+ values[name] = raw+ return values+++def _flow(path: Path) -> dict:+ try:+ document = json.loads(path.read_text())+ except (OSError, ValueError) as exc:+ raise CommandError(f"Cannot read the flow file {path}: {exc}", "invalid_flow") from None+ if not isinstance(document, dict):+ raise CommandError("The flow file holds one JSON object: {parameters, outputs, nodes}.", "invalid_flow")+ return document+++def _plan_text(plan: dict) -> str:+ lines = [f"{entry['node']:<20} {entry['action']:<10} {entry['reason']}" for entry in plan["entries"]]+ cost = "unknown" if plan.get("cost") is None else f"${plan['cost']:.2f}"+ lines.append(f"{plan['executions']} to run, {plan['reused']} reused, cost {cost}. Plan {plan['fingerprint']}")+ return "\n".join(lines)+++def _run_text(run: dict) -> str:+ lines = [f"Run {run['number']} ({run['id']}): {run['state']}{' — ' + run['reason'] if run.get('reason') else ''}"]+ for step in run.get("steps", []):+ error = f" — {step['error']}" if step.get("error") else ""+ lines.append(f" {step['node']:<20} {step['state']}{error}")+ return "\n".join(lines)+++@experiment_app.command("list")+def list_experiments(+ search: Annotated[str, typer.Option("--search", help="Words the name contains")] = "",+ offset: Annotated[int, typer.Option("--offset", min=0)] = 0,+ project_id: ProjectId = "",+ api_key: ApiKey = "",+ api_url: ApiUrl = "",+ path: ConfigPath = DEFAULT_PATH,+ as_json: AsJson = False,+) -> None:+ """List the project's experiments, newest change first, 50 from --offset."""+ try:+ api = Api(api_key, api_url, path)+ params = {"project": api.project(project_id), "search": search, "offset": offset}+ found = api.call("GET", "/api/experiments/", params=params)+ except (CommandError, OSError, ValueError) as exc:+ fail(exc, as_json)+ rows = [+ f"{item['id']} {item['name']} v{item['version']} "+ + (f"run {item['last_run']['number']} {item['last_run']['state']}" if item.get("last_run") else "no runs")+ for item in found+ ]+ emit(found, "\n".join(rows) or "No experiments.", as_json)+++@experiment_app.command("show")+def show(+ experiment: Annotated[str, typer.Argument(help="Experiment id")],+ revision: Annotated[int | None, typer.Option("--revision", min=1, help="Defaults to the newest")] = None,+ api_key: ApiKey = "",+ api_url: ApiUrl = "",+ path: ConfigPath = DEFAULT_PATH,+ as_json: AsJson = False,+) -> None:+ """Show an experiment: its flow, what a run still needs, and its runs."""+ try:+ api = Api(api_key, api_url, path)+ params = {"revision": revision} if revision else None+ found = api.call("GET", f"/api/experiments/{experiment}/", params=params)+ except (CommandError, OSError, ValueError) as exc:+ fail(exc, as_json)+ lines = [f"{found['name']} ({found['id']}), revision {found['revision']} of {found['version']}"]+ lines += [f" {node['id']:<20} {node['kind']}" for node in found["document"]["nodes"]]+ lines += [f"Needs: {item['node'] + ': ' if item['node'] else ''}{item['message']}" for item in found["problems"]]+ lines += [f"Run {run['number']} ({run['id']}): {run['state']}" for run in found["run_list"][:5]]+ emit(found, "\n".join(lines), as_json)+++@experiment_app.command("create")+def create(+ flow: Annotated[Path | None, typer.Option("--flow", help="A flow document: {parameters, outputs, nodes}")] = None,+ name: Annotated[str, typer.Option("--name")] = "",+ objective: Annotated[str, typer.Option("--objective")] = "",+ request_key: Annotated[str, typer.Option("--request-key", help="Repeat it to retry without a duplicate")] = "",+ project_id: ProjectId = "",+ api_key: ApiKey = "",+ api_url: ApiUrl = "",+ path: ConfigPath = DEFAULT_PATH,+ as_json: AsJson = False,+) -> None:+ """Create an experiment and save the flow file as its first revision."""+ try:+ document = _flow(flow) if flow else None+ api = Api(api_key, api_url, path)+ key = request_key or str(uuid.uuid4())+ body = {"project": api.project(project_id), "name": name, "objective": objective, "request_key": key}+ found = api.call("POST", "/api/experiments/", json=body)+ if document is not None:+ revise = {"document": document, "expected_version": 0, "request_key": f"{key}:flow"}+ try:+ found = api.call("POST", f"/api/experiments/{found['id']}/revise/", json=revise)+ except CommandError as exc:+ if exc.code == "connection_unavailable":+ raise CommandError(+ f"Created experiment {found['id']}; its flow save was not confirmed: {exc} "+ f"Run overmind experiment show {found['id']} before revising it.",+ exc.code,+ ) from None+ raise CommandError(+ f"Created experiment {found['id']} without a flow: {exc} "+ f"Fix the file and run overmind experiment revise {found['id']} --flow {flow}.",+ exc.code,+ ) from None+ except (CommandError, OSError, ValueError) as exc:+ fail(exc, as_json)+ emit(found, f"Created {found['name']} ({found['id']}), revision {found['revision']}.", as_json)+++@experiment_app.command("revise")+def revise(+ experiment: Annotated[str, typer.Argument(help="Experiment id")],+ flow: Annotated[Path, typer.Option("--flow", help="The whole flow document to save")],+ expected_version: Annotated[+ int | None,+ typer.Option("--expected-version", min=0, help="Refuse the save when a newer revision exists"),+ ] = None,+ request_key: Annotated[str, typer.Option("--request-key")] = "",+ api_key: ApiKey = "",+ api_url: ApiUrl = "",+ path: ConfigPath = DEFAULT_PATH,+ as_json: AsJson = False,+) -> None:+ """Save the flow file as the experiment's next revision."""+ try:+ document = _flow(flow)+ api = Api(api_key, api_url, path)+ if expected_version is None:+ expected_version = api.call("GET", f"/api/experiments/{experiment}/")["version"]+ body = {+ "document": document,+ "expected_version": expected_version,+ "request_key": request_key or str(uuid.uuid4()),+ }+ found = api.call("POST", f"/api/experiments/{experiment}/revise/", json=body)+ except (CommandError, OSError, ValueError) as exc:+ fail(exc, as_json)+ needs = len(found["problems"])+ emit(found, f"Saved revision {found['revision']}." + (f" A run needs {needs} more." if needs else ""), as_json)+++def _options(revision: int | None, params: list[str] | None, reuse_run: str) -> dict:+ return {"revision": revision, "parameters": _parameters(params), "reuse_run": reuse_run or None}+++@experiment_app.command("plan")+def plan(+ experiment: Annotated[str, typer.Argument(help="Experiment id")],+ param: Params = None,+ revision: Annotated[int | None, typer.Option("--revision", min=1)] = None,+ reuse_run: Annotated[str, typer.Option("--reuse-run", help="Reuse this run's unchanged stages")] = "",+ api_key: ApiKey = "",+ api_url: ApiUrl = "",+ path: ConfigPath = DEFAULT_PATH,+ as_json: AsJson = False,+) -> None:+ """Show what a run would do, stage by stage, and the plan fingerprint start takes."""+ try:+ api = Api(api_key, api_url, path)+ found = api.call("POST", f"/api/experiments/{experiment}/plan/", json=_options(revision, param, reuse_run))+ except (CommandError, OSError, ValueError) as exc:+ fail(exc, as_json)+ emit(found, _plan_text(found), as_json)+++@experiment_app.command("start")+def start(+ experiment: Annotated[str, typer.Argument(help="Experiment id")],+ plan_fingerprint: Annotated[+ str, typer.Option("--plan", help="The reviewed plan's fingerprint; a changed plan is refused")+ ] = "",+ param: Params = None,+ revision: Annotated[int | None, typer.Option("--revision", min=1)] = None,+ reuse_run: Annotated[str, typer.Option("--reuse-run")] = "",+ max_hours: Annotated[int | None, typer.Option("--max-hours", min=1, max=168)] = None,+ request_key: Annotated[str, typer.Option("--request-key", help="Repeat it to retry without a second run")] = "",+ watch: Annotated[bool, typer.Option("--watch", help="Wait until the run ends")] = False,+ interval: Annotated[float, typer.Option("--interval", min=1.0)] = 10.0,+ api_key: ApiKey = "",+ api_url: ApiUrl = "",+ path: ConfigPath = DEFAULT_PATH,+ as_json: AsJson = False,+) -> None:+ """Start a run. Runs start paid work; review it first with plan and pass its --plan."""+ try:+ api = Api(api_key, api_url, path)+ options = _options(revision, param, reuse_run)+ fingerprint = (+ plan_fingerprint or api.call("POST", f"/api/experiments/{experiment}/plan/", json=options)["fingerprint"]+ )+ body = {**options, "plan": fingerprint, "request_key": request_key or str(uuid.uuid4()), "max_hours": max_hours}+ run = api.call("POST", f"/api/experiments/{experiment}/run/", json=body)+ except (CommandError, OSError, ValueError) as exc:+ fail(exc, as_json)+ if watch:+ _watch(api, run["id"], interval, as_json)+ return+ emit(run, f"Started run {run['number']} ({run['id']}).", as_json)+++def _watch(api: Api, run_id: str, interval: float, as_json: bool) -> None:+ seen: dict[str, str] = {}+ try:+ while True:+ run = api.call("GET", f"/api/experiment-runs/{run_id}/")+ for step in run["steps"]:+ if not as_json and seen.get(step["id"]) != step["state"]:+ typer.echo(+ f"{step['node']:<20} {step['state']}{' — ' + step['error'] if step.get('error') else ''}"+ )+ seen[step["id"]] = step["state"]+ if run["state"] in ENDED:+ break+ time.sleep(interval)+ except (CommandError, OSError, ValueError) as exc:+ fail(exc, as_json)+ emit(run, f"Run {run['number']} {run['state']}{': ' + run['reason'] if run.get('reason') else '.'}", as_json)+ if run["state"] != "completed":+ raise typer.Exit(1)+++@experiment_app.command("status")+def status(+ run: Annotated[str, typer.Argument(help="Run id")],+ watch: Annotated[bool, typer.Option("--watch", help="Wait until the run ends; exit 1 unless it completed")] = False,+ interval: Annotated[float, typer.Option("--interval", min=1.0)] = 10.0,+ api_key: ApiKey = "",+ api_url: ApiUrl = "",+ path: ConfigPath = DEFAULT_PATH,+ as_json: AsJson = False,+) -> None:+ """Show a run and each stage's state."""+ try:+ api = Api(api_key, api_url, path)+ if watch:+ _watch(api, run, interval, as_json)+ return+ found = api.call("GET", f"/api/experiment-runs/{run}/")+ except (CommandError, OSError, ValueError) as exc:+ fail(exc, as_json)+ emit(found, _run_text(found), as_json)+++@experiment_app.command("stop")+def stop(+ run: Annotated[str, typer.Argument(help="Run id")],+ api_key: ApiKey = "",+ api_url: ApiUrl = "",+ path: ConfigPath = DEFAULT_PATH,+ as_json: AsJson = False,+) -> None:+ """Stop a run: each running stage's work is cancelled at its next check."""+ try:+ found = Api(api_key, api_url, path).call("POST", f"/api/experiment-runs/{run}/stop/")+ except (CommandError, OSError, ValueError) as exc:+ fail(exc, as_json)+ emit(found, f"Run {found['number']} {found['state']}.", as_json)+++@experiment_app.command("message")+def message(+ experiment: Annotated[str, typer.Argument(help="Experiment id")],+ text: Annotated[str, typer.Argument(help="The message to the experiment's agent")],+ request_key: Annotated[str, typer.Option("--request-key")] = "",+ api_key: ApiKey = "",+ api_url: ApiUrl = "",+ path: ConfigPath = DEFAULT_PATH,+ as_json: AsJson = False,+) -> None:+ """Send a message to the experiment's agent; it replies in the Console conversation."""+ try:+ api = Api(api_key, api_url, path)+ thread = api.call("GET", f"/api/experiments/{experiment}/")["thread"]+ body = {"text": text, "request_key": request_key or str(uuid.uuid4())}+ sent = api.call("POST", f"/api/assistant-threads/{thread}/messages/", json=body)+ except (CommandError, OSError, ValueError) as exc:+ fail(exc, as_json)+ emit(sent, "Sent. The agent replies in the experiment's conversation.", as_json)diff --git a/overmind/overmind/rest.py b/overmind/overmind/rest.pynew file mode 100644index 00000000..755b593d--- /dev/null+++ b/overmind/overmind/rest.py@@ -0,0 +1,91 @@+"""The REST API as the CLI's record commands call it, and how they print results and refusals."""++from __future__ import annotations++import json+from pathlib import Path+from typing import Annotated, Any, NoReturn++import requests+import typer++from overmind.config import load+from overmind.transfer_connection import resolve_transfer_connection++ApiKey = Annotated[str, typer.Option("--api-key", envvar="OVERMIND_API_KEY", show_default=False)]+ApiUrl = Annotated[str, typer.Option("--api-url", envvar="OVERMIND_API_URL")]+ConfigPath = Annotated[Path, typer.Option("--path", help="Path to overmind.toml")]+AsJson = Annotated[bool, typer.Option("--json", help="Print machine-readable output")]+ProjectId = Annotated[str, typer.Option("--project-id", help="Defaults to overmind.toml's project")]+++class CommandError(Exception):+ def __init__(self, message: str, code: str = "request_failed"):+ super().__init__(message)+ self.code = code+++class Api:+ """The API with the CLI's key. Redirects are refused, so the key never reaches another host."""++ def __init__(self, api_key: str, api_url: str, path: Path):+ self.config = load(path) if path.exists() else None+ key, url = resolve_transfer_connection(api_key, api_url, self.config)+ self.base = url.rstrip("/")+ self.session = requests.Session()+ self.session.headers.update({"X-Api-Key": key})++ def project(self, given: str) -> str:+ project = given.strip() or (self.config.project_id.strip() if self.config else "")+ if not project:+ raise CommandError("Pass --project-id or run in a folder with overmind.toml.", "project_required")+ return project++ def call(self, method: str, path: str, **kwargs) -> Any:+ try:+ response = self.session.request(method, self.base + path, timeout=60, allow_redirects=False, **kwargs)+ except requests.RequestException:+ raise CommandError("The API connection failed.", "connection_unavailable") from None+ if 200 <= response.status_code < 300:+ try:+ return response.json() if response.content else {}+ except ValueError:+ raise CommandError("The API returned a response that is not JSON.", "invalid_response") from None+ status = response.status_code+ code = {400: "refused", 401: "authentication_failed", 403: "permission_denied", 404: "not_found"}+ if 300 <= status < 400:+ raise CommandError("The API redirected; the key was not sent on.", "redirect_refused")+ raise CommandError(+ refusal(response) or f"The API returned HTTP {status}.",+ code.get(status, "refused" if status == 409 else "http_error"),+ )+++def refusal(response: requests.Response) -> str:+ """The platform's authored reason for a refused request, as the Console shows it."""+ if response.status_code not in (400, 403, 409):+ return ""+ try:+ body = response.json()+ except ValueError:+ return ""+ if not isinstance(body, dict):+ return ""+ parts = []+ for field, value in body.items():+ texts = value if isinstance(value, list) else [value]+ joined = " ".join(text for text in texts if isinstance(text, str))+ if joined and field != "code":+ parts.append(joined if field == "detail" else f"{field}: {joined}")+ return " ".join(parts)[:2000]+++def emit(result: Any, text: str, as_json: bool) -> None:+ typer.echo(json.dumps(result, ensure_ascii=False) if as_json else text)+++def fail(exc: Exception, as_json: bool) -> NoReturn:+ code = exc.code if isinstance(exc, CommandError) else "local_configuration"+ record = {"code": code, "message": str(exc)}+ typer.echo(json.dumps({"error": record}) if as_json else record["message"], err=not as_json)+ raise typer.Exit(1) from Nonediff --git a/overmind/pyproject.toml b/overmind/pyproject.tomlindex 0c5daa21..2ff105c6 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.134"+version = "0.1.135"[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.mdindex 27770a60..0791cd76 100644--- a/overmind/skills/overmind-datasets/SKILL.md+++ b/overmind/skills/overmind-datasets/SKILL.md@@ -329,6 +329,9 @@ given, and refuses overwrite. To export traces, call `create_dataset_from_traceswait for landing, author any requested transformations, then export. There is no`export_trace` MCP tool.+A script without MCP lists datasets with `overmind dataset list --json` (`--search`,+`--intent`, `--page`) and reads one with its versions with `overmind dataset show DATASET --json`.+## Preparation execution and correctionsUpload original source bytes once and pin upstream revisions. Register retaineddiff --git a/overmind/skills/overmind-experiments/SKILL.md b/overmind/skills/overmind-experiments/SKILL.mdindex 0df1b492..afd13853 100644--- a/overmind/skills/overmind-experiments/SKILL.md+++ b/overmind/skills/overmind-experiments/SKILL.md@@ -28,8 +28,14 @@ Start with `list_projects`; pass `project_id` on every call from an account conn1. `delete_experiment` deletes an experiment the user asked to delete: its running runs stopand its triggers end.-The final holdout of a Partition stage is read once, by a Qualify stage that nothing trains-or selects after. The flow refuses any other reader, and every read tool refuses its rows.+A save checks each stage's settings against the catalogue: an unknown key, a wrong type, a+value outside its range or choices is refused with the stage and key named. Null, blank+text and `{"$parameter": …}` are accepted for any setting. A missing required setting still+saves; `problems` lists it until a run.++The final holdout of a Partition stage, or a Data stage that pins one, is read once, by a+Qualify stage that nothing trains or selects after. The flow refuses any other reader, at+save and at plan for a version a parameter supplies, and every read tool refuses its rows.A setting a person chose is protected: the experiment's Console agent cannot change it; itschange is kept as a proposal the person applies. Your edits count as a person's.@@ -72,3 +78,11 @@ results as Data Workshop pipelines; the kernel is scratch.- `configure_experiment_trigger` sends an instruction to that agent every N hours, or when acapability's failing traces within N hours reach a threshold, up to `max_sends` times, andno unattended run past `max_spend_usd` of measured spend; `enabled` false ends one.++## From scripts++`overmind experiment` drives the same records over the REST API, with `--json` on every+command: `list`, `show EXPERIMENT`, `create --flow FILE`, `revise EXPERIMENT --flow FILE`,+`plan EXPERIMENT --param name=value`, `start EXPERIMENT --plan FINGERPRINT [--watch]`,+`status RUN [--watch]`, `stop RUN` and `message EXPERIMENT TEXT`. `--watch` exits 1 unless+the run completed. A refused save prints the platform's reason.diff --git a/overmind/skills/overmind-training/SKILL.md b/overmind/skills/overmind-training/SKILL.mdindex a5d86e48..b1e26cc5 100644--- a/overmind/skills/overmind-training/SKILL.md+++ b/overmind/skills/overmind-training/SKILL.md@@ -201,7 +201,7 @@ objective; both tools share the same durable training lifecycle.Freeze `hyperparameters.monitoring` with the rest of the recipe. Modal supports lossmonitoring with adaptive/steps/epoch/off schedules; discover currentprovider capabilities from the model catalogue. Modal also accepts explicit-classification labels, exact matching, JSON Schema and `json_fields` generation probes. The+classification labels, exact matching, JSON Schema, `json_fields` and `tool_calls` generation probes. Theagent supplies task semantics; the platform never invents labels or a successrubric. Metered judges, challenge suites and declared-strata sampling are notavailable in this monitoring contract. Native decisions use their typed metrics.@@ -214,10 +214,16 @@ not a schema/field hybrid. Missing or invalid references are unscorable, whilemissing/wrong predictions fail. Inspect per-field coverage and complete-examplepass rates separately. The scorer never infers fields or executes tools.+For tool-use data, declare `generation={kind:"tool_calls"}`. It generates the first+supervised turn that calls a tool and passes when the call names the reference tool+with arguments that parse as an object; argument equality is reported beside it. A row+with no parseable reference call is unscorable. `selection="generation"` keeps the+verified checkpoint with the best probe pass rate and runs the probe at every check.+Default monitoring uses initial, fixed-sample periodic and full final developmentchecks. Samples freeze during Modal transfer before GPU dispatch, not duringtoken preparation. Adaptive scheduling changes timing only; the overhead target-is not a spend cap. Set `selection=development_loss` or `early_stopping` only when+is not a spend cap. Set `selection=development_loss`, `selection=generation` or `early_stopping` only whenthe user authorises that decision rule. Required checks fail closed. Modal trainingattempts keep the 24-hour function timeout. `runtime_limit_seconds` does not shortenthat call or change optimizer steps; CPU preparation, storage and other costs remaindiff --git a/overmind/tests/test_dataset_cmd.py b/overmind/tests/test_dataset_cmd.pyindex d40aab42..dcb0cce5 100644--- a/overmind/tests/test_dataset_cmd.py+++ b/overmind/tests/test_dataset_cmd.py@@ -428,10 +428,8 @@ def test_wait_until_ready_polls_past_busy_states_and_raises_the_dataset_error(mofrom overmind import dataset_cmdclass _Response:- ok = True-- def __init__(self, body):- self._body = body+ def __init__(self, body, status_code=200):+ self._body, self.status_code = body, status_codedef json(self):return self._body@@ -441,8 +439,10 @@ def test_wait_until_ready_polls_past_busy_states_and_raises_the_dataset_error(moself.states = list(states)self.headers = {}- def get(self, *_args, **_kwargs):- return _Response(self.states.pop(0))+ def request(self, *_args, allow_redirects=True, **_kwargs):+ assert allow_redirects is False+ state = self.states.pop(0)+ return state if isinstance(state, _Response) else _Response(state)monkeypatch.setattr(dataset_cmd.time, "sleep", lambda _s: None)done = dataset_cmd.wait_until_ready(@@ -459,3 +459,7 @@ def test_wait_until_ready_polls_past_busy_states_and_raises_the_dataset_error(moapi_url="http://x",session=_Session([{"state": "error", "error": "Row 2 has 3 cells; the header has 2."}]),)+ # The key would follow a redirect to another host.+ with pytest.raises(dataset_cmd.TransferError) as refused:+ dataset_cmd.wait_until_ready("d1", api_key="k", api_url="http://x", session=_Session([_Response({}, 302)]))+ assert refused.value.code == "redirect_refused"diff --git a/overmind/tests/test_experiment_cmd.py b/overmind/tests/test_experiment_cmd.pynew file mode 100644index 00000000..fa1793f5--- /dev/null+++ b/overmind/tests/test_experiment_cmd.py@@ -0,0 +1,153 @@+from __future__ import annotations++import json+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import pytest+from typer.testing import CliRunner++from overmind import experiment_cmd+from overmind.__main__ import app++pytestmark = pytest.mark.covers("cli-contract")++EXPERIMENT = {"id": "e1", "name": "Refunds", "revision": 0, "version": 0, "problems": [], "thread": "t1"}+REFUSED = {"detail": ["train: hyperparameters has no setting training_type."]}+++def api():+ """A scripted API: each route replies from its queue; every request is recorded."""+ routes: dict[tuple[str, str], list[tuple[int, dict]]] = {}+ received: list[tuple[str, str, dict]] = []++ class Handler(BaseHTTPRequestHandler):+ def _serve(self, method):+ length = int(self.headers.get("Content-Length") or 0)+ body = json.loads(self.rfile.read(length)) if length else {}+ path = self.path.split("?")[0]+ received.append((method, self.path, body))+ queue = routes.get((method, path)) or [(404, {})]+ status, reply = queue.pop(0) if len(queue) > 1 else queue[0]+ if status == 0: # The reply is lost: the connection closes without one.+ self.close_connection = True+ return+ data = json.dumps(reply).encode()+ self.send_response(status)+ if status == 302:+ self.send_header("Location", "http://elsewhere.invalid/")+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def do_GET(self):+ self._serve("GET")++ def do_POST(self):+ self._serve("POST")++ def log_message(self, *args):+ pass++ httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target=httpd.serve_forever, daemon=True).start()+ yield f"http://127.0.0.1:{httpd.server_address[1]}", routes, received+ httpd.shutdown()+++def invoke(url, *args):+ result = CliRunner().invoke(app, [*args, "--api-url", url, "--api-key", "k", "--json"])+ return result, json.loads(result.stdout.splitlines()[-1])+++def test_create_saves_the_flow_file_and_shows_the_platforms_refusal(api, tmp_path):+ url, routes, received = api+ flow = {"nodes": [{"id": "train", "kind": "train", "settings": {"hyperparameters": {"epochs": 2}}}]}+ (tmp_path / "flow.json").write_text(json.dumps(flow))+ routes[("POST", "/api/experiments/")] = [(201, EXPERIMENT)]+ routes[("POST", "/api/experiments/e1/revise/")] = [(200, {**EXPERIMENT, "revision": 1, "version": 1})]++ args = ["experiment", "create", "--flow", str(tmp_path / "flow.json"), "--project-id", "p1", "--request-key", "r"]+ result, created = invoke(url, *args)++ assert result.exit_code == 0, result.output+ assert created["revision"] == 1+ (_, _, create), (_, _, revise) = received+ assert create == {"project": "p1", "name": "", "objective": "", "request_key": "r"}+ assert revise == {"document": flow, "expected_version": 0, "request_key": "r:flow"}++ received.clear()+ routes[("POST", "/api/experiments/e1/revise/")] = [(400, REFUSED)]+ result, refused = invoke(url, *args)+ assert result.exit_code == 1+ assert refused["error"]["code"] == "refused"+ assert "train: hyperparameters has no setting training_type." in refused["error"]["message"]+ assert "overmind experiment revise e1" in refused["error"]["message"]++ routes[("POST", "/api/experiments/e1/revise/")] = [(403, {"detail": "This API key is read-only."})]+ result, forbidden = invoke(url, *args)+ assert "This API key is read-only." in forbidden["error"]["message"]++ routes[("POST", "/api/experiments/e1/revise/")] = [(0, {})]+ result, lost = invoke(url, *args)+ assert lost["error"]["code"] == "connection_unavailable"+ assert "not confirmed" in lost["error"]["message"]+ assert "overmind experiment show e1" in lost["error"]["message"]+++def test_start_runs_the_reviewed_plan_and_watch_exits_with_the_runs_outcome(api, monkeypatch):+ url, routes, received = api+ monkeypatch.setattr(experiment_cmd.time, "sleep", lambda _seconds: None)+ plan = {"entries": [], "executions": 1, "reused": 0, "cost": None, "fingerprint": "f1"}+ run = {"id": "r1", "number": 1, "state": "running", "reason": "", "steps": []}+ step = {"id": "s1", "node": "train", "error": "", "state": "running"}+ routes[("POST", "/api/experiments/e1/plan/")] = [(200, plan)]+ routes[("POST", "/api/experiments/e1/run/")] = [(201, run)]+ routes[("GET", "/api/experiment-runs/r1/")] = [+ (200, {**run, "steps": [step]}),+ (200, {**run, "state": "unmet", "steps": [{**step, "state": "failed", "error": "No GPU."}]}),+ ]++ result, ended = invoke(url, "experiment", "start", "e1", "--param", "epochs=2", "--param", "name=a", "--watch")++ assert result.exit_code == 1+ assert ended["state"] == "unmet"+ (_, _, planned), (_, _, started), *_ = received+ assert planned["parameters"] == {"epochs": 2, "name": "a"}+ assert started["plan"] == "f1" and started["parameters"] == planned["parameters"]+++def test_a_message_reaches_the_experiments_conversation_and_redirects_keep_the_key(api):+ url, routes, received = api+ routes[("GET", "/api/experiments/e1/")] = [(200, EXPERIMENT)]+ routes[("POST", "/api/assistant-threads/t1/messages/")] = [(202, {"id": "m1", "state": "queued"})]++ result, sent = invoke(url, "experiment", "message", "e1", "Add a holdout")++ assert result.exit_code == 0, result.output+ assert sent["state"] == "queued"+ assert received[-1][2]["text"] == "Add a holdout"++ routes[("GET", "/api/experiment-runs/r1/")] = [(302, {})]+ result, refused = invoke(url, "experiment", "status", "r1")+ assert result.exit_code == 1 and refused["error"]["code"] == "redirect_refused"+ assert received[-1][1] == "/api/experiment-runs/r1/"+++def test_dataset_list_and_show_read_the_projects_datasets(api):+ url, routes, received = api+ dataset = {"id": "d1", "name": "Refunds", "intent": "eval", "state": "idle", "active_version": "1", "rows": 60}+ routes[("GET", "/api/datasets/")] = [(200, {"results": [dataset], "next": None})]+ cells = [{"id": "c1", "version": "1", "state": "ok", "rows": 60}]+ routes[("GET", "/api/datasets/d1/")] = [(200, {**dataset, "active_cell": "c1", "cells": cells})]++ result, listed = invoke(url, "dataset", "list", "--project-id", "p1", "--intent", "eval")+ assert result.exit_code == 0, result.output+ assert listed["results"] == [dataset]+ assert received[-1][1] == "/api/datasets/?project=p1&page=1&page_size=100&intent=eval"++ result = CliRunner().invoke(app, ["dataset", "show", "d1", "--api-url", url, "--api-key", "k"])+ assert result.exit_code == 0, result.output+ assert "c1 ok 60 rows active" in result.stdoutdiff --git a/overmind/tests/test_resumable_transfer.py b/overmind/tests/test_resumable_transfer.pyindex 0be4334d..ef442966 100644--- a/overmind/tests/test_resumable_transfer.py+++ b/overmind/tests/test_resumable_transfer.py@@ -68,6 +68,8 @@ class TransferServer:]}})+ if method == "GET" and url.endswith("/api/datasets/dataset-1/"):+ return Response({"state": "error", "error": "Source landing stopped; retained bytes are available."})if "/readiness/" in url:return Response({"protocol_version": 1,@@ -123,10 +125,6 @@ class TransferServer:def close(self):pass- def get(self, url, **kwargs):- assert url.endswith("/api/datasets/dataset-1/")- return Response({"state": "error", "error": "Source landing stopped; retained bytes are available."})-def test_batch_upload_retries_a_lost_chunk_and_completion_without_republishing(tmp_path, monkeypatch):monkeypatch.setattr(time, "sleep", lambda _: None)diff --git a/overmind/uv.lock b/overmind/uv.lockindex a0fb5975..108a42c3 100644--- a/overmind/uv.lock+++ b/overmind/uv.lock@@ -923,7 +923,7 @@ wheels = [[[package]]name = "overmind"-version = "0.1.134"+version = "0.1.135"source = { editable = "." }dependencies = [{ name = "packaging" },diff --git a/tests/fakes/modal.py b/tests/fakes/modal.pyindex 45ee3f50..1e48ba65 100644--- a/tests/fakes/modal.py+++ b/tests/fakes/modal.py@@ -83,6 +83,8 @@ class FakeCall:return self.resultdef _cancel(self, *args, **kwargs) -> None:+ if self.unreachable is not None:+ raise self.unreachableself.cloud.cancelled.append((self.object_id, kwargs))if self.state == "pending":self.state = "cancelled"diff --git a/tests/test_capabilities_api.py b/tests/test_capabilities_api.pyindex a77f3d09..fe4f8ccf 100644--- a/tests/test_capabilities_api.py+++ b/tests/test_capabilities_api.py@@ -78,21 +78,26 @@ def test_a_client_cannot_point_at_a_foreign_eval_set_or_write_measured_fields():capability.refresh_from_db()assert capability.project_id == project.id- client.patch(+ patched = client.patch(f"/api/capabilities/{capability.id}/",{+ "description": "Answers refund questions","observed": True,"usage_stats": {"span_count": 9},"last_activity_at": "2099-01-01T00:00Z",+ "status": "deleted",},format="json",)+ assert patched.status_code == 200, patched.datacapability.refresh_from_db()- assert (capability.observed, capability.usage_stats, capability.last_activity_at) == (- False,- {},- None,- )+ assert capability.description == "Answers refund questions"+ assert (+ capability.observed,+ capability.usage_stats,+ capability.last_activity_at,+ capability.status,+ ) == (False, {}, None, Capability.Status.CURRENT)def _project() -> Project:diff --git a/tests/test_dataset_thread_migration.py b/tests/test_dataset_thread_migration.pyindex e7775259..00b9e25a 100644--- a/tests/test_dataset_thread_migration.py+++ b/tests/test_dataset_thread_migration.py@@ -44,3 +44,40 @@ def test_each_dataset_conversation_becomes_an_experiment_that_reads_the_dataset(assert (empty.experiment.name, empty.experiment.version) == ("Prepare Upload", 0)# The first pass that waited for its source would run unasked in the experiment.assert empty.inputs.get().state == "removed"+++def test_a_dataset_conversation_left_after_the_first_pass_moves_before_its_column_goes(+ django_db_blocker,+):+ before = [("overbae", "0074_eval_judge_context_and_one_score_per_row")]+ after = [("overbae", "0075_drop_assistant_thread_dataset")]+ with scratch_database(django_db_blocker) as database:+ executor = MigrationExecutor(database)+ executor.migrate(before)+ state = executor.loader.project_state(before).apps+ user = state.get_model("overbae", "User").objects.create(email="[email protected]")+ project = state.get_model("overbae", "Project").objects.create(name="P", slug="p")+ dataset = state.get_model("overbae", "Dataset").objects.create(+ project=project, name="Refunds", created_by=user+ )+ cell = state.get_model("overbae", "Cell").objects.create(+ dataset=dataset, position=0, state="ok", fingerprint="f0"+ )+ experiment = state.get_model("overbae", "Experiment").objects.create(+ project=project, name="Kept", created_by=user+ )+ threads = state.get_model("overbae", "AssistantThread").objects+ late = threads.create(project=project, dataset=dataset)+ kept = threads.create(project=project, experiment=experiment)++ executor = MigrationExecutor(database)+ executor.migrate(after)+ state = executor.loader.project_state(after).apps+ threads = state.get_model("overbae", "AssistantThread").objects+ moved = threads.select_related("experiment").get(pk=late.pk)++ assert moved.experiment.name == "Prepare Refunds"+ assert moved.experiment.revisions.get().document["nodes"][0]["settings"] == {+ "cell": str(cell.pk)+ }+ assert threads.get(pk=kept.pk).experiment_id == experiment.pkdiff --git a/tests/test_decision_provider_recovery.py b/tests/test_decision_provider_recovery.pyindex 1f94fcd6..a0a901ba 100644--- a/tests/test_decision_provider_recovery.py+++ b/tests/test_decision_provider_recovery.py@@ -5,6 +5,7 @@ import pytestfrom conftest import frozen_datasetfrom modal_shared.decision_inference import input_digest+from overbae.core import decisions as decisions_corefrom overbae.models import DecisionProviderRequest, Projectfrom overbae.services import decision_providers, native_evaluationfrom overbae.services.decision_providers import interpret_response@@ -196,3 +197,25 @@ def test_external_resume_verifies_changed_input_chunk_without_resubmitting():pytest.raises(ValueError, match="chunk"),):decision_providers.external_step(plan, "final", participant)++[email protected]("measured-facts")+def test_an_unreported_token_count_leaves_the_usage_total_unknown():+ plan, _, request = fixture()+ reported = decisions_core.response_usage(payload(), 0.1)+ unreported = decisions_core.response_usage({**payload(), "usage": {"cost": 0.002}}, 0.1)+ assert (reported["prompt_tokens"], reported["completion_tokens"]) == (20, 10)+ assert (unreported["prompt_tokens"], unreported["completion_tokens"]) == (None, None)+ record = DecisionProviderRequest.objects.create(+ plan=plan,+ participant="external",+ role="final",+ input_sha256=input_digest(request),+ state="completed",+ attempts=[{"usage": reported}],+ )+ totals = decision_providers.usage(plan, "external", "final")+ assert (totals["tokens"], totals["requests"]) == (30, {"completed": 1})+ record.attempts = [{"usage": reported}, {"usage": {"response_cost": None}}]+ record.save()+ assert decision_providers.usage(plan, "external", "final")["tokens"] is Nonediff --git a/tests/test_eval_run_requests.py b/tests/test_eval_run_requests.pynew file mode 100644index 00000000..9365835f--- /dev/null+++ b/tests/test_eval_run_requests.py@@ -0,0 +1,38 @@+import pytest+from conftest import frozen_dataset+from factories import auth_client, make_matrix_row, make_project, make_user++from overbae.models import BillingService, EvalRun+from overbae.services.billing_ledger import append_entry, balance_usd++pytestmark = [pytest.mark.django_db, pytest.mark.covers("work-once")]+++def test_a_keyed_evaluation_retry_returns_its_group_and_a_changed_request_conflicts():+ user = make_user()+ project = make_project(member=user)+ dataset = frozen_dataset(project, contract="eval")+ make_matrix_row(project)+ client = auth_client(user)+ request = {+ "project": str(project.pk),+ "dataset": str(dataset.pk),+ "name": "Baseline",+ "targets": [{"mode": "recorded"}],+ "request_key": "baseline-1",+ }++ first = client.post("/api/eval-runs/", request, format="json")+ append_entry(user=user, amount=-balance_usd(user), service=BillingService.EVALUATION)+ retry = client.post("/api/eval-runs/", request, format="json")+ changed = client.post("/api/eval-runs/", {**request, "name": "Other"}, format="json")++ assert first.status_code == 201, first.data+ assert retry.status_code == 201, retry.data+ assert retry.data["group"] == first.data["group"]+ assert [run["id"] for run in retry.data["runs"]] == [run["id"] for run in first.data["runs"]]+ assert changed.status_code == 400+ assert "request_key" in changed.data+ fresh = client.post("/api/eval-runs/", {**request, "request_key": "baseline-2"}, format="json")+ assert fresh.status_code == 402+ assert EvalRun.objects.filter(project=project).count() == 1diff --git a/tests/test_experiments.py b/tests/test_experiments.pyindex f538af5e..e70df84d 100644--- a/tests/test_experiments.py+++ b/tests/test_experiments.py@@ -1,6 +1,7 @@"""Experiments: the flow document's rules, a run's lifecycle and the surfaces that drive it."""import dataclasses+import reimport uuidfrom datetime import timedelta@@ -25,6 +26,7 @@ from overbae.services.experiments import document, operator, records, runs, stagpytestmark = [pytest.mark.django_db, pytest.mark.covers("experiments")]+CELL = str(uuid.uuid4())ROWS = [{"input": "hi", "expected_output": "hello"}, {"input": "bye", "expected_output": "ciao"}]@@ -56,7 +58,7 @@ def setup(eager, monkeypatch):def test_flow_refuses_type_mismatches_loops_and_early_holdout_reads():split = {"id": "split", "kind": "split", "inputs": {"data": ["data.data"]}}- data = {"id": "data", "kind": "data", "settings": {"cell": "x"}}+ data = {"id": "data", "kind": "data", "settings": {"cell": CELL}}# A malformed protected mark is dropped, not a server error.assert document.normalize({"nodes": [{**data, "protected": 1}]})["nodes"][0]["protected"] == []with pytest.raises(InputValidationError, match="takes data, not model"):@@ -811,7 +813,12 @@ def test_an_iteration_with_a_malformed_stop_rule_ends_instead_of_failing_each_adparent = records.create(context.project,context.user,+ # A save refuses such settings; a parameter's value still reaches the stage.document={+ "parameters": [+ {"name": "most", "type": "string", "default": "two"},+ {"name": "rule", "type": "string", "default": "accuracy above 0.9"},+ ],"nodes": [{"id": "data", "kind": "data", "settings": {"cell": str(cell.pk)}},{@@ -820,11 +827,11 @@ def test_an_iteration_with_a_malformed_stop_rule_ends_instead_of_failing_each_ad"inputs": {"data": ["data.data"]},"settings": {"experiment": str(child.pk),- "max_iterations": "two",- "until": "accuracy above 0.9",+ "max_iterations": {"$parameter": "most"},+ "until": {"$parameter": "rule"},},},- ]+ ],},)run = runs.start(parent, context.user, origin="console")@@ -834,10 +841,10 @@ def test_an_iteration_with_a_malformed_stop_rule_ends_instead_of_failing_each_addef test_flow_and_run_parameters_refuse_what_jsonb_cannot_store():- data = {"id": "data", "kind": "data", "settings": {"cell": "x"}}+ data = {"id": "data", "kind": "data", "settings": {"cell": CELL}}for unstorable in ({"nodes": [{**data, "settings": {"cell": "a\x00b"}}]},- {"nodes": [{**data, "settings": {"cell": "x", "limit": float("inf")}}]},+ {"nodes": [{**data, "settings": {"cell": CELL, "limit": float("inf")}}]},{"nodes": [{**data, "notes": "a\x00b"}]},):with pytest.raises(InputValidationError):@@ -885,8 +892,43 @@ def test_a_halt_after_the_starter_left_names_the_work_it_did_not_stop(setup):assert f"connector_sync {connector.pk} was not stopped." in run.steps.get().error+def test_a_save_refuses_settings_the_stage_catalogue_does_not_allow():+ data = {"id": "data", "kind": "data", "settings": {"cell": CELL}}++ def train(settings):+ node = {"id": "train", "kind": "train", "inputs": {"data": ["data.data"]}}+ return document.normalize({"nodes": [data, {**node, "settings": settings}]})++ for settings, message in (+ (+ {"hyperparameters": {"training_type": "Lora"}},+ "hyperparameters has no setting training_type",+ ),+ ({"epochs": 2}, "train: Train has no setting epochs."),+ (+ {"hyperparameters": {"epochs": 1.5}},+ "train: hyperparameters.epochs takes a whole number.",+ ),+ ({"hyperparameters": {"lora_r": 4}}, "train: hyperparameters.lora_r is at least 8."),+ ({"name": 3}, "train: name takes text."),+ ):+ with pytest.raises(InputValidationError, match=re.escape(message)):+ train(settings)+ with pytest.raises(InputValidationError, match="intent is one of train, eval, pending"):+ document.normalize(+ {"nodes": [{"id": "t", "kind": "trace_dataset", "settings": {"intent": "x"}}]}+ )+ with pytest.raises(InputValidationError, match="data: cell takes an id."):+ document.normalize({"nodes": [{**data, "settings": {"cell": "refunds.csv"}}]})++ # A parameter, null and blank text are allowed; a draft without required settings saves.+ train({"hyperparameters": {"epochs": {"$parameter": "epochs"}, "lora_r": None}, "name": ""})+ draft = document.normalize({"nodes": [{"id": "data", "kind": "data"}]})+ assert document.problems(draft) == [{"node": "data", "message": "Set Dataset version."}]++def test_flow_refuses_malformed_fields_and_a_second_reader_of_the_final_holdout():- data = {"id": "data", "kind": "data", "settings": {"cell": "x"}}+ data = {"id": "data", "kind": "data", "settings": {"cell": CELL}}for malformed in ({"nodes": 1},{"outputs": 1},@@ -1150,10 +1192,38 @@ def test_agents_read_no_row_of_a_final_holdout(setup):assert refused["error"]["code"] == "holdout_sealed"from overbae.services.experiments import describe- pinned = {"nodes": [{"id": "data", "kind": "data", "settings": {"cell": final["cell"]}}]}- reading = records.create(context.project, context.user, document=pinned)+ pinned = {"id": "data", "kind": "data", "settings": {"cell": final["cell"]}}+ reading = records.create(context.project, context.user, document={"nodes": [pinned]})assert describe.brief(reading)["datasets"] == []+ # A Data stage pinning the final holdout follows the Partition's rule.+ model = {"id": "model", "kind": "model", "settings": {"base_model": "m"}}+ evaluate = {"id": "score", "kind": "evaluate", "inputs": {"data": ["data.data"]}}+ qualify = {+ "id": "qualify",+ "kind": "qualify",+ "inputs": {"data": ["data.data"], "model": ["model.model"]},+ }+ with pytest.raises(InputValidationError, match="only a Qualify stage reads the final"):+ records.create(context.project, context.user, document={"nodes": [pinned, evaluate]})+ again = {**pinned, "id": "again"}+ twice = {**qualify, "id": "twice", "inputs": {**qualify["inputs"], "data": ["again.data"]}}+ with pytest.raises(InputValidationError, match="qualify already reads the final holdout"):+ records.create(+ context.project,+ context.user,+ document={"nodes": [pinned, again, model, qualify, twice]},+ )+ records.create(context.project, context.user, document={"nodes": [pinned, model, qualify]})+ chosen = {**pinned, "settings": {"cell": {"$parameter": "data"}}}+ parameterized = records.create(+ context.project,+ context.user,+ document={"parameters": [{"name": "data", "type": "data"}], "nodes": [chosen, evaluate]},+ )+ with pytest.raises(InputValidationError, match="only a Qualify stage reads the final"):+ runs.plan(parameterized, parameters={"data": final["cell"]})+def test_a_coding_agent_has_its_own_kernel_that_a_delete_forgets(setup, monkeypatch):from overbae.services import workspacesdiff --git a/tests/test_inference_live.py b/tests/test_inference_live.pyindex 106a8a0d..e3dc14f3 100644--- a/tests/test_inference_live.py+++ b/tests/test_inference_live.py@@ -2,6 +2,7 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport pytest+from django.utils import timezonefrom overbae.models import DeployedModelfrom overbae.services import inference_live@@ -108,3 +109,17 @@ def test_worker_cache_separates_context_profiles(worker_status):model.max_model_len = 4096inference_live.live_worker_stats(model)assert worker_status[2].await_count == 2+++ "runners,error,expected",+ [(0, None, "asleep"), (1, None, "warm"), (None, TimeoutError(), "warming")],+)+def test_measured_runners_decide_the_state_before_recent_requests(+ worker_status, monkeypatch, runners, error, expected+):+ monkeypatch.setattr(inference_live, "has_recent_inference", lambda *args: True)+ worker_status[2].return_value.num_total_runners = runners+ worker_status[2].side_effect = error+ model = deployment(warming_started_at=timezone.now())+ assert inference_live.worker_status(model)["state"] == expecteddiff --git a/tests/test_mcp_manifest.py b/tests/test_mcp_manifest.pyindex 074b15c8..eb6620e2 100644--- a/tests/test_mcp_manifest.py+++ b/tests/test_mcp_manifest.py@@ -2,9 +2,11 @@ from __future__ import annotationsimport json+import jsonschemaimport pytestfrom mcp_fixtures import EXPECTED_TOOL_NAMES, MAX_MANIFEST_BYTES+from overbae.services.mcp.annotations import SPEC_DEFAULTSfrom overbae.services.mcp.catalog import CATALOGpytestmark = pytest.mark.covers("mcp-surface")@@ -150,8 +152,32 @@ def test_manifest_annotations_cover_read_only_world_and_cost_metadata():definition.async_mode,) == (read_only, idempotent, open_world, cost_class, async_mode)- tool = definition.as_mcp_tool()- assert tool.annotations.readOnlyHint is read_only- assert tool.annotations.destructiveHint is False- assert tool.annotations.idempotentHint is idempotent- assert tool.annotations.openWorldHint is open_world+ hints = {+ **SPEC_DEFAULTS,+ **definition.as_mcp_tool().annotations.model_dump(exclude_none=True),+ }+ assert hints == {+ "readOnlyHint": read_only,+ "destructiveHint": False,+ "idempotentHint": idempotent,+ "openWorldHint": open_world,+ }+++def test_compact_schema_inlines_definitions_and_keeps_validation():+ tools = {tool.name: tool for tool in CATALOG.tools(frozenset({"read", "write"}))}+ assert not any("$ref" in json.dumps(tool.inputSchema) for tool in tools.values())++ validator = jsonschema.Draft202012Validator(tools["start_finetune"].inputSchema)+ accepted = {+ "dataset": "d",+ "base_model": "m",+ "monitoring": {"failure_policy": None, "early_stopping": {"patience": 2}},+ }+ assert list(validator.iter_errors(accepted)) == []+ for refused in (+ {**accepted, "monitoring": {"early_stopping": {"patience": 2, "made_up": 1}}},+ {**accepted, "monitoring": {"failure_policy": "sometimes"}},+ {**accepted, "monitoring": {"early_stopping": {"patience": 0}}},+ ):+ assert list(validator.iter_errors(refused))diff --git a/tests/test_mcp_model_catalog.py b/tests/test_mcp_model_catalog.pyindex 8fd70851..156b780e 100644--- a/tests/test_mcp_model_catalog.py+++ b/tests/test_mcp_model_catalog.py@@ -72,6 +72,7 @@ def test_catalog_is_dataset_independent_and_returns_complete_model_metadata():"exact_match","json_schema","json_fields",+ "tool_calls",]assert output["monitoring"]["runtime_qualification"] != "gpu_qualified"assert output["has_tool_calling"] is Falsediff --git a/tests/test_model_deployment_resume.py b/tests/test_model_deployment_resume.pyindex 8a9d03f3..da1bd710 100644--- a/tests/test_model_deployment_resume.py+++ b/tests/test_model_deployment_resume.py@@ -139,7 +139,7 @@ def test_cancellation_during_poll_cannot_publish_ready(deployed, fake_modal):warming(deployed, fake_modal, state="done", on_get=cancel_job)advance(deployed)- assert deployed.status == "failed"+ assert deployed.status == "cancelled"assert deployed.deployed_at is Nonedeployed.finetuning_job.refresh_from_db()assert deployed.finetuning_job.status == "cancelled"diff --git a/tests/test_queue_metrics.py b/tests/test_queue_metrics.pyindex 97b44856..0c84fb82 100644--- a/tests/test_queue_metrics.py+++ b/tests/test_queue_metrics.py@@ -324,13 +324,15 @@ def test_eval_demand_counts_only_rows_admission_can_start(settings):@pytest.mark.django_dbdef test_assistant_demand_counts_replies_waiting_and_running():- from overbae.models import AssistantInput, AssistantThread, Dataset, Project, User+ from overbae.models import AssistantInput, AssistantThread, Experiment, Project, Userproject = Project.objects.create(name="Assistant queues", slug="assistant-queues")user = User.objects.create_user(email="[email protected]")asked, replying, quiet = (AssistantThread.objects.create(- project=project, dataset=Dataset.objects.create(project=project, name=name), state=state+ project=project,+ experiment=Experiment.objects.create(project=project, name=name, created_by=user),+ state=state,)for name, state in (("asked", "idle"), ("replying", "running"), ("quiet", "idle")))diff --git a/tests/test_trace_usage_aggregation.py b/tests/test_trace_usage_aggregation.pyindex 2a3f1e09..b5fe56f1 100644--- a/tests/test_trace_usage_aggregation.py+++ b/tests/test_trace_usage_aggregation.py@@ -119,6 +119,74 @@ def test_helper_counts_cross_scope_twin_spans_once():assert totals["model"] == "gpt-5.4"+def test_response_ids_decide_twins_when_both_reports_carry_one():+ """The same response ID is one call even when the two instrumentors count tokens+ differently; different IDs are two calls despite equal totals and overlap."""+ _, project = _client_and_project()+ trace_id = uuid.uuid4().hex[:32]+ root = _span(project, trace_id=trace_id)+ reports = [+ ("openinference.langchain", "resp-1", 930, 0, 5_000),+ ("opentelemetry.instrumentation.openai.v1", "resp-1", 900, 100, 4_900),+ ("openinference.langchain", "resp-2", 500, 6_000, 9_000),+ ("opentelemetry.instrumentation.openai.v1", "resp-3", 500, 6_100, 8_900),+ ]+ for scope, response, tokens, start, end in reports:+ span = _span(+ project,+ trace_id=trace_id,+ parent=root.span_id,+ scope=scope,+ attributes={"gen_ai.usage.total_tokens": tokens, "gen_ai.response.id": response},+ )+ Span.objects.filter(span_id=span.span_id).update(start_time_ns=start, end_time_ns=end)+ totals = trace_usage_totals([project.id], [trace_id])[trace_id]+ assert totals["total_tokens"] == 900 + 500 + 500+++def test_one_response_keeps_every_fact_and_an_id_less_twin_stands_for_one_call():+ """Reports of one response keep its tokens and its cost whichever span carries+ each; an ID-less framework span overlapping two responses absorbs only one."""+ _, project = _client_and_project()+ trace_id = uuid.uuid4().hex[:32]+ root = _span(project, trace_id=trace_id)+ reports = [+ ("openinference.langchain", {"gen_ai.response.id": "resp-1", "genai.cost": 0.03}, 0, 5_000),+ (+ "opentelemetry.instrumentation.openai.v1",+ {"gen_ai.response.id": "resp-1", "gen_ai.usage.total_tokens": 700},+ 100,+ 4_900,+ ),+ (+ "openinference.langchain",+ {"gen_ai.usage.total_tokens": 500, "genai.cost": 0.01},+ 6_000,+ 9_000,+ ),+ (+ "opentelemetry.instrumentation.openai.v1",+ {"gen_ai.response.id": "resp-2", "gen_ai.usage.total_tokens": 500},+ 6_100,+ 8_900,+ ),+ (+ "opentelemetry.instrumentation.openai.v1",+ {"gen_ai.response.id": "resp-3", "gen_ai.usage.total_tokens": 500},+ 6_200,+ 8_800,+ ),+ ]+ for scope, attributes, start, end in reports:+ span = _span(+ project, trace_id=trace_id, parent=root.span_id, scope=scope, attributes=attributes+ )+ Span.objects.filter(span_id=span.span_id).update(start_time_ns=start, end_time_ns=end)+ totals = trace_usage_totals([project.id], [trace_id])[trace_id]+ assert totals["total_tokens"] == 700 + 500 + 500+ assert totals["total_cost"] == pytest.approx(0.03 + 0.01)++def test_helper_counts_sequential_identical_calls_separately():"""Two identical calls that do NOT overlap in time are two real calls."""_, project = _client_and_project()diff --git a/tests/test_training_cancellation.py b/tests/test_training_cancellation.pynew file mode 100644index 00000000..eadccd54--- /dev/null+++ b/tests/test_training_cancellation.py@@ -0,0 +1,115 @@+import pytest+from conftest import TRAIN_ROWS, frozen_dataset+from django.utils import timezone+from factories import make_project, make_user++from modal_shared.stacks import TRAIN_FUNCTION_NAMES+from overbae.core.errors import InputValidationError+from overbae.models import DeployedModel, FinetuningJob+from overbae.services import deployment, training_preparation, training_release+from overbae.services.training_cancellation import cancel++pytestmark = [pytest.mark.django_db, pytest.mark.covers("spend-stops")]++MODEL = "Qwen/Qwen3.5-9B"+++def setup(settings, sft):+ settings.FINETUNING_BACKEND = "modal"+ user = make_user()+ cell = frozen_dataset(make_project(member=user), TRAIN_ROWS, contract="train").active_cell+ prep = training_preparation.begin_preparation(cell, MODEL, 4096, user=user)+ return user, cell, prep, prep.training_jobs.get()+++def prepare_calls(fake_modal):+ return [call for call in fake_modal.calls.values() if call.name.startswith("prepare_")]+++def test_cancel_stops_the_preparation_and_a_new_request_starts_it_again(setup, fake_modal):+ user, cell, prep, job = setup+ training_preparation.advance(prep.pk)+ [call] = prepare_calls(fake_modal)+ assert call.state == "pending"++ cancel(job)++ prep.refresh_from_db()+ assert (prep.state, call.state) == ("cancelled", "cancelled")+ training_preparation.advance(prep.pk)+ assert len(prepare_calls(fake_modal)) == 1+ again = training_preparation.begin_preparation(cell, MODEL, 4096, user=user)+ assert again.pk == prep.pk and again.state == "queued"+ assert again.training_jobs.exclude(status="cancelled").get().status == "preprocessing"+++def test_an_unacknowledged_cancel_is_retried_before_the_preparation_starts_again(setup, fake_modal):+ user, cell, prep, job = setup+ training_preparation.advance(prep.pk)+ [call] = prepare_calls(fake_modal)+ call.unreachable = ConnectionError("modal offline")++ cancel(job)++ prep.refresh_from_db()+ assert (prep.state, prep.remote_id, call.state) == ("cancelled", call.object_id, "pending")+ with pytest.raises(InputValidationError):+ training_preparation.begin_preparation(cell, MODEL, 4096, user=user)+ call.unreachable = None+ training_preparation.advance(prep.pk)+ prep.refresh_from_db()+ assert (prep.remote_id, call.state) == ("", "cancelled")+ again = training_preparation.begin_preparation(cell, MODEL, 4096, user=user)+ assert again.pk == prep.pk and again.state == "queued"+++def test_a_preparation_another_job_waits_on_keeps_running(setup, fake_modal):+ _, cell, prep, job = setup+ FinetuningJob.objects.create(+ project=job.project, dataset=cell.dataset, cell=cell, preparation=prep, status="queued"+ )+ training_preparation.advance(prep.pk)++ cancel(job)++ prep.refresh_from_db()+ assert prep.state == "running"+ assert [call.state for call in prepare_calls(fake_modal)] == ["pending"]+++def test_a_call_submitted_while_cancelling_is_cancelled_too(setup, fake_modal):+ _, _, prep, job = setup+ app = training_release.current()["app"]+ for name in TRAIN_FUNCTION_NAMES.values():+ fake_modal.deploy(app, f"prepare_{name}", lambda *args: cancel(job))++ training_preparation.advance(prep.pk)++ prep.refresh_from_db()+ [call] = prepare_calls(fake_modal)+ assert prep.state == "cancelled" and prep.remote_id == ""+ assert call.object_id in [cancelled for cancelled, _ in fake_modal.cancelled]+++def test_cancel_stops_publication_of_the_trained_model(setup, serving, fake_modal):+ _, _, _, job = setup+ FinetuningJob.objects.filter(pk=job.pk).update(+ status="deploying", remote_job_id="run:call", base_model="Qwen/Qwen3-8B"+ )+ published = deployment.ensure_training_deployment(str(job.pk))+ DeployedModel.objects.filter(pk=published.pk).update(+ deployment_stage="weights",+ deployment_call_id="fc-weights",+ deployment_next_poll_at=timezone.now() + timezone.timedelta(minutes=1),+ )+ call = fake_modal.adopt("fc-weights", "weights")++ cancel(job)+ deployment.advance_deployment(published.pk)+ DeployedModel.objects.filter(pk=published.pk).update(deployment_next_poll_at=timezone.now())+ deployment.advance_deployment(published.pk)++ published.refresh_from_db()+ assert published.status == "cancelled"+ assert call.state == "cancelled"diff --git a/tests/test_training_field_checks.py b/tests/test_training_field_checks.pyindex b109fb06..58c24e35 100644--- a/tests/test_training_field_checks.py+++ b/tests/test_training_field_checks.py@@ -7,7 +7,14 @@ from django.urls import reversefrom mcp_fixtures import call_toolfrom rest_framework.test import APIClient-from modal_shared.training_monitoring import paired_generation_metrics, resolve_policy+from modal_shared.training_monitoring import (+ contract_metrics,+ first_tool_call,+ paired_generation_metrics,+ parse_tool_call,+ resolve_policy,+ score_tool_call,+)from modal_shared.training_monitoring_runtime import Monitorfrom overbae.models import APIToken, Dataset, FinetuningJob, Project, ProjectMembership, Userfrom overbae.services import training_monitoring@@ -176,6 +183,77 @@ def test_paired_results_exclude_unscorable_reference_instead_of_coercing_null():assert paired_generation_metrics(rows, rows, seed=42)["paired"] == 0+ "output,call",+ [+ (+ '<think>\n\n</think>\n\n<tool_call>\n{"name": "refund", "arguments": {"id": 7}}\n'+ "</tool_call>",+ ("refund", {"id": 7}),+ ),+ (+ "<tool_call>\n<function=refund>\n<parameter=id>\n7\n</parameter>\n</function>\n"+ "</tool_call>",+ ("refund", {"id": 7}),+ ),+ ('{"name": "refund", "parameters": {"id": 7}}', ("refund", {"id": 7})),+ ('[TOOL_CALLS][{"name": "refund", "arguments": "{\\"id\\": 7}"}]', ("refund", {"id": 7})),+ ('[TOOL_CALLS]refund[ARGS]{"id": 7}', ("refund", {"id": 7})),+ ('[TOOL_CALLS]refund[ARGS] {"id": 7}', ("refund", {"id": 7})),+ ("<function=refund>\n<parameter=id>\n7", ("refund", "\n<parameter=id>\n7")),+ ("<function=ping>\n</function>", ("ping", {})),+ (+ '<tool_call>{"name": "search", "arguments": {"query": "<function=refund>"}}</tool_call>',+ ("search", {"query": "<function=refund>"}),+ ),+ ('<tool_call>{"name": "refund", "arguments": "{id: 7"}</tool_call>', ("refund", "{id: 7")),+ ("The refund is on its way.", None),+ ],+)+def test_the_first_tool_call_is_read_from_each_native_format(output, call):+ parsed = parse_tool_call(output)+ assert (parsed and (parsed["name"], parsed["arguments"])) == call+++def test_tool_call_probe_scores_the_first_call_turn_and_leaves_rows_without_one_unscorable():+ # Token ids are characters, so the fake tokenizer decodes the ids it is given.+ def decode(ids):+ return "".join(chr(i) for i in ids)++ def row(*turns):+ ids, labels = [], []+ for text, supervised in turns:+ ids += [ord(c) for c in text]+ labels += [ord(c) if supervised else -100 for c in text]+ return {"input_ids": ids, "labels": labels}++ call = '<tool_call>{"name": "refund", "arguments": {"id": 7}}</tool_call>'+ prompt, answer, reference = first_tool_call(+ row(("user: refund 7\n", False), ("Checking.", True), ("\n", False), (call, True)), decode+ )+ assert decode(prompt).endswith("Checking.\n")+ assert decode(answer) == call+ assert first_tool_call(row(("user: hi\n", False), ("Hello.", True)), decode) is None++ wrong = call.replace("refund", "cancel")+ scores = [score_tool_call(output, reference) for output in (call, wrong, "No call.")]+ assert [score["passed"] for score in scores] == [True, False, False]+ assert scores[1]["tool_call"] == {+ "name": "cancel",+ "name_correct": False,+ "arguments_valid": True,+ "arguments_equal": True,+ }+ unscorable = score_tool_call("anything", None)+ assert (unscorable["passed"], unscorable["scoring_status"]) == (None, "unscorable")+ examples = [{"status": "completed", **score} for score in [*scores, unscorable]]+ metrics = contract_metrics([*examples, {"status": "failed"}], {"kind": "tool_calls"})+ assert (metrics["scored"], metrics["unscorable"], metrics["technical_errors"]) == (3, 1, 1)+ assert metrics["pass_rate"] == pytest.approx(1 / 3)+ assert metrics["tool_call"]["name_correct"] == pytest.approx(1 / 3)+ assert metrics["tool_call"]["arguments_valid"] == pytest.approx(2 / 3)++@pytest.mark.parametrize("extra", [{"schema": {}}, {"labels": ["yes", "no"]}])def test_field_contract_does_not_silently_ignore_an_additional_grader(extra):with pytest.raises(ValueError, match="json_fields"):diff --git a/tests/test_training_monitoring.py b/tests/test_training_monitoring.pyindex fb72166e..c250ceda 100644--- a/tests/test_training_monitoring.py+++ b/tests/test_training_monitoring.py@@ -374,3 +374,42 @@ def test_completed_measurements_are_durable_before_slow_generation_or_checkpointassert result["state"] == "failed"assert result["metrics"]["generation"]["accuracy"] == 1assert "checkpoint write interrupted" in result["error"]["message"]+++def test_generation_selection_probes_every_check_and_keeps_the_best_passing_checkpoint(tmp_path):+ with pytest.raises(ValueError, match="generation probe"):+ resolve_policy({"selection": "generation"}, has_development=True, provider="modal")+ with pytest.raises(ValueError, match="tool_calls"):+ resolve_policy(+ {"generation": {"kind": "tool_calls", "labels": ["a", "b"]}},+ has_development=True,+ provider="modal",+ )+ rows = [{"key": str(i), "input_ids": [1, 2], "labels": [-100, 2]} for i in range(4)]+ policy = resolve_policy(+ {"generation": {"kind": "exact_match"}, "selection": "generation", "generation_every": 5},+ has_development=True,+ provider="modal",+ )+ assert policy["failure_policy"] == "stop"+ monitor = Monitor(tmp_path, policy, rows, rows, total_steps=40, attempt=1)+ passing = {10: 2, 20: 3, 30: 1}+ losses = {10: 0.9, 20: 0.7, 30: 0.5}+ for step in (10, 20, 30):+ monitor.check(+ step,+ evaluate=lambda indices, split, step=step: {"eval_loss": losses[step]},+ generate=lambda indices, step=step: [+ {"row": i, "status": "completed", "passed": n < passing[step]}+ for n, i in enumerate(indices)+ ],+ save_checkpoint=lambda step, metrics: {+ "identity": str(step),+ "state": "available",+ "metrics": metrics,+ "verification": {"reload_verified": True},+ },+ )+ checks = monitor.summary()["checks"]+ assert all(check["metrics"]["generation"]["expected"] == 4 for check in checks)+ assert monitor.summary()["selected_checkpoint"] == "1:20"diff --git a/tests/test_workshop_analytics.py b/tests/test_workshop_analytics.pyindex 92a32cee..565d38a1 100644--- a/tests/test_workshop_analytics.py+++ b/tests/test_workshop_analytics.py@@ -1,4 +1,6 @@import pytest+from conftest import frozen_dataset+from factories import make_projectfrom overbae.models import Cellfrom overbae.services.datasets.analytics import VERSION, describe@@ -84,3 +86,18 @@ def test_null_semantics_and_stale_fingerprints_are_not_reported_as_known():assert describe(cell)["status"] == "completed"cell.stats["analytics"]["version"] = VERSION - 1assert describe(cell)["status"] == "unmeasured"+++def test_a_landed_version_carries_its_checks_without_an_exploration():+ refunds = [{"input": f"Refund order {i}?", "expected_output": "Yes"} for i in range(60)]+ plain = frozen_dataset(make_project(), refunds).active_cell+ labelled = frozen_dataset(make_project(), [decision([1, 0]), decision([0, 1])]).active_cell++ for cell in (plain, labelled):+ report = describe(cell)+ assert report["status"] == "completed"+ assert {"leakage.input_determines_label", "leakage.label_in_input"} <= {+ c["id"] for c in report["checks"]+ }+ assert describe(plain)["rows_scanned"] == 60