The platform for continuously improving AI agents.
Rebuild the Data Workshop data plane and dataset screens (#336)
Freyam Mehta33fc6267a4fd
diff --git a/.agents/skills/backend-architecture/references/assistant.md b/.agents/skills/backend-architecture/references/assistant.mdindex 8aab9536..88b0730f 100644--- a/.agents/skills/backend-architecture/references/assistant.md+++ b/.agents/skills/backend-architecture/references/assistant.md@@ -8,7 +8,8 @@ The Console's assistant is a second author beside a customer's coding agent, sco- A turn is one Celery task (`tasks/assistant.run_turn`, queue `assistant`): from the delivered messages to a reply without tool calls, or to a `present` that asks a Question or Choices. `turn.wake` sends it after the commit that queued a message; a second task finds the thread taken and ends. The task starts the next turn itself when messages arrived while it ran.- A turn takes the thread by raising `AssistantThread.turn` and writes only while it still holds that number (`log.append(..., turn=)` raises `LostTurnError`). `updated_at` is its progress mark. `turn.settle`, called by every read of the thread and every message, marks a turn without progress for `STALE` (15 minutes) as interrupted; no process watches for it. A turn ends itself after `TURN_SECONDS`. An interrupted turn is never resumed: the next message starts a new one, and a call left without a result is answered as abandoned.- A message for a dataset whose source still lands waits: `_begin` leaves it queued, and the landing task calls `turn.wake_dataset` when it ends.-- A message is delivered with `threads.brief`: what the dataset holds now (source and versions with their `data/<cell>.parquet` path, columns, measured profile, its pipeline). It is attached again only when it changed or a summary replaced the message that carried it.+- A Console dataset made with `prepare` (the dialog sends it when an intent or a brief is given) queues `threads.queue_first_pass` in the create transaction, so its turn starts when the source lands. `turn.ready` holds that message while the dataset has no landed source, so a failed import keeps it queued for the next landing. A split queues one pass on the train half; the brief names the eval half (`split.sibling`), and both halves share the cleaning steps.+- A message is delivered with `threads.brief`: what the dataset holds now: its intent, the linked capability's contract, the split sibling, its pipeline, and for the source and latest versions their `data/<cell>.parquet` path, `fit`, exact `duplicate_rows` and a column profile (`store.frame_profile`, cached per frame). It is attached again only when it changed or a summary replaced the message that carried it.- When a reply's prompt passes `ASSISTANT_COMPACT_TOKENS`, the turn appends a `summary` of all but the last `COMPACT_KEEP` events. A model call reads the newest summary and the events after it; the transcript keeps everything. The cut never separates a tool call from its result.- Stop sets `stop_requested`, drops queued messages and stops the conversation's kernel at once (`tasks/assistant.stop_kernel`), so a cell that runs answers. The turn sees the flag at its next step. Jobs the turn started continue.- The sender of the newest message pays for the model calls (`BillingService.DATA_WORKSHOP`, idempotency key `assistant:<thread>:<sequence>`), and tools run with that sender's project access, checked before each model call. A reply and its charge are saved in one transaction. A reply stopped in the middle is not charged: the provider reports no usage for it.@@ -16,11 +17,11 @@ The Console's assistant is a second author beside a customer's coding agent, sco## Tools- Catalog tools (`tools.CATALOG_TOOLS`) are MCP tools called in process through `CATALOG.invoke`; validation and receipts are the catalog's own. The turn supplies `project_id`, and `request_key` on mutating tools. A tool that starts a job waits for it in the same call (`tools._wait`).-- Own tools: `run_python` runs a cell in the conversation's kernel; `versions` names the dataset versions it reads, copied into the workspace first. `run_pipeline` retains a package from the model's files, then saves, validates and runs it through the catalog and waits for the run; a `pipeline` argument names either id of a saved pipeline. `present` shows a result.+- Own tools: `run_python` runs a cell in the conversation's kernel; `versions` names the dataset versions it reads, copied into the workspace first. `run_pipeline` retains a package from the model's files, then saves, validates and runs it through the catalog and waits for the run; a publish over more than `tools.SAMPLE_ROWS` rows first runs a preview of that many rows and stops there when it fails, unless the script ran and kept none of those rows; a `pipeline` argument names either id of a saved pipeline. `present` shows a result.- Every tool schema starts with a `summary` argument (`tools.SUMMARY`): a few words for the reader. The Console shows it in place of the tool's name, while the call is written and afterwards.- Publication has one path: a retained pipeline package run by the pipeline runner. The kernel is for exploration only. The assistant has no path to the customer's repository or machine.- `present` documents are validated by `services/assistant/presentation.py` and stored in `AssistantEvent.presentation`. Charts, tables and metrics read tables the kernel wrote, and an Image is a PNG, JPEG or WebP file it wrote, retained under `MEDIA_ROOT/assistant/<thread>/` by content name. A Question or Choices answer is `{"call", "id", "values"}`.-- `prompt.RULES` sets the conversation: text is for findings, assumptions and answers; data preparation takes the least-changing reading without asking; a question is for a request the data cannot serve.+- `prompt.RULES` sets the conversation: text is for findings, assumptions and answers; preparation ends with a published version whose `fit` is ok for the intent (a pending intent takes the closest use and says so); a question is for a request the data cannot serve.## Workspacesdiff --git a/.agents/skills/data-workshop/SKILL.md b/.agents/skills/data-workshop/SKILL.mdindex cb3a190d..6ecfe568 100644--- a/.agents/skills/data-workshop/SKILL.md+++ b/.agents/skills/data-workshop/SKILL.md@@ -24,7 +24,7 @@ A customer's coding agent over MCP and the Console assistant own interpretation,## Sources and landing-- A dataset may start from a written `brief` with no source or capability. Purpose is explicit (`train`, `eval`, `explore`) and otherwise stays pending; when no capability is given, REST and MCP landing assign the top-ranked capability if its score is above zero; CLI transfers never infer one.+- A dataset may start from a written `brief` with no source or capability. Intent is explicit (`train` with `train_format` `sft` or `decision`, or `eval`) and otherwise stays pending; when no capability is given, REST and MCP landing assign the top-ranked capability if its score is above zero; CLI transfers never infer one.- The first source attaches to the draft; later uploads append versions. Original bytes, extraction metadata and row evidence are retained.- CLI uploads use `DatasetTransfer`: a project request key binds SHA-256, byte count and destination. Up to 100 ordered files and 2 GiB per transfer; file order is part of identity; one batch becomes one source cell or one version. Repeat the identical command after an interruption. `get_job(kind=dataset_transfer)` reads byte and publication state; `dataset_run` reports landing. An explicit `--json-rows-field` selects a top-level JSON row array and is recorded.- Local upload, export and checkpoint download authenticate separately from MCP. Without an explicit or repository key they use the address-bound account connection at `$XDG_CONFIG_HOME/overmind/connection.toml` (mode `0600`); repository keys are endpoint-bound too. `overmind connection check --project-id PROJECT --json` verifies MCP and transfer access from the invoking environment; MCP connectivity alone is not readiness. Verify the installed CLI from the workspace and from a repository-free directory.@@ -49,7 +49,8 @@ A customer's coding agent over MCP and the Console assistant own interpretation,- Cells carry receipt-backed `transformation` attribution (run, revision, package checksum, entrypoint). External imports and unrecorded history never claim platform execution. Every retained package file is inspectable with checksum-verified pagination.- Recovery is lease expiry: the `reap_stuck_runs` beat task calls `workbench.expire_runs`, which fails runs past their lease without publishing partial output or replaying scripts.- Failure or cancellation leaves source and consumer versions unchanged. Cancellation prevents publication; it does not claim to stop a running calculation.-- `batch_rows` (1–100,000) splits a row-independent step into separate sandbox runs (`pipeline_execution.py`); global sorting, grouping, splitting and deduplication must not batch.+- A step is one sandbox request. `batch_rows` (1–100,000) runs a row-independent script once per batch, each in a fresh process, one after another under one memory reservation (`sandbox/execute.py`); global sorting, grouping, splitting and deduplication must not batch. The worker streams the stored Parquet; the sandbox writes JSONL for the script unless the step declares `io: parquet`. A full sandbox makes the request wait inside the run lease.+- `packages.runtime_id()` hashes only what a script observes (the I/O contract, the interpreter, `uv.lock`, `package_child.py`, `kernel.py`). Changing the sandbox server leaves saved packages runnable.- Bindings start paused, pin a revision, and rebuild full source snapshots; checkpoint and cells commit together.- Keep each step's logic in its visible entrypoint; helpers hold reusable utilities, not an opaque dispatcher. Change a recipe through a new revision and run; never rewrite historical scripts.- `save_dataset_pipeline(dataset=..., package=...)` associates the script with the dataset's preparation; retrying an older request never resets a newer association.@@ -62,15 +63,17 @@ External results arrive inline (at most 2,000 rows or 4 MiB) or as a project-sco## Storage and queries- 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 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.## Checks and consumers-- The platform measures format and change impact. Semantic quality stays unmeasured without attributable evidence; technical compatibility is not semantic correctness. Do not add a universal quality gate.+- The platform measures format. Semantic quality stays unmeasured without attributable evidence; technical compatibility is not semantic correctness. Do not add a universal quality gate.- Preserve probability targets, option order, weights, duplicates, blank states and declared groups. Never argmax soft targets or invent distributions from means. Decision recipes publish a typed `decision` with tied maxima and supervision metadata.-- The native agent declares target meaning per family from evidence in retained code and output metadata; unknown meaning stays unknown. Historical preparation plans are not a writable API. Profiles and impact checks keep declared supervision metadata, so a changed weight or semantic declaration shows in review.+- The native agent declares target meaning per family from evidence in retained code and output metadata; unknown meaning stays unknown. Analytics keep declared supervision metadata.- Publication measures analytics on the full rows, bound to the exact fingerprint and rule version. They are advisory; `explore_dataset` backfills older cells, and reads never scan.- Raw tables have no inferred feature or target mapping; column names such as `label` or `score` never select columns.- Column contracts use `object` for a nested decision. A final step's `consumer` (`decision_train`, `decision_eval`, `chat_train`, `model_eval`) validates targets in preview and publication.@@ -79,19 +82,19 @@ External results arrive inline (at most 2,000 rows or 4 MiB) or as a project-sco## Console canvas-The landing page opens on the assistant composer (`components/assistant/assistant-composer.tsx`): files or attached datasets plus one sentence start a thread on the working dataset. The project dataset table is a sheet below it; a row opens its cells on a grid-snapped flow canvas. Cells stay full-size at scale 1; zoom and Fit view change only the camera. Steps run downward and sibling branches share a horizontal layer. Positions persist in the browser and never change execution. The folder button opens project-scoped dataset navigation. The assistant chat is a bar at the bottom of the canvas that opens into a resizable left panel (`components/assistant/`). There is no funding control, cell search or cell-selector strip.--The dataset inventory exposes current work from retained pipeline and transfer receipts.-Uploads attached to a dataset report measured bytes; transformations and previews stay-indeterminate unless measured progress exists. The table retains the published version-and row count during work, and shows no row count before a version is published.--The inventory Role column and filter derive roles from completed partition memberships-and recorded training/evaluation consumers, not intent or names. Source datasets-include every role produced by their completed partition plans. Multiple roles remain-visible. Raw-only published datasets without a consumer role show Source; other-unassigned datasets show an em dash. MCP retains its existing partition and consumer-facts; this Console grouping adds no MCP operation or intent mutation.+The landing page opens on the assistant composer (`components/assistant/assistant-composer.tsx`): files or attached datasets plus one sentence start a thread on the working dataset. The project dataset table is a sheet below it; a row opens its cells on a flow canvas. Cells stay full-size at scale 1; zoom and Fit view change only the camera. Steps run downward and sibling branches share a horizontal layer. The layered layout owns every position and reruns when a cell's height changes, so cells are not draggable. The folder button opens project-scoped dataset navigation. The assistant chat is a bar at the bottom of the canvas that opens into a resizable left panel (`components/assistant/`). There is no funding control, cell search or cell-selector strip.++The inventory columns are Name, Role, Capability, Datapoints, Source and Updated+(`components/datasets/datasets-table.tsx`); every value is one chip shape or an em dash.+Current work (`list_activity.current_work`) shows beside the name only while busy or+failed: upload bytes, landing rows written then measured, and a run's stage with the+sandbox's counted batches or rows written and measured; anything else stays+indeterminate. Role is the intent (Train · SFT, Train · Decision, Train, Eval); its tooltip+names the uses that completed partitions or recorded consumers made (`roles`). With no+intent, a used dataset (often a split's source) shows its uses, with the training+member's format ("Train · SFT + Eval"). Datapoints are compact above 10,000. Source is one chip for+files (first name and `+N`), pasted rows, inline rows, traces, LLM calls, a derived version+or a split.The Console inventory groups datasets by `workspace_id`, resolved from completedpartition and exploration lineage. One source workspace row combines output rolesdiff --git a/frontend/src/components/datasets/badges.tsx b/frontend/src/components/datasets/badges.tsxindex 494d7a57..a77ed94d 100644--- a/frontend/src/components/datasets/badges.tsx+++ b/frontend/src/components/datasets/badges.tsx@@ -2,7 +2,7 @@ import { Link } from "@tanstack/react-router";import { Badge } from "@/components/ui/badge";import { Icon } from "@/components/ui/icons";-import { INTENT_LABEL, type UsedVersionInfo } from "@/hooks/use-datasets";+import { intentLabel, type UsedVersionInfo } from "@/hooks/use-datasets";import { cn } from "@/lib/utils";export const SOURCE_KIND_LABEL: Record<string, string> = {@@ -15,15 +15,17 @@ export const SOURCE_KIND_LABEL: Record<string, string> = {/** `train` / `eval` are what a consumer needs; `pending` is not decided yet. */export function IntentBadge({intent,+ trainFormat,className,}: {intent: string | null | undefined;+ trainFormat?: string | null;className?: string;}) {if (!intent) return null;return (<Badge className={className} size="chip" variant="outline">- {INTENT_LABEL[intent] ?? intent}+ {intentLabel(intent, trainFormat)}</Badge>);}diff --git a/frontend/src/components/datasets/datasets-table.test.tsx b/frontend/src/components/datasets/datasets-table.test.tsxnew file mode 100644index 00000000..b2d23136--- /dev/null+++ b/frontend/src/components/datasets/datasets-table.test.tsx@@ -0,0 +1,111 @@+// @vitest-environment jsdom+// covers: console-logic++import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, render, screen, within } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { TooltipProvider } from "@/components/ui/tooltip";+import type { Dataset } from "@/openapi";+import { DatasetsBrowser } from "./datasets-table";++vi.mock("@tanstack/react-router", () => ({+ Link: ({ children }: { children: unknown }) => children,+ useNavigate: () => vi.fn(),+}));+vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+);++afterEach(cleanup);++const dataset = (fields: Partial<Dataset>): Dataset =>+ ({+ activeVersion: "1.0",+ capability: null,+ capabilityName: null,+ cells: [],+ id: crypto.randomUUID(),+ intent: "pending",+ name: "rows",+ roles: [],+ rows: 10,+ sourceKind: "file",+ sourceSpec: {},+ state: "idle",+ trainFormat: "",+ updatedAt: "2026-11-18T10:00:00Z",+ work: null,+ ...fields,+ }) as unknown as Dataset;++function table(datasets: Dataset[]) {+ render(+ <QueryClientProvider client={new QueryClient()}>+ <TooltipProvider>+ <DatasetsBrowser+ datasets={datasets}+ isLoading={false}+ roleFilter="all"+ search=""+ setRoleFilter={vi.fn()}+ setSearch={vi.fn()}+ />+ </TooltipProvider>+ </QueryClientProvider>+ );+ return (name: string) => within(screen.getByText(name).closest("tr") as HTMLElement);+}++describe("datasets table", () => {+ it("shows every row's role, count and source in one shape", () => {+ const row = table([+ dataset({+ intent: "train",+ name: "Tickets",+ roles: ["training"],+ rows: 48_213,+ sourceSpec: {+ sources: [{ filename: "a.csv" }, { filename: "b.csv" }, { filename: "c.csv" }],+ },+ trainFormat: "sft",+ }),+ dataset({ name: "Calls", sourceKind: "traces" }),+ dataset({ activeVersion: undefined, name: "Draft", sourceKind: "pending" }),+ dataset({ name: "Split source", roles: ["training", "evaluation"] }),+ ]);++ expect(row("Tickets").getByText("Train · SFT")).toBeTruthy();+ expect(row("Tickets").getByText("48.2K")).toBeTruthy();+ expect(row("Tickets").getByText("a.csv")).toBeTruthy();+ expect(row("Tickets").getByText("+2")).toBeTruthy();+ expect(row("Calls").getByText("Traces")).toBeTruthy();+ // A draft has no role, capability, count or source: each shows the same dash.+ expect(row("Draft").getAllByText("—")).toHaveLength(4);+ // With no intent, a used dataset shows what it was used for, and rows sent inline say so.+ expect(row("Split source").getByText("Train + Eval")).toBeTruthy();+ expect(row("Split source").getByText("Inline rows")).toBeTruthy();+ });++ it("shows running work and its measured count beside the name", () => {+ const row = table([+ dataset({+ name: "Orders",+ work: {+ actorKind: null,+ completed: 340_000,+ label: "Writing",+ status: "running",+ total: 1_000_000,+ unit: "rows",+ },+ } as Partial<Dataset>),+ ]);+ expect(row("Orders").getByText("Writing · 340K of 1M rows")).toBeTruthy();+ });+});diff --git a/frontend/src/components/datasets/datasets-table.tsx b/frontend/src/components/datasets/datasets-table.tsxindex 40d336d0..b33ab77f 100644--- a/frontend/src/components/datasets/datasets-table.tsx+++ b/frontend/src/components/datasets/datasets-table.tsx@@ -1,12 +1,10 @@-import { useMemo, useState } from "react";+import { type ReactNode, useMemo, useState } from "react";import { useNavigate } from "@tanstack/react-router";import type { ColumnDef, OnChangeFn, RowSelectionState } from "@tanstack/react-table";-import { SOURCE_KIND_LABEL } from "@/components/datasets/badges";import { EntityRef } from "@/components/entity-ref";import { FileTypeIcon } from "@/components/file-type-icon";-import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";import { ConfirmDialog } from "@/components/ui/confirm-dialog";@@ -25,19 +23,50 @@ import {} from "@/components/ui/select";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { useActivityHighlights } from "@/hooks/use-activity";-import { datasetDisplayName, useDeleteDatasetMutation } from "@/hooks/use-datasets";+import {+ compactCount,+ datasetDisplayName,+ INTENT_LABEL,+ intentLabel,+ intentOf,+ SPLIT_LABEL,+ useDeleteDatasetMutation,+ workText,+} from "@/hooks/use-datasets";import { useGuestGate } from "@/hooks/use-guest-gate";+import type { WorkspaceDataset } from "@/lib/dataset-workspaces";import { parseDrfOrdering } from "@/lib/drf-ordering";import { ResolvedStatusBadge, resolveStatus } from "@/lib/job-status";import { cn } from "@/lib/utils";import type { Dataset } from "@/openapi";-const DATASET_ROLES: Record<string, string> = {- calibration: "Calibration",- development: "Development",- evaluation: "Evaluation",- source: "Source",- training: "Training",+/** What a dataset is for, from its intent: the one value the Role column shows. */+export const ROLE_LABEL: Record<string, string> = {+ decision: intentLabel("train", "decision"),+ eval: intentLabel("eval"),+ pending: intentLabel("pending"),+ sft: intentLabel("train", "sft"),+ train: intentLabel("train"),+};++const roleOf = (ds: Dataset): string => {+ const intent = intentOf(ds);+ return intent === "train" ? ds.trainFormat || "train" : intent;+};++// In the order a model meets them; a workspace merges its members' uses in any order.+const USES: [string, string][] = [+ ["training", SPLIT_LABEL.train],+ ["development", SPLIT_LABEL.development],+ ["calibration", SPLIT_LABEL.calibration],+ ["evaluation", INTENT_LABEL.eval],+];++/** Where runs and partitions used the dataset, as one sentence for the role's tooltip. */+const usedText = (ds: Dataset): string | null => {+ if (!ds.roles.length) return null;+ const uses = ds.roles.map((role) => role.toLowerCase());+ return `Used for ${uses.length > 1 ? `${uses.slice(0, -1).join(", ")} and ${uses.at(-1)}` : uses[0]}`;};const NO_CAPABILITY = "__none__";@@ -46,16 +75,12 @@ const filterDatasets = (datasets: Dataset[],search: string,roleFilter = "all",- capabilityFilter = "all"+ capabilityFilter = "all",+ nameById: Record<string, string> = {}): Dataset[] => {const q = search.trim().toLowerCase();return datasets.filter((ds) => {- if (- roleFilter === "unassigned"- ? ds.roles.length > 0- : roleFilter !== "all" && !ds.roles.some((role) => role === roleFilter)- )- return false;+ if (roleFilter !== "all" && roleOf(ds) !== roleFilter) return false;if (capabilityFilter !== "all" && (ds.capability || NO_CAPABILITY) !== capabilityFilter) {return false;}@@ -64,7 +89,10 @@ const filterDatasets = (datasetDisplayName(ds).toLowerCase().includes(q) ||ds.id.toLowerCase().startsWith(q) ||(ds.capabilityName ?? "").toLowerCase().includes(q) ||- (SOURCE_KIND_LABEL[ds.sourceKind] ?? "").toLowerCase().includes(q)+ [+ describeSource(ds, nameById)?.label ?? "",+ ...(describeSource(ds, nameById)?.more ?? []),+ ].some((text) => text.toLowerCase().includes(q)));});};@@ -107,17 +135,16 @@ export function DatasetsToolbar({filters={<><Select onValueChange={setRoleFilter} value={roleFilter}>- <SelectTrigger aria-label="Filter by role" className="w-[140px]" size="default">+ <SelectTrigger aria-label="Filter by role" className="w-[160px]" size="default"><SelectValue placeholder="All roles" /></SelectTrigger><SelectContent><SelectItem value="all">All roles</SelectItem>- {Object.entries(DATASET_ROLES).map(([value, label]) => (+ {Object.entries(ROLE_LABEL).map(([value, label]) => (<SelectItem key={value} value={value}>{label}</SelectItem>))}- <SelectItem value="unassigned">Unassigned</SelectItem></SelectContent></Select>{setCapabilityFilter && capabilityIds.length > 1 && (@@ -157,20 +184,25 @@ export function DatasetsToolbar({);}-type SortKey = "source" | "name" | "role" | "rows" | "version" | "capability" | "updated";+type SortKey = "source" | "name" | "role" | "rows" | "capability" | "updated";++const sourceText = (ds: Dataset, nameById: Record<string, string>): string =>+ describeSource(ds, nameById)?.label ?? "";-const sortValue = (ds: Dataset, key: SortKey): string | number => {+const sortValue = (+ ds: Dataset,+ key: SortKey,+ nameById: Record<string, string>+): string | number => {switch (key) {case "source":- return SOURCE_KIND_LABEL[ds.sourceKind] ?? ds.sourceKind;+ return sourceText(ds, nameById).toLowerCase();case "name":return datasetDisplayName(ds).toLowerCase();case "role":- return ds.roles.map((role) => DATASET_ROLES[role] ?? role).join(", ");+ return ROLE_LABEL[roleOf(ds)];case "rows":- return ds.rows ?? 0;- case "version":- return ds.activeVersion ?? "";+ return ds.activeVersion ? ds.rows : -1;case "capability":return (ds.capabilityName ?? "").toLowerCase();case "updated":@@ -178,39 +210,110 @@ const sortValue = (ds: Dataset, key: SortKey): string | number => {}};-// The widest glyphs of the table's text, in pixels: an estimate must not fall short.-const CHAR_PX = 7;+/** One height, border and type size for every chip the table shows. */+const TABLE_CHIP =+ "inline-flex h-5 max-w-full min-w-0 items-center gap-1.5 rounded-sm border border-border/70 bg-transparent px-1.5 py-0 text-xs text-foreground";-function statusOf(dataset: Dataset) {+function Chip({ children, title }: { children: ReactNode; title?: string | null }) {+ if (!title) return <span className={TABLE_CHIP}>{children}</span>;+ return (+ <Tooltip>+ {/* Focusable, so a keyboard reaches what the tooltip says. */}+ <TooltipTrigger asChild>+ <span+ className={cn(TABLE_CHIP, "outline-none focus-visible:ring-2 focus-visible:ring-ring")}+ // biome-ignore lint/a11y/noNoninteractiveTabindex: the tooltip is its content+ tabIndex={0}+ >+ {children}+ </span>+ </TooltipTrigger>+ <TooltipContent>{title}</TooltipContent>+ </Tooltip>+ );+}++const Dash = () => <span className="text-sm text-muted-foreground">—</span>;++interface SourceDescription {+ icon: ReactNode;+ label: string;+ more: string[];+}++/** One label for any source: files, pasted rows, traces, LLM calls or another dataset. */+function describeSource(ds: Dataset, nameById: Record<string, string>): SourceDescription | null {+ const spec = (ds.sourceSpec ?? {}) as {+ sources?: { filename: string }[];+ filename?: string;+ pasted?: boolean;+ derived_from?: { dataset_id?: string; version?: string };+ partition_plan?: string;+ role?: string;+ };+ const icon = (Glyph: (typeof Icon)[keyof typeof Icon]) => <Glyph className="size-3.5 shrink-0" />;+ if (spec.derived_from) {+ const name = nameById[spec.derived_from.dataset_id ?? ""] ?? "a dataset";+ const version = spec.derived_from.version ? ` ${spec.derived_from.version}` : "";+ return { icon: icon(Icon.gitBranch), label: `From ${name}${version}`, more: [] };+ }+ if (spec.partition_plan)+ return {+ icon: icon(Icon.gitBranch),+ label: `Split · ${SPLIT_LABEL[spec.role ?? ""] ?? spec.role}`,+ more: [],+ };+ if (ds.sourceKind === "traces")+ return { icon: icon(Icon.observability), label: "Traces", more: [] };+ if (ds.sourceKind === "llm_calls")+ return { icon: icon(Icon.model), label: "LLM calls", more: [] };+ const files = spec.sources?.length+ ? spec.sources.map((source) => source.filename)+ : spec.filename+ ? [spec.filename]+ : [];+ // Rows sent inline (pasted, or given through the API) name no file.+ if (!files.length)+ return ds.activeVersion && ds.sourceKind === "file"+ ? { icon: icon(Icon.clipboard), label: "Inline rows", more: [] }+ : null;+ return {+ icon: <FileTypeIcon className="size-3.5" filename={files[0]} />,+ label: files[0],+ more: files.slice(1),+ };+}++/** Busy or failed work beside the name; an idle dataset shows its name alone. */+function NameStatus({ dataset }: { dataset: Dataset }) {const work = dataset.work;+ const failed = !work && dataset.state === "error";const queued =work?.status === "queued" ||(!work && dataset.state === "landing" && dataset.operation?.state === "queued");const busy = !!work || dataset.state === "running" || dataset.state === "landing";- const failed = !work && dataset.state === "error";- return { busy, failed, queued, work };-}--function statusLabel(dataset: Dataset): string {- const { busy, failed, queued, work } = statusOf(dataset);- if (!busy && !failed) return dataset.activeVersion ? "Ready" : "Waiting for source";- if (failed) return "Failed";- if (queued) return "Queued";- return work?.label ?? (dataset.state === "landing" ? "Importing" : "Transforming");-}--function DatasetStatus({ dataset }: { dataset: Dataset }) {- const { busy, failed, queued, work } = statusOf(dataset);- const label = statusLabel(dataset);- if (!busy && !failed) return <span className="text-sm text-muted-foreground">{label}</span>;+ if (!busy && !failed) return null;const completed = work?.completed;const total = work?.total;const percent =typeof completed === "number" && typeof total === "number" && total > 0? (completed / total) * 100: null;+ const label = failed+ ? "Failed"+ : queued+ ? "Queued"+ : work+ ? workText(work, { compact: true })+ : dataset.state === "landing"+ ? "Importing"+ : "Transforming";return (- <span aria-live="polite" className="inline-flex items-center gap-2">+ <span+ aria-live="polite"+ className="inline-flex shrink-0"+ title={failed ? dataset.error : undefined}+ ><ResolvedStatusBadgeactorKind={work?.actorKind ?? undefined}cfg={resolveStatus(@@ -225,9 +328,7 @@ function DatasetStatus({ dataset }: { dataset: Dataset }) {}function getColumns(opts: {- roleWidth: number;- sourceWidth: number;- statusWidth: number;+ nameById: Record<string, string>;onDelete: (ds: Dataset) => void;onDeleteClick?: (e: React.MouseEvent) => void;deletePendingId?: string | null;@@ -239,131 +340,49 @@ function getColumns(opts: {cell: ({ row }) => (<span className="flex min-w-0 items-center gap-2"><span- className="truncate font-mono text-sm text-foreground"+ className="truncate text-sm text-foreground"title={datasetDisplayName(row.original)}>{datasetDisplayName(row.original)}</span>+ <NameStatus dataset={row.original} /></span>),header: "Name",id: "name",meta: { label: "Name", orderingField: "name" },- minSize: 160,- size: 180,- },- {- cell: ({ row }) => <DatasetStatus dataset={row.original} />,- header: "Status",- id: "status",- meta: { label: "Status", noTruncate: true },- minSize: opts.statusWidth,- size: opts.statusWidth,- },- {- accessorFn: (row) => row.roles.join(", "),- cell: ({ row }) =>- row.original.roles.length ? (- <span className="inline-flex flex-nowrap gap-1">- {row.original.roles.map((role) => (- <Badge key={role} size="chip" variant="outline">- {DATASET_ROLES[role] ?? role}- </Badge>- ))}- </span>- ) : (- <span className="text-muted-foreground">—</span>- ),- header: "Role",- id: "role",- meta: { label: "Role", noTruncate: true, orderingField: "role" },- minSize: opts.roleWidth,- size: opts.roleWidth,- },- {- accessorFn: (row) => row.activeVersion ?? "",- cell: ({ row }) => (- <span className="font-mono text-sm text-foreground">- {row.original.activeVersion || <span className="text-muted-foreground">—</span>}- </span>- ),- header: "Version",- id: "version",- meta: { label: "Version", orderingField: "version" },- minSize: 88,- size: 88,- },- {- accessorFn: (row) => row.rows ?? 0,- cell: ({ row }) => (- <span className="tabular-nums text-sm text-foreground">- {row.original.activeVersion ? (- row.original.rows.toLocaleString()- ) : (- <span className="text-muted-foreground">—</span>- )}- </span>- ),- header: "Rows",- id: "rows",- meta: { label: "Rows", orderingField: "rows" },- minSize: 80,- size: 80,+ minSize: 200,+ size: 280,},{- accessorKey: "sourceKind",+ accessorFn: (row) => ROLE_LABEL[roleOf(row)],cell: ({ row }) => {- const dataset = row.original;- const sources: { filename: string }[] = dataset.sourceSpec?.sources ?? [];- const filenames = sources.length- ? sources.map((source) => source.filename)- : dataset.sourceSpec?.filename- ? [String(dataset.sourceSpec.filename)]- : [];- return filenames.length ? (- <span className="flex min-w-0 items-center gap-1 whitespace-nowrap">- {filenames.slice(0, 1).map((filename, index) => {- const extension = filename.replace(/\.gz$/i, "").match(/\.([^.]+)$/)?.[1];- return (- <Badge- className="min-w-0 max-w-full gap-1.5"- key={`${filename}:${index}`}- size="chip"- title={filename}- variant="outline"- >- <FileTypeIcon className="size-3" filename={filename} />- <span className="min-w-0 truncate">{filename}</span>- <span className="shrink-0 text-muted-foreground">- {extension?.toUpperCase() ?? "File"}- </span>- </Badge>- );- })}- {filenames.length > 1 && (- <Badge- aria-label={`Also ${filenames.slice(1).join(", ")}`}- className="shrink-0"- size="chip"- tabIndex={0}- title={filenames.slice(1).join(", ")}- variant="outline"- >- +{filenames.length - 1}- </Badge>- )}- </span>- ) : (- <span className="text-sm text-foreground">- {SOURCE_KIND_LABEL[dataset.sourceKind] ?? dataset.sourceKind}- </span>+ const role = roleOf(row.original);+ const used = usedText(row.original);+ if (role === "pending" && !used) return <Dash />;+ // With no intent, a used dataset (often the source of a split) shows its uses.+ const fromUses = role === "pending";+ return (+ <Chip title={fromUses ? `Intent not set · ${used}` : used}>+ <span className="truncate font-mono">+ {fromUses+ ? USES.filter(([use]) => row.original.roles.includes(use as never))+ .map(([use, short]) => {+ // The training half of a split names its format: "Train · SFT + Eval".+ const format = (row.original as WorkspaceDataset).useFormat;+ return use === "training" && format ? intentLabel("train", format) : short;+ })+ .join(" + ")+ : ROLE_LABEL[role]}+ </span>+ </Chip>);},- header: "Source",- id: "source",- meta: { label: "Source", noTruncate: true, orderingField: "source" },- minSize: opts.sourceWidth,- size: opts.sourceWidth,+ header: "Role",+ id: "role",+ meta: { label: "Role", noTruncate: true, orderingField: "role" },+ minSize: 130,+ size: 140,},];@@ -372,25 +391,66 @@ function getColumns(opts: {accessorFn: (row) => row.capabilityName ?? "",cell: ({ row }) =>row.original.capability ? (- <div className="flex w-full justify-start">+ <div className="flex w-full min-w-0 justify-start"><EntityRef+ className={TABLE_CHIP}id={row.original.capability}kind="capability"name={row.original.capabilityName}/></div>) : (- <span className="text-muted-foreground">—</span>+ <Dash />),header: "Capability",id: "capability",meta: { label: "Capability", noTruncate: true, orderingField: "capability" },minSize: 120,- size: 140,+ size: 150,});}cols.push(+ {+ accessorFn: (row) => row.rows ?? 0,+ cell: ({ row }) =>+ row.original.activeVersion ? (+ <span+ className="text-sm tabular-nums text-foreground"+ title={row.original.rows.toLocaleString()}+ >+ {compactCount(row.original.rows)}+ </span>+ ) : (+ <Dash />+ ),+ header: "Datapoints",+ id: "rows",+ meta: { label: "Datapoints", orderingField: "rows" },+ minSize: 96,+ size: 104,+ },+ {+ accessorFn: (row) => sourceText(row, opts.nameById),+ cell: ({ row }) => {+ const source = describeSource(row.original, opts.nameById);+ if (!source) return <Dash />;+ return (+ <Chip title={[source.label, ...source.more].join(", ")}>+ {source.icon}+ <span className="min-w-0 truncate">{source.label}</span>+ {source.more.length > 0 && (+ <span className="shrink-0 text-muted-foreground">+{source.more.length}</span>+ )}+ </Chip>+ );+ },+ header: "Source",+ id: "source",+ meta: { label: "Source", noTruncate: true, orderingField: "source" },+ minSize: 140,+ size: 200,+ },{accessorKey: "updatedAt",cell: ({ row }) => (@@ -514,9 +574,15 @@ export function DatasetsBrowser({const [pageSize, setPageSize] = useState(25);const [ordering, setOrdering] = useState<string | undefined>("-updated");+ // Keyed by the names themselves: the inventory is a new array on every render, and new+ // columns would reset the table.+ const names = JSON.stringify(+ datasets.map((dataset) => [dataset.id, datasetDisplayName(dataset)])+ );+ const nameById = useMemo(() => Object.fromEntries(JSON.parse(names)), [names]);const filtered = useMemo(- () => filterDatasets(datasets, search, roleFilter, capabilityFilter),- [datasets, search, roleFilter, capabilityFilter]+ () => filterDatasets(datasets, search, roleFilter, capabilityFilter, nameById),+ [datasets, search, roleFilter, capabilityFilter, nameById]);const sorted = useMemo(() => {const parsed = parseDrfOrdering(ordering);@@ -524,66 +590,28 @@ export function DatasetsBrowser({const key = parsed.field as SortKey;const dir = parsed.dir === "desc" ? -1 : 1;return [...filtered].sort((a, b) => {- const va = sortValue(a, key);- const vb = sortValue(b, key);+ const va = sortValue(a, key, nameById);+ const vb = sortValue(b, key, nameById);if (va < vb) return -dir;if (va > vb) return dir;return 0;});- }, [filtered, ordering]);+ }, [filtered, ordering, nameById]);const currentPage = Math.min(page, Math.max(1, Math.ceil(sorted.length / pageSize)));const pageRows = sorted.slice((currentPage - 1) * pageSize, currentPage * pageSize);const hasActiveFilters = roleFilter !== "all" || capabilityFilter !== "all" || !!search;- // A column is as wide as the widest thing it shows now: a cell clips what does not fit.- const roleWidth = Math.max(- 100,- ...datasets.map((dataset) =>- dataset.roles.reduce(- (width, role, index) =>- width + (DATASET_ROLES[role] ?? role).length * CHAR_PX + 19 + (index ? 5 : 0),- 16- )- )- );- // A status at work is a badge: an icon and padding beside its label.- const statusWidth = Math.max(- 120,- ...datasets.map((dataset) => {- const { busy, failed } = statusOf(dataset);- return statusLabel(dataset).length * CHAR_PX + (busy || failed ? 52 : 16);- })- );- // A column of dashes says nothing and costs the width the others need.- const noCapabilities = !datasets.some((dataset) => dataset.capability);- const sourceWidth = datasets.some(- (dataset) => dataset.sourceSpec?.sources?.length || dataset.sourceSpec?.filename- )- ? 160- : 90;-const selectable = !!onRowSelectionChange;const columns = useMemo(() => {const base = getColumns({deletePendingId: deleteMutation.isPending ? deleteMutation.variables : null,- hideCapabilityColumn: hideCapabilityColumn || noCapabilities,+ hideCapabilityColumn,+ nameById,onDelete: (ds) => deleteMutation.mutate(ds.id),onDeleteClick: guard(() => undefined),- roleWidth,- sourceWidth,- statusWidth,});return selectable ? [ATTACH_COLUMN, ...base] : base;- }, [- deleteMutation,- guard,- hideCapabilityColumn,- noCapabilities,- roleWidth,- selectable,- sourceWidth,- statusWidth,- ]);+ }, [deleteMutation, guard, hideCapabilityColumn, nameById, selectable]);return (<DataTablediff --git a/frontend/src/components/datasets/new-dataset-dialog.test.tsx b/frontend/src/components/datasets/new-dataset-dialog.test.tsxindex 7924abc7..f829aa39 100644--- a/frontend/src/components/datasets/new-dataset-dialog.test.tsx+++ b/frontend/src/components/datasets/new-dataset-dialog.test.tsx@@ -60,7 +60,7 @@ function choose(label: string, option: string) {}describe("dataset file dialog", () => {- it("allows exploration before choosing a purpose and resets that choice when reopened", async () => {+ it("creates before an intent is chosen and resets the choice when reopened", async () => {const props = {initialFiles: [new File(["a"], "first.csv")],onOpenChange: vi.fn(),@@ -70,31 +70,20 @@ describe("dataset file dialog", () => {await within(screen.getByRole("list", { name: "Selected files" })).findByText("7 rows");const create = screen.getByRole("button", { name: "Create dataset" }) as HTMLButtonElement;expect(create.disabled).toBe(false);- expect(screen.getByRole("combobox", { name: "Purpose" }).textContent).toBe(- "Choose in workshop"- );- fireEvent.keyDown(screen.getByRole("combobox", { name: "Purpose" }), { key: "ArrowDown" });- expect(screen.getAllByRole("option").map((option) => option.textContent)).toEqual([- "Choose in workshop",- "Data exploration",- "Evaluation",- "Training",- "Train + eval",- ]);- fireEvent.click(screen.getByRole("option", { name: "Training" }));+ expect(screen.getByRole("combobox", { name: "Intent" }).textContent).toBe("Not set");+ fireEvent.keyDown(screen.getByRole("combobox", { name: "Intent" }), { key: "ArrowDown" });+ fireEvent.click(screen.getByRole("option", { name: "Train" }));expect(create.disabled).toBe(false);view.rerender(<NewDatasetDialog {...props} open={false} />);view.rerender(<NewDatasetDialog {...props} open />);- expect(screen.getByRole("combobox", { name: "Purpose" }).textContent).toBe(- "Choose in workshop"- );+ expect(screen.getByRole("combobox", { name: "Intent" }).textContent).toBe("Not set");expect((screen.getByRole("button", { name: "Create dataset" }) as HTMLButtonElement).disabled).toBe(true);});it.each([- "Training",+ "Train","Train + eval",])("preserves an explicit None capability for %s", async (purpose) => {render(@@ -108,14 +97,14 @@ describe("dataset file dialog", () => {);await within(screen.getByRole("list", { name: "Selected files" })).findByText("7 rows");choose("Capability", "None");- choose("Purpose", purpose);+ choose("Intent", purpose);fireEvent.click(screen.getByRole("button", {- name: purpose === "Training" ? "Create dataset" : "Create datasets",+ name: purpose === "Train" ? "Create dataset" : "Create datasets",}));await waitFor(() =>- expect(purpose === "Training" ? mocks.create : mocks.split).toHaveBeenCalledWith(+ expect(purpose === "Train" ? mocks.create : mocks.split).toHaveBeenCalledWith(expect.objectContaining({ capabilityId: null })));@@ -139,7 +128,7 @@ describe("dataset file dialog", () => {expect(within(list).queryByText("first.csv")).toBeNull();expect((screen.getByLabelText("Dataset name") as HTMLInputElement).value).toBe("Support data");choose("Capability", "Support");- choose("Purpose", "Evaluation");+ choose("Intent", "Eval");fireEvent.click(screen.getByRole("button", { name: "Create dataset" }));await waitFor(() =>expect(mocks.create).toHaveBeenCalledWith({@@ -147,6 +136,7 @@ describe("dataset file dialog", () => {capabilityId: "cap",intent: "eval",name: "Support data",+ prepare: true,projectId: "project",source: { uploads: ["second.jsonl"] },})@@ -164,7 +154,7 @@ describe("dataset file dialog", () => {);await screen.findByText("15 rows");expect(screen.queryByRole("spinbutton", { name: "Data split" })).toBeNull();- choose("Purpose", "Train + eval");+ choose("Intent", "Train + eval");expect(screen.queryByLabelText("Group columns")).toBeNull();expect(screen.queryByLabelText("Stratify by")).toBeNull();expect(screen.queryByText(/Estimated counts\./)).toBeNull();@@ -185,6 +175,7 @@ describe("dataset file dialog", () => {evalPercent: 40,name: "first",position: "tail",+ prepare: true,projectId: "project",source: { uploads: ["first.csv", "second.jsonl"] },})@@ -202,7 +193,7 @@ describe("dataset file dialog", () => {/>);await screen.findByText("1 row");- choose("Purpose", "Train + eval");+ choose("Intent", "Train + eval");expect(screen.getByRole("alert").textContent).toContain("At least two rows");const create = screen.getByRole("button", { name: "Create datasets" }) as HTMLButtonElement;expect(create.disabled).toBe(true);@@ -211,7 +202,7 @@ describe("dataset file dialog", () => {});expect(screen.getByRole("alert").textContent).toContain("1 to 99");expect(create.disabled).toBe(true);- choose("Purpose", "Training");+ choose("Intent", "Train");expect(screen.queryByRole("spinbutton", { name: "Data split" })).toBeNull();expect((screen.getByRole("button", { name: "Create dataset" }) as HTMLButtonElement).disableddiff --git a/frontend/src/components/datasets/new-dataset-dialog.tsx b/frontend/src/components/datasets/new-dataset-dialog.tsxindex dad53519..fd414d5d 100644--- a/frontend/src/components/datasets/new-dataset-dialog.tsx+++ b/frontend/src/components/datasets/new-dataset-dialog.tsx@@ -43,12 +43,11 @@ import { errorMessage } from "@/lib/notify";import { cn } from "@/lib/utils";import type { Dataset, SourceRequest } from "@/openapi";-type Purpose = "train" | "eval" | "explore" | "split" | "pending";-const PURPOSES: Array<{ value: Purpose; label: string }> = [- { label: "Choose in workshop", value: "pending" },- { label: "Data exploration", value: "explore" },- { label: "Evaluation", value: "eval" },- { label: "Training", value: "train" },+type IntentChoice = "train" | "eval" | "split" | "pending";+const INTENTS: Array<{ value: IntentChoice; label: string }> = [+ { label: "Not set", value: "pending" },+ { label: "Eval", value: "eval" },+ { label: "Train", value: "train" },{ label: "Train + eval", value: "split" },];const POSITIONS: Array<{ value: SplitPosition; label: string }> = [@@ -97,8 +96,8 @@ export function NewDatasetDialog({const defaultCapabilityId =initialCapabilityId ?? (sourceType === "traces" ? NO_CAPABILITY : AUTO_CAPABILITY);const [capabilityId, setCapabilityId] = useState(defaultCapabilityId);- const [filePurpose, setPurpose] = useState<Purpose>("pending");- const purpose = sourceType === "traces" ? "pending" : filePurpose;+ const [fileIntent, setIntent] = useState<IntentChoice>("pending");+ const intent = sourceType === "traces" ? "pending" : fileIntent;const [percentInput, setPercentInput] = useState("30");const [position, setPosition] = useState<SplitPosition>("tail");const [picked, setPicked] = useState<TraceSelectionState>({ status: "counting" });@@ -123,7 +122,7 @@ export function NewDatasetDialog({setName("");setNameTouched(false);setCapabilityId(defaultCapabilityId);- setPurpose("pending");+ setIntent("pending");setBrief("");setPercentInput("30");setPosition("tail");@@ -167,7 +166,7 @@ export function NewDatasetDialog({const canStart = ready || (sourceType === "file" && upload.files.length === 0 && !!brief.trim());const rows = ready ? readiness.rows : undefined;const splitError =- purpose === "split"+ intent === "split"? !validPercent? "Enter a percentage from 1 to 99.": rows !== undefined && rows < 2@@ -202,7 +201,7 @@ export function NewDatasetDialog({);const handleSubmit = async () => {- if (!canStart || busy || splitError || (purpose === "split" && !ready)) return;+ if (!canStart || busy || splitError || (intent === "split" && !ready)) return;setError(null);const base = {brief: sourceType === "traces" ? "" : brief.trim(),@@ -213,11 +212,13 @@ export function NewDatasetDialog({? null: capabilityId,name: name.trim() || suggestedName || "Untitled dataset",+ // A stated intent or brief starts the assistant's first pass once the source lands.+ prepare: !!ready && (intent !== "pending" || !!brief.trim()),projectId,source: ready ? readiness.source : undefined,};try {- if (purpose === "split") {+ if (intent === "split") {const pair = await createSplit.mutateAsync({...base,deduplicate: true,@@ -227,7 +228,7 @@ export function NewDatasetDialog({});finish(pair.train);} else {- finish(await create.mutateAsync({ ...base, intent: purpose }));+ finish(await create.mutateAsync({ ...base, intent }));}} catch (err) {setError(errorMessage(err, "Couldn't create the dataset."));@@ -300,20 +301,20 @@ export function NewDatasetDialog({</div>{sourceType === "file" && (<div className="flex min-w-0 flex-col gap-1.5">- <Label className="text-xs text-muted-foreground" htmlFor="dataset-purpose">- Purpose+ <Label className="text-xs text-muted-foreground" htmlFor="dataset-intent">+ Intent</Label><Selectdisabled={busy}- onValueChange={(value) => setPurpose(value as Purpose)}+ onValueChange={(value) => setIntent(value as IntentChoice)}required- value={purpose}+ value={intent}>- <SelectTrigger className="w-full" id="dataset-purpose">- <SelectValue placeholder="Select purpose" />+ <SelectTrigger className="w-full" id="dataset-intent">+ <SelectValue placeholder="Select intent" /></SelectTrigger><SelectContent>- {PURPOSES.map((option) => (+ {INTENTS.map((option) => (<SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>@@ -324,7 +325,7 @@ export function NewDatasetDialog({)}</div>- {purpose === "split" && (+ {intent === "split" && (<section aria-label="Data split" className="flex flex-col gap-3"><div className="grid grid-cols-1 gap-x-5 gap-y-3 sm:grid-cols-2"><div className="flex flex-col gap-1.5">@@ -351,7 +352,7 @@ export function NewDatasetDialog({</div><div className="flex min-w-0 flex-col gap-1.5"><Label className="text-xs text-muted-foreground" htmlFor="eval-position">- Evaluation rows+ Eval rows</Label><Selectdisabled={busy}@@ -377,7 +378,7 @@ export function NewDatasetDialog({className="flex flex-wrap gap-x-5 gap-y-1 text-xs text-muted-foreground"><p>- Training dataset{" "}+ Train dataset{" "}<span className="tabular-nums text-foreground">{heldRows === undefined || rows === undefined? "—"@@ -385,7 +386,7 @@ export function NewDatasetDialog({</span></p><p>- Evaluation dataset{" "}+ Eval dataset{" "}<span className="tabular-nums text-foreground">{heldRows === undefined ? "—" : `${heldRows.toLocaleString()} rows`}</span>@@ -401,7 +402,7 @@ export function NewDatasetDialog({{sourceType === "file" && (<div className="flex flex-col gap-1.5"><Label className="text-xs text-muted-foreground" htmlFor="dataset-brief">- Intent (optional)+ Brief (optional)</Label><textareaclassName="min-h-16 max-h-40 w-full resize-y rounded-sm border border-border bg-background px-3 py-2 text-sm outline-none transition-colors focus-visible:border-primary placeholder:text-muted-foreground"@@ -427,18 +428,20 @@ export function NewDatasetDialog({? rows === undefined? null: `${rows.toLocaleString()} ${rows === 1 ? "row" : "rows"}`- : readiness.hint}+ : canStart && intent !== "split"+ ? null+ : readiness.hint}</span>)}<Button disabled={busy} onClick={() => onOpenChange(false)} variant="secondary">Cancel</Button><Button- disabled={!canStart || busy || !!splitError || (purpose === "split" && !ready)}+ disabled={!canStart || busy || !!splitError || (intent === "split" && !ready)}onClick={() => void handleSubmit()}>{busy ? <Spinner className="size-4" /> : <Icon.datasetAdd />}- {purpose === "split" ? "Create datasets" : "Create dataset"}+ {intent === "split" ? "Create datasets" : "Create dataset"}</Button></DialogFooter></DialogContent>diff --git a/frontend/src/components/datasets/notebook/cell-analytics.test.tsx b/frontend/src/components/datasets/notebook/cell-analytics.test.tsxdeleted file mode 100644index 86874653..00000000--- a/frontend/src/components/datasets/notebook/cell-analytics.test.tsx+++ /dev/null@@ -1,148 +0,0 @@-// @vitest-environment jsdom-// covers: measured-facts-import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";-import { afterEach, describe, expect, it } from "vitest";--import type { DatasetAnalytics } from "@/openapi";-import { AnalyticsAlerts, AnalyticsDetails } from "./cell-analytics";--afterEach(cleanup);--const report: DatasetAnalytics = {- cell: "cell",- checks: [- {- id: "targets.class_balance",- metrics: { families: ["fraud"] },- status: "warning",- summary: "Accuracy can conceal missed classes.",- title: "Class imbalance",- },- {- id: "leakage",- metrics: {},- status: "not_checked",- summary: "Requires related splits.",- title: "Split leakage",- },- {- id: "targets.validity",- metrics: {},- status: "pass",- summary: "All decision rows have valid targets.",- title: "Target validity",- },- ],- dataset: "dataset",- families: [- {- counts: [1000, 1],- id: "fraud",- labels: ["No", "Yes"],- labelsTruncated: false,- majorityBaseline: 1000 / 1001,- question: "Fraud?",- rows: 1001,- semantics: "categorical_gold",- targetMass: [1000, 1],- weightSum: 1001,- },- ],- fingerprint: "abc",- rowsScanned: 1001,- status: "completed",-};--describe("Workshop analytics", () => {- it("keeps warnings and unchecked coverage visible without opening the report", () => {- render(<AnalyticsAlerts report={report} />);- expect(screen.getByText("Class imbalance")).toBeTruthy();- expect(screen.getByText("1 not checked")).toBeTruthy();- });- it("shows exact class counts and a baseline, not model accuracy", () => {- render(<AnalyticsDetails report={report} />);- const finding = screen.getByRole("region", { name: "Class imbalance" });- expect(within(finding).getByText("Accuracy alone is misleading here")).toBeTruthy();- expect(finding.textContent).toContain("99.90% accuracy while missing all 1 “Yes” example.");- expect(finding.textContent).toContain("track precision and recall for “Yes”");- expect(finding.textContent).toContain("not a trained model result");- expect(finding.compareDocumentPosition(screen.getByRole("table")) & 4).toBe(4);- expect(screen.getByText("0.10%")).toBeTruthy();- expect(screen.getByRole("button", { name: "1 checks not assessed" })).toBeTruthy();- expect(screen.queryByText("Evidence")).toBeNull();- expect(screen.queryByRole("link")).toBeNull();- });- it("collapses completed checks while keeping coverage gaps named", () => {- render(<AnalyticsDetails report={report} />);- const button = screen.getByRole("button", { name: "1 completed checks" });- const details = document.getElementById(button.getAttribute("aria-controls")!);- expect(button.getAttribute("aria-expanded")).toBe("false");- expect(details?.hidden).toBe(true);- expect(screen.getAllByText("Split leakage").some((el) => !el.closest("[hidden]"))).toBe(true);- fireEvent.click(button);- expect(button.getAttribute("aria-expanded")).toBe("true");- expect(details?.hidden).toBe(false);- fireEvent.click(button);- expect(details?.hidden).toBe(true);- });- it("puts errors before warnings", () => {- render(- <AnalyticsDetails- report={{- ...report,- checks: [- ...report.checks,- {- id: "invalid",- metrics: {},- status: "error",- summary: "Invalid targets.",- title: "Invalid targets",- },- ],- }}- />- );- expect(screen.getAllByRole("region")[0].getAttribute("aria-label")).toBe("Invalid targets");- });- it.each([- "unknown",- "soft_distribution",- ])("never infers a missed-class claim for %s targets", (semantics) => {- render(- <AnalyticsDetails- report={{- ...report,- families: [{ ...report.families[0], counts: null, majorityBaseline: null, semantics }],- }}- />- );- expect(screen.queryByText("Accuracy alone is misleading here")).toBeNull();- expect(screen.getByText("Accuracy can conceal missed classes.")).toBeTruthy();- });- it("does not claim zero examples were missed for an absent class", () => {- render(- <AnalyticsDetails- report={{- ...report,- families: [{ ...report.families[0], counts: [1001, 0], majorityBaseline: 1 }],- }}- />- );- expect(screen.queryByText(/while missing all/)).toBeNull();- expect(screen.getByText("Accuracy can conceal missed classes.")).toBeTruthy();- });- it("does not generate a warning that Overmind did not report", () => {- render(- <AnalyticsDetails- report={{ ...report, checks: report.checks.filter((check) => check.status !== "warning") }}- />- );- expect(screen.queryByText("Accuracy alone is misleading here")).toBeNull();- expect(screen.getByText(/Always predicting/)).toBeTruthy();- });- it("does not turn absent historical analytics into a clean result", () => {- render(<AnalyticsAlerts report={undefined} />);- expect(screen.getByText("Metrics not measured")).toBeTruthy();- });-});diff --git a/frontend/src/components/datasets/notebook/cell-analytics.tsx b/frontend/src/components/datasets/notebook/cell-analytics.tsxdeleted file mode 100644index 0bd3efe0..00000000--- a/frontend/src/components/datasets/notebook/cell-analytics.tsx+++ /dev/null@@ -1,261 +0,0 @@-import { useId, useState } from "react";--import { Badge } from "@/components/ui/badge";-import { Button } from "@/components/ui/button";-import { Icon } from "@/components/ui/icons";-import type { DatasetAnalytics, DatasetAnalyticsCheck } from "@/openapi";--function tone(status: DatasetAnalyticsCheck["status"]) {- return status === "error" ? "error" : status === "warning" ? "warning" : "neutral";-}--export function AnalyticsAlerts({ report }: { report?: DatasetAnalytics }) {- if (report?.status !== "completed")- return (- <Badge size="chip" variant="neutral">- Metrics not measured- </Badge>- );- const alerts = report.checks.filter(- (check) => check.status === "warning" || check.status === "error"- );- const unchecked = report.checks.filter((check) => check.status === "not_checked").length;- return (- <span className="inline-flex min-w-0 flex-wrap items-center gap-1">- {alerts.slice(0, 2).map((check) => (- <Badge key={check.id} size="chip" title={check.summary} variant={tone(check.status)}>- {check.title}- </Badge>- ))}- {alerts.length > 2 && (- <Badge size="chip" variant="warning">- +{alerts.length - 2} alerts- </Badge>- )}- {unchecked > 0 && (- <Badge size="chip" variant="neutral">- {unchecked} not checked- </Badge>- )}- </span>- );-}--function CheckGroup({- title,- checks,- preview = false,-}: {- title: string;- checks: DatasetAnalyticsCheck[];- preview?: boolean;-}) {- const [open, setOpen] = useState(false);- const id = useId();- if (!checks.length) return null;- return (- <section className="space-y-2">- <Button- aria-controls={id}- aria-expanded={open}- className="h-auto w-full justify-start whitespace-normal py-2 text-left text-xs"- onClick={() => setOpen(!open)}- variant="secondary"- >- <Icon.chevronRight className={open ? "size-3 rotate-90" : "size-3"} />- {checks.length} {title}- </Button>- {preview && !open && (- <p className="leading-relaxed text-muted-foreground">- {checks.map((check) => check.title).join(" · ")}- </p>- )}- <dl- className="-mx-3 divide-y divide-border/60 border-y border-border/60"- hidden={!open}- id={id}- >- {checks.map((check) => (- <div- className="grid gap-1 px-3 py-2.5 sm:grid-cols-[12rem_minmax(0,1fr)] sm:gap-4"- key={check.id}- >- <dt className="text-foreground">{check.title}</dt>- <dd className="max-w-prose break-words leading-relaxed text-muted-foreground">- {check.summary}- </dd>- </div>- ))}- </dl>- </section>- );-}--function Finding({ check, report }: { check: DatasetAnalyticsCheck; report: DatasetAnalytics }) {- const familyIds = check.metrics?.families;- const families =- check.id === "targets.class_balance" && Array.isArray(familyIds)- ? report.families.filter(- (family) =>- familyIds.includes(family.id) &&- family.semantics === "categorical_gold" &&- family.majorityBaseline != null &&- family.counts &&- family.counts.length > 1 &&- family.counts.length === family.labels.length &&- Math.min(...family.counts) > 0- )- : [];- return (- <section aria-label={check.title} className="-mx-3 space-y-3 border-y border-border px-3 py-4">- <h3 className="flex items-start gap-2 text-base font-medium text-foreground">- <Icon.warning className="mt-0.5 size-4 shrink-0 text-warning" />- {families.length ? "Accuracy alone is misleading here" : check.title}- </h3>- {families.length ? (- families.map((family) => {- const counts = family.counts!;- const majority = counts.indexOf(Math.max(...counts));- const minority = counts.indexOf(Math.min(...counts));- return (- <div className="max-w-prose space-y-3 text-sm leading-relaxed" key={family.id}>- <p>{family.question}</p>- <p>- Predicting “{family.labels[majority]}” for every row gets{" "}- <strong className="font-semibold">- {(family.majorityBaseline! * 100).toFixed(2)}% accuracy- </strong>{" "}- while missing all {counts[minority].toLocaleString()} “{family.labels[minority]}”- {counts[minority] === 1 ? " example" : " examples"}.- </p>- <p>- <strong className="font-semibold">Before training:</strong> track precision and- recall for “{family.labels[minority]}”, not accuracy alone.- </p>- </div>- );- })- ) : (- <p className="max-w-prose text-sm leading-relaxed">{check.summary}</p>- )}- {families.length > 0 && <p>Baseline illustration — not a trained model result.</p>}- </section>- );-}--export function AnalyticsDetails({ report }: { report?: DatasetAnalytics }) {- if (report?.status !== "completed")- return (- <p className="px-3 pb-3 text-xs text-muted-foreground">- This version has not been scanned. Ask the agent to run dataset analytics in Overmind.- </p>- );- const alerts = report.checks- .filter((check) => check.status === "warning" || check.status === "error")- .sort((a, b) => Number(b.status === "error") - Number(a.status === "error"));- const unchecked = report.checks.filter((check) => check.status === "not_checked");- const completed = report.checks.filter((check) => check.status === "pass");- const weighted = report.checks.some(- (check) => check.id === "targets.weights" && check.status === "warning"- );- return (- <div aria-label="Dataset analytics" className="nodrag nowheel space-y-5 px-3 pb-3 text-xs">- {alerts.map((check) => (- <Finding check={check} key={check.id} report={report} />- ))}- {report.families.map((family) => {- const majority = family.counts ? family.counts.indexOf(Math.max(...family.counts)) : -1;- const showMass = !family.counts || weighted;- return (- <section className="space-y-2" key={family.id}>- <h3 className="break-words font-medium text-foreground">{family.question}</h3>- <div className="-mx-3 overflow-x-auto">- <table className="w-full text-left tabular-nums">- <caption className="sr-only">Target distribution for {family.question}</caption>- <thead className="text-muted-foreground">- <tr className="border-b border-border/70">- <th className="px-3 py-1.5 font-normal" scope="col">- Label- </th>- <th className="px-3 py-1.5 text-right font-normal" scope="col">- Examples- </th>- <th className="px-3 py-1.5 text-right font-normal" scope="col">- Share- </th>- {showMass && (- <th className="px-3 py-1.5 text-right font-normal" scope="col">- Weighted target total- </th>- )}- </tr>- </thead>- <tbody>- {family.labels.map((label, index) => (- <tr className="border-b border-border/60" key={`${family.id}-${index}`}>- <th className="max-w-48 break-words px-3 py-2 font-normal" scope="row">- {label}- </th>- <td className="px-3 py-2 text-right">- {family.counts?.[index].toLocaleString() ?? "—"}- </td>- <td className="px-3 py-2 text-right">- {family.counts- ? `${((100 * family.counts[index]) / family.rows).toFixed(2)}%`- : "—"}- </td>- {showMass && (- <td className="px-3 py-2 text-right">- {family.targetMass?.[index].toLocaleString() ?? "—"}- </td>- )}- </tr>- ))}- </tbody>- </table>- </div>- {family.majorityBaseline != null && majority >= 0 ? (- !alerts.some(- (check) =>- check.id === "targets.class_balance" &&- Array.isArray(check.metrics?.families) &&- check.metrics.families.includes(family.id)- ) && (- <p className="leading-relaxed">- Always predicting “{family.labels[majority]}” scores{" "}- {(family.majorityBaseline * 100).toFixed(2)}% accuracy.- <span className="ml-1 text-muted-foreground">- Baseline only, not a trained model result.- </span>- </p>- )- ) : (- <p className="leading-relaxed text-muted-foreground">- {family.semantics === "unknown"- ? "Target meaning is undeclared. Label counts and an accuracy baseline cannot be reported."- : "These targets are distributions or numeric means, not observed labels. No label counts or accuracy baseline were inferred."}- </p>- )}- {family.labelsTruncated && (- <p className="text-muted-foreground">- Long labels are abbreviated; their original order is preserved.- </p>- )}- </section>- );- })}- <CheckGroup checks={unchecked} preview title="checks not assessed" />- <CheckGroup checks={completed} title="completed checks" />- <div className="space-y-1 text-muted-foreground" title={report.fingerprint}>- <p>- {report.rowsScanned?.toLocaleString()} rows scanned · Entire dataset- {report.measuredAt && <> · {report.measuredAt.toLocaleString()}</>}- </p>- <p>- Measured by Overmind · Checks v{report.version} · Data fingerprint{" "}- {report.fingerprint.slice(0, 12)}- </p>- </div>- </div>- );-}diff --git a/frontend/src/components/datasets/notebook/cell-flow.tsx b/frontend/src/components/datasets/notebook/cell-flow.tsxindex f9e97821..7b0b2c7e 100644--- a/frontend/src/components/datasets/notebook/cell-flow.tsx+++ b/frontend/src/components/datasets/notebook/cell-flow.tsx@@ -22,8 +22,9 @@ import {} from "@xyflow/react";import ELK from "elkjs/lib/elk.bundled.js";+import { Field } from "@/components/datasets/notebook/field";import { Icon } from "@/components/ui/icons";-import { usePersistedState } from "@/hooks/use-persisted-state";+import { SPLIT_LABEL } from "@/hooks/use-datasets";import { notify } from "@/lib/notify";import type { Cell } from "@/openapi";import { type CellMotion, CellMotionFrame, type CompleteCellMotion } from "./cell-motion";@@ -39,7 +40,6 @@ type CellNode = Node<},"cell">;-const GRID: [number, number] = [20, 20];const elk = new ELK();function CellFrame({ id, data }: NodeProps<CellNode>) {@@ -52,21 +52,43 @@ function CellFrame({ id, data }: NodeProps<CellNode>) {const NODE_TYPES = { cell: CellFrame };+const EDGE_LABEL: Record<string, string> = {+ attachment: "Added files",+ derived: "Derived",+};++/** What a connection does: a branch condition, a partition role, a derivation. */+function EdgeTag({ kind, value }: { kind: string; value: string }) {+ if (kind === "condition")+ return (+ <Field label="If" title={value}>+ <span className="truncate font-mono">{value}</span>+ </Field>+ );+ if (kind === "split") return <Field label="Split">{SPLIT_LABEL[value] ?? value}</Field>;+ const label = EDGE_LABEL[kind];+ return label ? (+ <span className="inline-flex h-6 items-center rounded-sm border border-border/70 bg-card px-2 text-xs text-muted-foreground">+ {label}+ </span>+ ) : null;+}+function CellConnector(props: EdgeProps) {const [path] = getSmoothStepPath({ ...props, borderRadius: 0, offset: 0 });+ const data = props.data as { kind: string; value: string } | undefined;return (<><BaseEdge id={props.id} path={path} style={props.style} />- {props.label && (+ {data && data.kind !== "step" && (<EdgeLabelRenderer><div- className="absolute max-w-80 truncate rounded-sm border border-input bg-card px-2 py-1 text-xs text-foreground"+ className="absolute max-w-80"style={{transform: `translate(-50%, -100%) translate(${props.targetX}px, ${props.targetY - 32}px)`,}}- title={String(props.label)}>- {props.label}+ <EdgeTag kind={data.kind} value={data.value} /></div></EdgeLabelRenderer>)}@@ -79,7 +101,6 @@ const EDGE_TYPES = { cell: CellConnector };type Props = {cells: Cell[];edges: Edge[];- storageKey: string;showMinimap: boolean;focus: { id: string; request: number } | null;renderCell: (cell: Cell) => ReactNode;@@ -90,7 +111,6 @@ type Props = {function Canvas({cells,edges,- storageKey,showMinimap,focus,renderCell,@@ -100,7 +120,6 @@ function Canvas({const wrapper = useRef<HTMLDivElement>(null);const [width, setWidth] = useState(960);const [inset, setInset] = useState(16);- const [positions, savePositions] = usePersistedState<Record<string, XYPosition>>(storageKey, {});const [nodes, setNodes, onNodesChange] = useNodesState<CellNode>([]);const { getNodes, getViewport, setViewport } = useReactFlow<CellNode>();const initialized = useNodesInitialized();@@ -144,7 +163,6 @@ function Canvas({motion: motions.get(cell.id),ready: previous?.data.ready ?? false,},- dragHandle: ".workshop-cell-node article > div:first-of-type",id: cell.id,position: previous?.position ?? { x: 0, y: index * 580 },style: { width },@@ -186,23 +204,19 @@ function Canvas({if (cancelled) return;const anchor = current.find((node) => node.data.ready);const anchorLayout = layout.children?.find((node) => node.id === anchor?.id);+ // The layout owns every position; a relayout keeps the first placed cell still.const offset =- anchor && anchorLayout && !positions[anchor.id]+ anchor && anchorLayout? {x: anchor.position.x - (anchorLayout.x ?? 0),y: anchor.position.y - (anchorLayout.y ?? 0),}: { x: 0, y: 0 };const placedPosition = (id: string): XYPosition => {- const saved = positions[id];const placed = layout.children?.find((node) => node.id === id);- const point =- saved && Number.isFinite(saved.x) && Number.isFinite(saved.y)- ? saved- : { x: (placed?.x ?? 0) + offset.x, y: (placed?.y ?? 0) + offset.y };return {- x: Math.round((point?.x ?? 0) / 20) * 20,- y: Math.round((point?.y ?? 0) / 20) * 20,+ x: Math.round((placed?.x ?? 0) + offset.x),+ y: Math.round((placed?.y ?? 0) + offset.y),};};const key = focus ? `${focus.id}:${focus.request}` : "";@@ -234,7 +248,7 @@ function Canvas({// Move graph coordinates so connectors follow their cells on every frame.setNodes((latest) =>latest.map((node) => {- if (!ids.has(node.id) || node.dragging) return node;+ if (!ids.has(node.id)) return node;const target = placedPosition(node.id);const start = starts.get(node.id) ?? target;return {@@ -291,7 +305,6 @@ function Canvas({measurements,width,inset,- positions,focus,getNodes,getViewport,@@ -308,6 +321,11 @@ function Canvas({<div className="h-full min-h-0" ref={wrapper}><ReactFlow<CellNode>aria-label="Dataset transformation flow"+ // Cells are placed by the layout and never deleted from the canvas.+ ariaLabelConfig={{+ "node.a11yDescription.default": "Press enter or space to select a cell.",+ "node.a11yDescription.keyboardDisabled": "Press enter or space to select a cell.",+ }}colorMode="dark"deleteKeyCode={null}edges={visibleEdges}@@ -317,25 +335,11 @@ function Canvas({minZoom={0.25}nodes={nodes}nodesConnectable={false}+ nodesDraggable={false}nodeTypes={NODE_TYPES}- onNodesChange={(changes) => {- onNodesChange(changes);- const moved = changes.filter(- (change) => change.type === "position" && change.position && !change.dragging- );- if (moved.length)- savePositions((previous) => {- const next = { ...previous };- for (const change of moved)- if (change.type === "position" && change.position)- next[change.id] = change.position;- return next;- });- }}+ onNodesChange={onNodesChange}panOnScrollproOptions={{ hideAttribution: true }}- snapGrid={GRID}- snapToGridzoomOnDoubleClick={false}zoomOnPinchzoomOnScroll@@ -389,7 +393,7 @@ function Canvas({export function CellFlow(props: Props) {return (- <ReactFlowProvider key={props.storageKey}>+ <ReactFlowProvider><Canvas {...props} /></ReactFlowProvider>);diff --git a/frontend/src/components/datasets/notebook/cell-labels.test.tsx b/frontend/src/components/datasets/notebook/cell-labels.test.tsxnew file mode 100644index 00000000..67eb7d2a--- /dev/null+++ b/frontend/src/components/datasets/notebook/cell-labels.test.tsx@@ -0,0 +1,31 @@+// @vitest-environment jsdom+// covers: measured-facts+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, expect, it } from "vitest";++import type { Cell } from "@/openapi";+import { CellLabels } from "./cell-labels";++afterEach(cleanup);++it("shows each label's share of the rows", () => {+ const cell = {+ analytics: {+ families: [+ {+ counts: [1000, 1],+ id: "fraud",+ labels: ["No", "Yes"],+ question: "Fraud?",+ rows: 1001,+ targetMass: [1000, 1],+ },+ ],+ status: "completed",+ },+ rows: 1001,+ } as unknown as Cell;+ render(<CellLabels cell={cell} />);+ expect(screen.getByText("0.10%")).toBeTruthy();+ expect(screen.getByText("99.90%")).toBeTruthy();+});diff --git a/frontend/src/components/datasets/notebook/cell-labels.tsx b/frontend/src/components/datasets/notebook/cell-labels.tsxnew file mode 100644index 00000000..ecdee4de--- /dev/null+++ b/frontend/src/components/datasets/notebook/cell-labels.tsx@@ -0,0 +1,70 @@+import type { Cell } from "@/openapi";++/** How a decision version's rows spread over each question's labels. */+export function CellLabels({ cell }: { cell: Cell }) {+ const families = cell.analytics?.status === "completed" ? cell.analytics.families : [];+ return (+ <div aria-label="Labels" className="nodrag nowheel space-y-4 px-3 pb-3 text-xs">+ {families.map((family) => {+ // Observed labels are row counts; soft targets are weighted probability mass.+ const mass = !family.counts;+ const total = mass ? family.weightSum || family.rows : family.rows;+ return (+ <section className="space-y-2" key={family.id}>+ <h3 className="line-clamp-2 break-words text-foreground" title={family.question}>+ {family.question}+ </h3>+ <div className="-mx-3 overflow-x-auto">+ <table className="w-full text-left tabular-nums">+ <caption className="sr-only">Labels for {family.question}</caption>+ <thead className="text-muted-foreground">+ <tr className="border-b border-border/70">+ <th className="px-3 py-1.5 font-normal" scope="col">+ Label+ </th>+ <th className="px-3 py-1.5 text-right font-normal" scope="col">+ {mass ? "Target mass" : "Rows"}+ </th>+ <th className="w-40 px-3 py-1.5 text-right font-normal" scope="col">+ Share+ </th>+ </tr>+ </thead>+ <tbody>+ {family.labels.map((label, index) => {+ const amount = family.counts?.[index] ?? family.targetMass?.[index];+ return (+ <tr className="border-b border-border/60" key={`${family.id}-${index}`}>+ <th className="max-w-48 break-words px-3 py-2 font-normal" scope="row">+ {label}+ </th>+ <td className="px-3 py-2 text-right">{amount?.toLocaleString() ?? "—"}</td>+ <td className="w-40 px-3 py-2">+ {amount == null ? (+ "—"+ ) : (+ <span className="flex items-center gap-2">+ <span className="h-1.5 flex-1 overflow-hidden rounded-xs bg-muted">+ <span+ className="block h-full bg-primary/70"+ style={{ width: `${(100 * amount) / total}%` }}+ />+ </span>+ <span className="w-14 text-right">+ {((100 * amount) / total).toFixed(2)}%+ </span>+ </span>+ )}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ </section>+ );+ })}+ </div>+ );+}diff --git a/frontend/src/components/datasets/notebook/cell-motion.tsx b/frontend/src/components/datasets/notebook/cell-motion.tsxindex 4c3d5096..5a50b102 100644--- a/frontend/src/components/datasets/notebook/cell-motion.tsx+++ b/frontend/src/components/datasets/notebook/cell-motion.tsx@@ -16,8 +16,6 @@ function contentSignature(cell: Cell) {cell.columns,cell.fingerprint,cell.review,- cell.qualityReport,- cell.readiness,]);}@@ -119,7 +117,7 @@ export function CellMotionFrame({return (<div- className="workshop-cell-node nopan"+ className="nopan"data-cell-motion={ready ? motion?.kind : undefined}// Focusing a cell control must not trigger React Flow's node-centering behaviour.onFocus={(event) => event.stopPropagation()}diff --git a/frontend/src/components/datasets/notebook/cell-script.tsx b/frontend/src/components/datasets/notebook/cell-script.tsxindex 08eb092e..a78bd974 100644--- a/frontend/src/components/datasets/notebook/cell-script.tsx+++ b/frontend/src/components/datasets/notebook/cell-script.tsx@@ -3,6 +3,7 @@ import { useState } from "react";import { useInfiniteQuery, useQuery } from "@tanstack/react-query";import apiClient from "@/client";+import { Field } from "@/components/datasets/notebook/field";import { ScriptCode } from "@/components/datasets/notebook/script-code";import { Button } from "@/components/ui/button";import {@@ -15,19 +16,22 @@ import {import { LoadingState, Spinner } from "@/components/ui/spinner";import type { Cell, PackageSource } from "@/openapi";+/** The step's entrypoint, and any other file of its retained package on request. */export function CellScript({ cell }: { cell: Cell }) {- const [browsing, setBrowsing] = useState(false);- const [selected, setSelected] = useState(cell.transformation.entrypoint);+ const entrypoint = cell.transformation.entrypoint;+ const [selected, setSelected] = useState(entrypoint);+ const [listing, setListing] = useState(false);const packageId = cell.transformation._package;+ const other = selected !== entrypoint;const inventory = useQuery({- enabled: browsing && !!packageId,+ enabled: listing && !!packageId,queryFn: () =>apiClient.datasetPipelinePackages.datasetPipelinePackagesRetrieve({ id: packageId! }),queryKey: ["dataset-package", packageId],staleTime: Infinity,});const file = useInfiniteQuery({- enabled: browsing && !!packageId && !!selected,+ enabled: other && !!packageId,getNextPageParam: (page: PackageSource) => page.nextOffset ?? undefined,initialPageParam: 0,queryFn: ({ pageParam }) =>@@ -41,67 +45,57 @@ export function CellScript({ cell }: { cell: Cell }) {staleTime: Infinity,});const content = file.data?.pages.map((page) => page.content).join("") ?? "";+ const files = inventory.data?.inventory.map((item) => item.path) ?? [entrypoint];return (<div className="nodrag nowheel px-3 pt-1 pb-2.5">{packageId && (<div className="mb-2 flex min-w-0 flex-wrap items-center gap-2">- <Button onClick={() => setBrowsing(!browsing)} size="xs" variant="outline">- {browsing ? "Step script" : "Package files"}- </Button>- {browsing && inventory.data ? (- <Select onValueChange={setSelected} value={selected}>- <SelectTrigger- aria-label={`Package file for ${cell.title}`}- className="max-w-full"- size="xs"- >- <SelectValue />- </SelectTrigger>- <SelectContent>- {inventory.data.inventory.map((item) => (- <SelectItem key={item.path} value={item.path}>- {item.path} · {item.bytes.toLocaleString()} bytes- </SelectItem>- ))}- </SelectContent>- </Select>- ) : (- <span className="break-all font-mono text-xs text-muted-foreground">- {cell.transformation.entrypoint}+ <Select+ onOpenChange={(open) => open && setListing(true)}+ onValueChange={setSelected}+ value={selected}+ >+ <SelectTrigger+ aria-label={`Package file for ${cell.title}`}+ className="max-w-full font-mono"+ size="xs"+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(files.includes(selected) ? files : [selected, ...files]).map((path) => (+ <SelectItem className="font-mono" key={path} value={path}>+ {path}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Field label="Revision">{cell.transformation.revision}</Field>+ {inventory.isError && (+ <span className="flex items-center gap-2 text-xs text-muted-foreground" role="alert">+ Package files could not be listed.+ <Button onClick={() => void inventory.refetch()} size="xs" variant="outline">+ Retry+ </Button></span>)}- <span className="text-xs text-muted-foreground">- Revision {cell.transformation.revision}- </span></div>)}- {!browsing ? (+ {!other ? (<ScriptCode aria-label={`Script of ${cell.title}`} source={cell.script} />) : (<>- {(inventory.isLoading || file.isLoading) && (- <LoadingState label="Loading retained source" />- )}- {(inventory.isError || file.isError) && (+ {file.isLoading && <LoadingState label="Loading retained source" />}+ {file.isError && (<div className="flex items-center gap-2 text-xs text-muted-foreground" role="alert">Retained source could not be loaded.- <Button- onClick={() => {- void inventory.refetch();- void file.refetch();- }}- size="xs"- variant="outline"- >+ <Button onClick={() => void file.refetch()} size="xs" variant="outline">Retry</Button></div>)}{file.data && (<>- <p className="mb-2 break-all font-mono text-xs text-muted-foreground">- SHA-256 {file.data.pages[0].sha256}- </p><ScriptCode aria-label={`${selected} retained source`} source={content} />{file.hasNextPage && (<Buttondiff --git a/frontend/src/components/datasets/notebook/cell.tsx b/frontend/src/components/datasets/notebook/cell.tsxindex 5dbd5b74..6e0d31be 100644--- a/frontend/src/components/datasets/notebook/cell.tsx+++ b/frontend/src/components/datasets/notebook/cell.tsx@@ -1,11 +1,12 @@import { type ReactNode, useEffect, useState } from "react";+import { Link } from "@tanstack/react-router";import { Handle, Position, useNodeConnections } from "@xyflow/react";-import { AnalyticsAlerts, AnalyticsDetails } from "@/components/datasets/notebook/cell-analytics";+import { CellLabels } from "@/components/datasets/notebook/cell-labels";import { CellScript } from "@/components/datasets/notebook/cell-script";+import { Field } from "@/components/datasets/notebook/field";import { RowsGrid } from "@/components/datasets/notebook/rows-grid";-import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import {Dialog,@@ -16,10 +17,9 @@ import {DialogTitle,DialogTrigger,} from "@/components/ui/dialog";-import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card";-import { Icon, type IconName } from "@/components/ui/icons";+import { Icon } from "@/components/ui/icons";import { Spinner } from "@/components/ui/spinner";-import { type CellState, columnsOf, fitOf } from "@/hooks/use-datasets";+import { type CellState, columnsOf, fitOf, intentLabel } from "@/hooks/use-datasets";import { cn } from "@/lib/utils";import type { Cell } from "@/openapi";@@ -29,24 +29,7 @@ export type UsePurpose = "train" | "train_eval" | "optimise";export interface CellActions {onUse: (purpose: UsePurpose) => void;onExport: (fmt: "jsonl" | "csv") => void;- onIntent: (intent: "train" | "eval") => void;- onCapability: (id: string | null) => void;-}--interface Suggestion {- key: string;- icon: IconName;- title: string;- hint: string;- run: () => void;- primary?: boolean;-}--export interface CapabilityChoice {- id: string;- name: string;- /** Landing's score for this table, when it ranked the capability. */- score?: number;+ onIntent: (intent: "train" | "eval", trainFormat?: "sft" | "decision") => void;}function ExportDialog({@@ -103,13 +86,11 @@ function ExportDialog({function SectionHeader({label,- alerts,meta,open,onToggle,}: {label: string;- alerts?: ReactNode;meta?: string;open: boolean;onToggle: () => void;@@ -128,7 +109,6 @@ function SectionHeader({className={cn("size-3 transition-transform duration-150", open && "rotate-90")}/><span className="pixel-label whitespace-nowrap">{label}</span>- {alerts}<span className="flex-1" />{meta && <span className="truncate font-mono tabular-nums">{meta}</span>}</button>@@ -142,346 +122,107 @@ const STATE_LABEL: Record<CellState, string> = {running: "running",};-type Report = {- ok?: boolean;- reason?: string;- rows?: number;- rows_ok?: number;- /** false when no cell holds text, so no cell could shape the table. */- fixable?: boolean;- format?: string;-};+const USES = [+ { format: "sft", intent: "train", key: "sft" },+ { format: "decision", intent: "train", key: "decision" },+ { format: "", intent: "eval", key: "eval" },+] as const;-interface Check {- label: string;- ok: boolean;- /** What the contract asks of every row. */- requires: string;- /** Columns the contract reads, marked present or missing in the frame. */- columns: string[];- /** What the report measured. */- found: string;- /** What makes it pass. */- fix?: string;- /** false when nothing the agent could add would make it pass. */- fixable?: boolean;-}--function intentCheck(intent: string, shape: Report, ran: boolean): Check {- if (intent !== "train" && intent !== "eval") {- return {- columns: [],- fix: "Select train or eval.",- found: "train or eval not chosen",- label: "Intent",- ok: false,- requires: "an intent, so the table has a shape to hold",- };- }- const label = intent === "eval" ? "Eval table" : "Train table";- const requires =- intent === "eval"- ? "an input column with a value on every row; expected_output when a reference exists"- : shape.format === "decision"- ? "a decision column with valid options and targets on every row"- : "a messages column: a list of role and content turns on every row";- const columns =- intent === "eval"- ? ["input", "expected_output"]- : shape.format === "decision"- ? ["decision"]- : ["messages"];- if (!ran)- return {- columns,- fix: "Run the cell.",- found: "the cell has not run",- label,- ok: false,- requires,- };- if (shape.ok) return { columns, found: "every row holds the shape", label, ok: true, requires };- const reason = shape.reason ?? "";- if (shape.fixable === false)- return {- columns,- fix: "None. The rows hold numbers and ids only; a different source is needed.",- fixable: false,- found: "no text in any column",- label,- ok: false,- requires,- };- let fix = "Ask the agent to shape the table.";- if (reason.startsWith("no input column"))- fix = "Add an input column: rename the prompt column or build it from messages.";- else if (reason.startsWith("no messages column"))- fix = "Add a messages column: build it from the prompt and answer columns.";- else if (reason.startsWith("no expected_output"))- fix = "Add an expected_output column with the reference answer.";- else if (reason.includes("empty input")) fix = "Drop the rows whose input is empty.";- else if (reason.includes("cut at landing"))- fix = "Drop the rows that landing cut: part of each transcript is missing.";- else if (reason.includes("no usable messages") || reason.includes(" rows: "))- fix = "Drop the rows whose messages are empty or not a list.";- else if (reason === "no rows") fix = "The table is empty. Land more rows or loosen a filter.";- return { columns, fix, found: reason || "the shape does not hold", label, ok: false, requires };-}+type Fit = Record<string, { ok: boolean; reason: string }>;-function capabilityCheck(name: string, report: Report, intent: string): Check {- const label = `${name} rows`;- const requires =- intent === "eval"- ? `every input to carry the keys ${name} requires`- : `every transcript to be ${name}'s own: its system prompt first, only its tools called`;- const columns = intent === "eval" ? ["input"] : ["messages"];- if (report.ok !== false) {- return {- columns,- found:- report.rows != null- ? `${report.rows_ok ?? report.rows} of ${report.rows} rows`- : "no contract to check",- label,- ok: true,- requires,- };- }- const reason = report.reason ?? "";- let fix = `Ask the agent to align the rows with ${name}.`;- if (reason.startsWith("system turn differs"))- fix = `Set the first message of every row to ${name}'s system prompt.`;- else if (reason.startsWith("undeclared tool calls"))- fix = `Keep only rows whose tool calls use ${name}'s tools, or drop those calls.`;- else if (reason.startsWith("missing "))- fix = `Fill the input keys ${name} requires, or drop the rows that lack them.`;- else if (reason.startsWith("no input column"))- fix = `Add an input column that carries ${name}'s input keys.`;- else if (reason.startsWith("no messages column"))- fix = "Add a messages column: a list of role and content turns per row.";- const found =- report.rows != null ? `${report.rows_ok ?? 0} of ${report.rows} rows pass; ${reason}` : reason;- return { columns, fix, found, label, ok: false, requires };-}--function CheckRow({ check, present }: { check: Check; present: Set<string> }) {- return (- <li className="flex items-start gap-2 text-xs">- {check.ok ? (- <Icon.success className="mt-0.5 size-3 shrink-0 text-success" />- ) : (- <Icon.warning className="mt-0.5 size-3 shrink-0 text-warning" />- )}- <div className="grid min-w-0 flex-1 grid-cols-[3.5rem_1fr] gap-x-2 gap-y-1">- <span className="col-span-2 text-foreground">{check.label}</span>- <span className="pixel-label text-muted-foreground">Needs</span>- <span className="text-muted-foreground">{check.requires}</span>- {check.columns.length > 0 && (- <>- <span className="pixel-label text-muted-foreground">Columns</span>- <span className="flex flex-wrap gap-1">- {check.columns.map((column) => (- <span- className={cn(- "inline-flex items-center gap-0.5 rounded-xs border px-1 font-mono",- present.has(column)- ? "border-border/70 text-foreground"- : "border-warning/40 text-warning line-through"- )}- key={column}- >- {column}- </span>- ))}- </span>- </>- )}- <span className="pixel-label text-muted-foreground">Found</span>- <span className={check.ok ? "text-muted-foreground" : "text-warning"}>{check.found}</span>- {check.fix && (- <>- <span className="pixel-label text-muted-foreground">Fix</span>- <span className="text-foreground">{check.fix}</span>- </>- )}- </div>- </li>- );-}--/** Both contracts on the frame: the chip names the first failure, the hover- * card says what each needs, which columns are there, what was found and- * what makes it pass. */-function FitChip({+/** The dataset's intent and whether this version fits it. With no intent chosen, the+ * uses the rows fit, each a one-click choice while the intent can still change. */+function IntentFields({cell,+ fixed,intent,- capabilityName,- capabilities,- actions,+ trainFormat,+ onIntent,}: {cell: Cell;+ /** A run used this version, so its intent can no longer change. */+ fixed: boolean;intent: string;- capabilityName: string;- capabilities: CapabilityChoice[];- /** Absent while the dataset is busy or frozen: the card then only reports. */- actions?: Pick<CellActions, "onIntent" | "onCapability">;+ trainFormat: string;+ /** Absent while the dataset is busy or frozen. */+ onIntent?: CellActions["onIntent"];}) {- if (intent === "explore")- return (- <Badge size="chip" variant="neutral">- Data exploration- </Badge>+ const fit = (cell.fit ?? {}) as unknown as Fit;+ const chosen = USES.find(+ (use) => use.intent === intent && (use.intent === "eval" || use.format === trainFormat)+ );+ if (chosen) {+ const verdict = fit[chosen.key];+ return verdict?.ok ? (+ <Field label="Intent" tone="text-success">+ <Icon.success className="size-3 shrink-0" />+ {intentLabel(chosen.intent, chosen.format)}+ </Field>+ ) : (+ <>+ <Field label="Intent">{intentLabel(chosen.intent, chosen.format)}</Field>+ <Field label="Fit" title={verdict?.reason} tone="text-warning">+ <Icon.warning className="size-3 shrink-0" />+ <span className="truncate">{verdict?.reason || "Rows do not fit"}</span>+ </Field>+ {onIntent &&+ USES.filter((use) => use !== chosen && fit[use.key]?.ok).map((use) => (+ <Button+ key={use.key}+ onClick={() => onIntent(use.intent, use.format || undefined)}+ size="xs"+ variant="outline"+ >+ Use for {intentLabel(use.intent, use.format)}+ </Button>+ ))}+ </>);- const reports = (cell.intentReport as Record<string, Report> | null) ?? {};- const shape = (reports[intent] ?? {}) as Report;- const ran = cell.state === "ok" && !!cell.fingerprint;- const other: "train" | "eval" | null =- intent === "train" ? "eval" : intent === "eval" ? "train" : null;- const otherFits = other ? !!(reports[other] as Report | undefined)?.ok : false;- const checks = [intentCheck(intent, shape, ran)];-- /** Only the moves that would actually change the verdict, most likely first. */- function suggest(- failing: Check,- acts: Pick<CellActions, "onIntent" | "onCapability">- ): Suggestion[] {- const out: Suggestion[] = [];- const capabilityFails = failing.label.endsWith(" rows");- if (failing.label === "Intent") {- for (const choice of ["train", "eval"] as const) {- if ((reports[choice] as Report | undefined)?.ok) {- out.push({- hint: `The ${choice} shape already holds on this version.`,- icon: "target",- key: `intent-${choice}`,- run: () => acts.onIntent(choice),- title: `Use it for ${choice}`,- });- }- }- return out;- }- if (failing.fixable === false) return out;- if (other && otherFits) {- out.push({- hint: `The ${other} shape already holds on this version.`,- icon: "target",- key: "intent",- run: () => acts.onIntent(other),- title: `Use it for ${other} instead`,- });- }- if (capabilityFails) {- const current = capabilities.find((c) => c.name === capabilityName)?.score ?? 0;- const better = capabilities- .filter((c) => c.name !== capabilityName && (c.score ?? 0) > current)- .slice(0, 2);- for (const c of better) {- out.push({- hint: `${Math.round((c.score ?? 0) * 100)}% of rows match it, against ${Math.round(current * 100)}% for ${capabilityName}.`,- icon: "capability",- key: `cap-${c.id}`,- run: () => acts.onCapability(c.id),- title: `Switch to ${c.name}`,- });- }- if (better.length === 0) {- out.push({- hint: `No capability matches these rows better. Only the ${intent} shape is checked then.`,- icon: "close",- key: "detach",- run: () => acts.onCapability(null),- title: "Remove the capability",- });- }- }- return out;- }- if (capabilityName) {- checks.push(capabilityCheck(capabilityName, (cell.capabilityReport ?? {}) as Report, intent));}- const present = new Set(columnsOf(cell).map((c) => c.name));- const failing = checks.find((c) => !c.ok);- const headline = !failing- ? "Format valid"- : failing.label === "Intent"- ? "Intent pending"- : failing.label.endsWith(" rows")- ? `Does not match ${capabilityName}`- : `Not a ${intent} table`;- const detail = failing && failing.found.length <= 48 ? failing.found : null;- const suggestions = failing && actions ? suggest(failing, actions) : [];+ const fitting = USES.filter(+ (use) => (intent !== "train" || use.intent === "train") && fit[use.key]?.ok+ );return (- <HoverCard openDelay={250}>- <HoverCardTrigger asChild>- <span- className={cn(- "inline-flex h-6 min-w-0 max-w-96 cursor-default items-center gap-1 whitespace-nowrap rounded-sm border px-1.5 text-xs",- failing- ? "border-warning/40 bg-warning/10 text-warning"- : "border-success/40 bg-success/10 text-success"- )}- >- {failing ? (- <Icon.warning className="size-3 shrink-0" />- ) : (+ <>+ <Field+ label="Intent"+ title={fixed ? "A run used this version, so the intent is fixed." : undefined}+ tone="text-muted-foreground"+ >+ {fixed && <Icon.lock className="size-3 shrink-0" />}+ {intentLabel(intent)}+ </Field>+ {fitting.length > 0 &&+ (onIntent ? (+ fitting.map((use) => (+ <Button+ key={use.key}+ onClick={() => onIntent(use.intent, use.format || undefined)}+ size="xs"+ variant="outline"+ >+ Use for {intentLabel(use.intent, use.format)}+ </Button>+ ))+ ) : (+ <Field label="Fits" tone="text-success"><Icon.success className="size-3 shrink-0" />- )}- <span className="truncate">- {headline}- {detail && <span className="text-warning/80"> · {detail}</span>}- </span>- </span>- </HoverCardTrigger>- <HoverCardContent align="start" className="w-[28rem] p-2.5">- <ul className="flex flex-col gap-3">- {checks.map((check) => (- <CheckRow check={check} key={check.label} present={present} />- ))}- {!capabilityName && (- <li className="flex items-start gap-2 text-xs text-muted-foreground">- <Icon.info className="mt-0.5 size-3 shrink-0" />- <span>No capability is attached, so only the {intent} shape is checked.</span>- </li>- )}- </ul>- {failing && actions && suggestions.length > 0 && (- <div className="-mx-2.5 mt-3 flex flex-col gap-1 border-t border-border/70 px-2.5 pt-2">- {suggestions.map((item) => {- const Glyph = Icon[item.icon];- return (- <button- className={cn(- "flex w-full items-start gap-2 rounded-sm border px-2 py-1.5 text-left",- item.primary- ? "border-primary/40 bg-primary/10 hover:bg-primary/20"- : "border-border/70 hover:bg-accent/50"- )}- key={item.key}- onClick={item.run}- type="button"- >- <Glyph- className={cn(- "mt-0.5 size-3.5 shrink-0",- item.primary ? "text-primary" : "text-muted-foreground"- )}- />- <span className="flex min-w-0 flex-col">- <span- className={cn("text-xs", item.primary ? "text-primary" : "text-foreground")}- >- {item.title}- </span>- <span className="text-xs text-muted-foreground">{item.hint}</span>- </span>- </button>- );- })}- </div>- )}- </HoverCardContent>- </HoverCard>+ {fitting.map((use) => intentLabel(use.intent, use.format)).join(", ")}+ </Field>+ ))}+ </>+ );+}++/** Shown only when the rows do not match the bound capability. */+function CapabilityMismatch({ cell, name }: { cell: Cell; name: string }) {+ const report = (cell.capabilityReport ?? {}) as { ok?: boolean; reason?: string };+ if (!name || report.ok !== false) return null;+ return (+ <Field label="Capability" title={report.reason} tone="text-warning">+ <Icon.warning className="size-3 shrink-0" />+ <span className="truncate">Does not match {name}</span>+ </Field>);}@@ -489,10 +230,11 @@ export function NotebookCell({datasetId,cell,intent,+ trainFormat,capabilityName,- capabilities,active,- partition,+ member,+ intentLocked,editable,selected,onSelect,@@ -503,11 +245,14 @@ export function NotebookCell({datasetId: string;cell: Cell;intent: string;+ trainFormat: string;capabilityName: string;- capabilities: CapabilityChoice[];active: boolean;/** The cell's part of a training split, named for the reader. */- partition?: string;+ /** A cell of another dataset, such as a partition member: its name links there. */+ member?: { datasetId: string; label: string };+ /** A run used some version of the dataset: its intent no longer changes. */+ intentLocked: boolean;editable: boolean;selected: boolean;onSelect: () => void;@@ -519,13 +264,18 @@ export function NotebookCell({const attachment = (cell.review as { kind?: string } | undefined)?.kind === "attachment";const hasScript = !source && !attachment && !!cell.script;const ran = cell.state === "ok" && !!cell.fingerprint;- const frozen = !!cell.frozen;const incoming = useNodeConnections({ handleType: "target" });const outgoing = useNodeConnections({ handleType: "source" });const [scriptOpen, setScriptOpen] = useState(!ran);- const [tableOpen, setTableOpen] = useState(true);- const [metricsOpen, setMetricsOpen] = useState(false);+ // Intermediate versions start folded so the end of the flow stays in view.+ const [tableChoice, setTableOpen] = useState<boolean | null>(null);+ const [labelsOpen, setLabelsOpen] = useState(false);const terminal = outgoing.length === 0 || active;+ const tableOpen = tableChoice ?? (terminal || selected);+ // A table that selection opened stays open, with its filters, when selection moves on.+ useEffect(() => {+ if (selected && tableChoice === null) setTableOpen(true);+ }, [selected, tableChoice]);useEffect(() => {if (cell.state === "failed" || cell.state === "queued") setScriptOpen(true);}, [cell.state]);@@ -581,7 +331,18 @@ export function NotebookCell({>{version}</button>- <span>{partition || (source ? "Source" : cell.title)}</span>+ {member ? (+ <Link+ className="nodrag hover:underline"+ params={{ datasetId: member.datasetId }}+ search={(previous) => ({ projectId: previous.projectId })}+ to="/datasets/$datasetId"+ >+ {member.label}+ </Link>+ ) : (+ <span>{source ? "Source" : cell.title}</span>+ )}</span><spanaria-label={`${cell.title} cell`}@@ -610,12 +371,6 @@ export function NotebookCell({{STATE_LABEL[cell.state as CellState]}</span>) : null}- {frozen && !source && (- <Icon.lock- aria-label="Used by a run; frozen"- className="size-3 text-muted-foreground"- />- )}</div>{preparationActions}</div>@@ -647,7 +402,7 @@ export function NotebookCell({meta={cell.transformation.execution === "isolated_container" ||cell.transformation.execution === "platform_operations"- ? "Executed by Overmind"+ ? undefined: "Execution not recorded"}onToggle={() => setScriptOpen((o) => !o)}@@ -680,12 +435,9 @@ export function NotebookCell({{ran ? (<div className={cn(!source && (hasScript || attachment) && "border-t border-border/70")}><SectionHeader- alerts={- terminal && !metricsOpen ? <AnalyticsAlerts report={cell.analytics} /> : undefined- }label="Data"meta={`${cell.rows.toLocaleString()} rows × ${columns}`}- onToggle={() => setTableOpen((o) => !o)}+ onToggle={() => setTableOpen(!tableOpen)}open={tableOpen}/>{tableOpen && (@@ -697,37 +449,33 @@ export function NotebookCell({pageSize={10}/>)}- {terminal && (+ {terminal && !!cell.analytics?.families.length && (<div className="border-t border-border/70"><SectionHeader- label="Metrics"- meta={- cell.analytics?.status === "completed" ? "Measured by Overmind" : "Not measured"- }- onToggle={() => setMetricsOpen((open) => !open)}- open={metricsOpen}+ label="Labels"+ onToggle={() => setLabelsOpen((open) => !open)}+ open={labelsOpen}/>- {metricsOpen && <AnalyticsDetails report={cell.analytics} />}+ {labelsOpen && <CellLabels cell={cell} />}</div>)}{active && (- <footer className="flex min-h-8 flex-wrap items-center gap-1 border-t border-border/70 px-2.5 py-1 [&>*]:shrink-0">- <span className="inline-flex h-6 shrink-0 items-center gap-1 whitespace-nowrap rounded-sm border border-success/40 bg-success/10 px-1.5 text-xs text-success">- <Icon.success className="size-3" />- Active- </span>- <FitChip- actions={editable && !frozen ? actions : undefined}- capabilities={capabilities}- capabilityName={capabilityName}+ <footer className="flex min-h-10 flex-wrap items-center gap-2 border-t border-border/70 px-2.5 py-2">+ <IntentFieldscell={cell}+ fixed={intentLocked}intent={intent}+ onIntent={editable && !intentLocked ? actions.onIntent : undefined}+ trainFormat={trainFormat}/>+ <CapabilityMismatch cell={cell} name={capabilityName} /><span className="flex-1" />{intent === "train" && (<ButtonclassName="border-primary/40 bg-primary/10 text-primary hover:bg-primary/20"- disabled={!fit.ok}+ disabled={+ trainFormat ? !(cell.fit as unknown as Fit)?.[trainFormat]?.ok : !fit.ok+ }onClick={() => actions.onUse("train")}size="xs"variant="outline"diff --git a/frontend/src/components/datasets/notebook/field.tsx b/frontend/src/components/datasets/notebook/field.tsxnew file mode 100644index 00000000..4a8dd943--- /dev/null+++ b/frontend/src/components/datasets/notebook/field.tsx@@ -0,0 +1,28 @@+import type { ReactNode } from "react";++import { cn } from "@/lib/utils";++/** A labelled value, drawn like the version chip in the cell header. */+export function Field({+ label,+ title,+ tone = "text-foreground",+ children,+}: {+ label: string;+ title?: string;+ tone?: string;+ children: ReactNode;+}) {+ return (+ <span+ className="inline-flex h-6 min-w-0 items-center overflow-hidden rounded-sm border border-border/70 bg-card text-xs"+ title={title}+ >+ <span className="pixel-label flex h-full shrink-0 items-center border-r border-border/70 px-2 text-muted-foreground">+ {label}+ </span>+ <span className={cn("flex min-w-0 items-center gap-1.5 px-2", tone)}>{children}</span>+ </span>+ );+}diff --git a/frontend/src/components/datasets/notebook/notebook-page.test.tsx b/frontend/src/components/datasets/notebook/notebook-page.test.tsxindex d449ca5d..76b84a75 100644--- a/frontend/src/components/datasets/notebook/notebook-page.test.tsx+++ b/frontend/src/components/datasets/notebook/notebook-page.test.tsx@@ -119,5 +119,5 @@ it("keeps import retry unavailable while the source is landing", () => {};showNotebook();expect(screen.queryByRole("button", { name: "Resume import" })).toBeNull();- expect(screen.getByText("Workshop operation running")).toBeTruthy();+ expect(screen.getByRole("button", { name: "Stop" })).toBeTruthy();});diff --git a/frontend/src/components/datasets/notebook/notebook-page.tsx b/frontend/src/components/datasets/notebook/notebook-page.tsxindex 57f045fc..57d1d698 100644--- a/frontend/src/components/datasets/notebook/notebook-page.tsx+++ b/frontend/src/components/datasets/notebook/notebook-page.tsx@@ -18,7 +18,7 @@ import {import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";import { EmptyState } from "@/components/ui/empty-state";-import { LoadingState } from "@/components/ui/spinner";+import { LoadingState, Spinner } from "@/components/ui/spinner";import { useAssistantThread } from "@/hooks/use-assistant-thread";import {activeCellOf,@@ -28,7 +28,7 @@ import {intentOf,invalidateDataset,isBusy,- rankOf,+ SPLIT_LABEL,useCancelDatasetMutation,useDatasetEvents,useDatasetPreparationQuery,@@ -36,20 +36,13 @@ import {useDatasetWorkbenchQuery,usePatchDatasetMutation,useResumeDatasetImportMutation,+ workText,} from "@/hooks/use-datasets";-import { useProjectCapabilitiesQuery } from "@/hooks/use-evaluations";import { useGuestGate } from "@/hooks/use-guest-gate";import { usePersistedState } from "@/hooks/use-persisted-state";import { notify } from "@/lib/notify";import type { Cell } from "@/openapi";-const PARTITIONS: Record<string, string> = {- calibration: "Calibration data",- development: "Development data",- final: "Final evaluation data",- train: "Training data",-};-export function DatasetNotebook({datasetId,projectId,@@ -70,9 +63,7 @@ export function DatasetNotebook({cellParam,dataset?.updatedAt?.getTime());- const capabilitiesQuery = useProjectCapabilitiesQuery(projectId);const assistant = useAssistantThread(datasetId);- const capabilities = capabilitiesQuery.data?.results ?? [];const patch = usePatchDatasetMutation(datasetId);const cancel = useCancelDatasetMutation(datasetId);@@ -135,9 +126,11 @@ export function DatasetNotebook({const edges = useMemo(() =>(preparationQuery.data?.edges ?? []).map((edge) => ({- ...edge,+ data: { kind: edge.kind, value: edge.value },id: `${edge.source}:${edge.target}`,+ source: edge.source,style: { stroke: "var(--muted-foreground)", strokeWidth: 1.5 },+ target: edge.target,type: "cell",})),[preparationQuery.data]@@ -145,6 +138,15 @@ export function DatasetNotebook({const visibleIds = useMemo(() => new Set(cells.map((cell) => cell.id)), [cells]);const { motions, complete } = useCellMotion(nodes ? cells : undefined, visibleIds);const busy = isBusy(dataset);+ // A first landing shows its stage in the source cell; added files show it here.+ const busyText =+ dataset?.state === "landing"+ ? ((cells.some((cell) => cell.state === "ok")+ ? extractionStatus(dataset.sourceSpec)+ : undefined) ?? "Importing")+ : dataset?.work+ ? workText(dataset.work)+ : "Running";const editable = !!dataset && !busy;const intent = intentOf(dataset);@@ -205,12 +207,6 @@ export function DatasetNotebook({);}- const rank = rankOf(dataset);- const capabilityChoices = [- ...rank.map((r) => ({ id: r.capability_id, name: r.name, score: r.score })),- ...capabilities.map((c) => ({ id: c.id, name: c.name })),- ].filter((c, i, all) => all.findIndex((o) => o.id === c.id) === i);-const latestRun = workbenchQuery.data?.runs[0];const repairSource = latestRun?.state === "failed" ? latestRun.sourceCell : undefined;const actionCellId = cells.some((cell) => cell.id === repairSource) ? repairSource : active?.id;@@ -238,16 +234,8 @@ export function DatasetNotebook({const local = owner === datasetId;return (<div>- {node && (node.role || !local) && (- <div className="mb-2 text-sm text-muted-foreground">- <Link params={{ datasetId: owner }} search={{ projectId }} to="/datasets/$datasetId">- {PARTITIONS[node.role] || node.role || node.datasetName}- </Link>- </div>- )}<NotebookCellactions={{- onCapability: guard((id: string | null) => patch.mutate({ capability: id })),onExport: (fmt) =>void downloadExport(owner,@@ -255,19 +243,30 @@ export function DatasetNotebook({fmt,`${datasetDisplayName(dataset)}-${cell.version || "source"}`).catch((e) => notify.error(e, "Export failed")),- onIntent: guard((next: "train" | "eval") => patch.mutate({ intent: next })),+ onIntent: guard((next: "train" | "eval", format?: "sft" | "decision") =>+ patch.mutate({ intent: next, trainFormat: format ?? "" })+ ),onUse: guard(handOff),}}active={cell.id === active?.id}- capabilities={capabilityChoices}capabilityName={dataset.capabilityName ?? ""}cell={cell}datasetId={owner}editable={editable && local}intent={node?.intent ?? intent}+ // The server locks intent on the edited dataset's own used versions.+ intentLocked={+ nodes?.some(+ (other) => other.cell.frozen && (other.dataset ?? datasetId) === datasetId+ ) ?? false+ }key={cell.id}+ member={+ node && !local+ ? { datasetId: owner, label: SPLIT_LABEL[node.role] || node.role || node.datasetName }+ : undefined+ }onSelect={() => setSelectedId(cell.id)}- partition={PARTITIONS[node?.role ?? ""] || node?.role}preparationActions={cell.id === actionCellId ? preparationControls(cell) : undefined}selected={cell.id === selectedId}sourceDetails={@@ -279,6 +278,7 @@ export function DatasetNotebook({/>) : undefined}+ trainFormat={node ? node.trainFormat : (dataset.trainFormat ?? "")}/></div>);@@ -288,16 +288,23 @@ export function DatasetNotebook({<div className="relative flex h-full min-h-0 flex-col"><div className="assistant-notices pointer-events-none absolute bottom-16 z-10 max-h-48 overflow-y-auto"><div className="pointer-events-auto space-y-2 rounded-sm bg-card">+ {/* Mounted while idle too, so the first status is announced. */}+ <span className="sr-only" role="status">+ {busy ? busyText : ""}+ </span>{busy && (<div className="flex items-center justify-between gap-3 rounded-sm border border-border px-3 py-2 text-xs">- <span>Workshop operation running</span>+ <span className="flex min-w-0 items-center gap-2">+ <Spinner size="sm" />+ <span className="truncate tabular-nums">{busyText}</span>+ </span><Buttondisabled={cancel.isPending}onClick={() => cancel.mutate()}size="sm"variant="secondary">- Stop operation+ Stop</Button></div>)}@@ -355,11 +362,11 @@ export function DatasetNotebook({cells={cells}edges={edges}focus={focus}+ key={datasetId}motions={motions}onMotionComplete={complete}renderCell={renderCell}showMinimap={showMinimap}- storageKey={`workshop-flow:layers:${projectId}:${datasetId}`}/>)}<AssistantDockdiff --git a/frontend/src/components/datasets/notebook/preparation-actions.tsx b/frontend/src/components/datasets/notebook/preparation-actions.tsxindex dd49837b..967d1969 100644--- a/frontend/src/components/datasets/notebook/preparation-actions.tsx+++ b/frontend/src/components/datasets/notebook/preparation-actions.tsx@@ -82,7 +82,7 @@ export function PreparationActions({</HoverCardContent></HoverCard>)}- <PromptAgentActions prompt={prompt} />+ <PromptAgentActions prompt={prompt} quiet />{children}</div>);diff --git a/frontend/src/components/datasets/notebook/preparation.tsx b/frontend/src/components/datasets/notebook/preparation.tsxindex b74a857b..959705f8 100644--- a/frontend/src/components/datasets/notebook/preparation.tsx+++ b/frontend/src/components/datasets/notebook/preparation.tsx@@ -1,3 +1,6 @@+import { Field } from "@/components/datasets/notebook/field";++/** The split landing made, as measured counts. */export function ContaminationReport({ spec }: { spec: unknown }) {const report = (spec as {@@ -8,27 +11,26 @@ export function ContaminationReport({ spec }: { spec: unknown }) {content_overlap: number;group_overlap: number;group_by: string[];- stratify_by: string | null;};} | null)?.contamination_report;if (!report) return null;return (- <details className="mb-2 mr-2 rounded-md border border-border p-2.5 text-xs">- <summary className="cursor-pointer">- Data split · {report.train_rows} train · {report.eval_rows} eval- </summary>- <div className="mt-2 flex flex-col gap-1 text-muted-foreground">- <p>- {report.duplicates_removed} duplicates removed · {report.content_overlap} matching inputs- across splits · {report.group_overlap} shared groups- </p>- <p>- Groups: {report.group_by.join(", ") || "matching content"} · Stratification:{" "}- {report.stratify_by ?? "none"}- </p>- <p>Source snapshot only. Near-duplicate similarity not checked.</p>- </div>- </details>+ <div aria-label="Data split" className="mb-2 mr-2 flex flex-wrap gap-2">+ <Field label="Train">{report.train_rows.toLocaleString()} rows</Field>+ <Field label="Eval">{report.eval_rows.toLocaleString()} rows</Field>+ <Field label="Duplicates removed">{report.duplicates_removed.toLocaleString()}</Field>+ <Field+ label="Exact overlap"+ title="Exact content and group overlap between the splits; near duplicates are not checked."+ >+ {(report.content_overlap + report.group_overlap).toLocaleString()}+ </Field>+ {report.group_by.length > 0 && (+ <Field label="Grouped by">+ <span className="font-mono">{report.group_by.join(", ")}</span>+ </Field>+ )}+ </div>);}diff --git a/frontend/src/components/datasets/notebook/rows-grid.tsx b/frontend/src/components/datasets/notebook/rows-grid.tsxindex a69c366a..f28101e1 100644--- a/frontend/src/components/datasets/notebook/rows-grid.tsx+++ b/frontend/src/components/datasets/notebook/rows-grid.tsx@@ -1,4 +1,4 @@-import { Fragment, useCallback, useEffect, useMemo, useState } from "react";+import { Fragment, type ReactNode, useCallback, useEffect, useMemo, useState } from "react";import { diffText } from "@/components/datasets/notebook/diff";import { Badge } from "@/components/ui/badge";@@ -109,6 +109,76 @@ function cellText(value: unknown): string {}}+const TURN_FIELDS = new Set(["role", "content", "name", "tool_calls", "tool_call_id"]);++/** A chat turn: a role and nothing but the fields a turn carries. */+function isTurn(value: unknown): value is { role: string; content?: unknown } {+ return (+ !!value &&+ typeof value === "object" &&+ typeof (value as { role?: unknown }).role === "string" &&+ Object.keys(value).every((key) => TURN_FIELDS.has(key))+ );+}++// A collapsed object shows its first fields; the expanded row shows them all.+const PREVIEW_FIELDS = 6;++function Tag({ children }: { children: ReactNode }) {+ return (+ <span className="shrink-0 rounded-xs border border-border/70 px-1 text-muted-foreground">+ {children}+ </span>+ );+}++/** One line for a nested value: a conversation's turns, a list's size and first item,+ * or an object's fields, so a cell reads as data rather than JSON text. */+function ValuePreview({ value }: { value: object }) {+ if (Array.isArray(value)) {+ if (value.length > 0 && value.every(isTurn)) {+ // A conversation reads by its first user message; every turn shows in the row view.+ const text = (turn: { content?: unknown }) => cellText(turn.content ?? "").trim();+ const opening =+ value.find((turn) => turn.role === "user" && text(turn)) ??+ value.find((turn) => text(turn)) ??+ value[0];+ return (+ <span className="flex min-w-0 items-center gap-1.5">+ <Tag>{value.length === 1 ? "1 turn" : `${value.length} turns`}</Tag>+ <span className="truncate">{cellText(opening.content)}</span>+ </span>+ );+ }+ return (+ <span className="flex min-w-0 items-center gap-1.5">+ <Tag>{value.length === 1 ? "1 item" : `${value.length} items`}</Tag>+ {value.length > 0 &&+ (value[0] && typeof value[0] === "object" ? (+ <ValuePreview value={value[0] as object} />+ ) : (+ <span className="truncate">{cellText(value[0])}</span>+ ))}+ </span>+ );+ }+ return (+ <span className="flex min-w-0 items-center gap-2.5">+ {Object.entries(value)+ .slice(0, PREVIEW_FIELDS)+ .map(([key, item]) => (+ <span className="flex shrink-0 items-center gap-1" key={key}>+ <span className="text-muted-foreground">{key}</span>+ <span>{item === null ? "—" : cellText(item)}</span>+ </span>+ ))}+ {Object.keys(value).length > PREVIEW_FIELDS && (+ <Tag>+{Object.keys(value).length - PREVIEW_FIELDS}</Tag>+ )}+ </span>+ );+}+function Stat({ label, value }: { label: string; value: string }) {return (<div className="flex flex-col gap-0.5 rounded-sm border border-border/70 bg-wash-raised px-2 py-1.5">@@ -148,7 +218,7 @@ function ColumnStatsCard({ column, total }: { column: ColumnStat; total: number<HoverCardTrigger asChild><buttonaria-label={`Profile of ${column.name}`}- className="rounded-sm p-0.5 text-muted-foreground/60 hover:bg-muted hover:text-foreground"+ className="rounded-sm p-0.5 text-muted-foreground/60 opacity-0 hover:bg-muted hover:text-foreground focus-visible:opacity-100 group-hover/column:opacity-100"type="button"><Icon.chartBar className="size-3" />@@ -539,7 +609,7 @@ export function RowsGrid({aria-sort={active ? (sort?.dir === "asc" ? "ascending" : "descending") : "none"}- className="max-w-[26rem] border-r border-b border-border/70 px-2 py-1.5 text-left font-normal last:border-r-0"+ className="group/column max-w-[26rem] border-r border-b border-border/70 px-2 py-1.5 text-left font-normal last:border-r-0"key={c.name}scope="col">@@ -595,9 +665,10 @@ export function RowsGrid({? undefined: marks[String(sourceRow)];const open = openRow === rowIndex;+ // Frames written before _overmind_evidence keep it in _overmind_provenance.const evidence =(- row._overmind_provenance as {+ (row._overmind_evidence ?? row._overmind_provenance) as {evidence?: Array<{ filename: string; page?: number; element?: string }>;} | null)?.evidence ?? [];@@ -620,10 +691,10 @@ export function RowsGrid({setOpenRow(open ? null : rowIndex);}}>- <td className="border-r border-b border-border/60 px-2 py-1 font-mono tabular-nums text-muted-foreground">+ <td className="border-r border-b border-border/60 px-2 py-1 align-top font-mono tabular-nums text-muted-foreground"><buttonaria-expanded={open}- aria-label={`${open ? "Collapse" : "Inspect"} row ${row._index}`}+ aria-label={`${open ? "Collapse" : "Inspect"} row ${row._index + 1}`}className="w-full text-left hover:text-foreground"onClick={(event) => {event.stopPropagation();@@ -631,7 +702,7 @@ export function RowsGrid({}}type="button">- {row._index}+ {row._index + 1}</button></td>{columns.map((c) => {@@ -651,7 +722,7 @@ export function RowsGrid({title={!open && text.length > 80 ? text.slice(0, 400) : undefined}><div- aria-label={open ? `Row ${row._index}, ${c.name}` : undefined}+ aria-label={open ? `Row ${row._index + 1}, ${c.name}` : undefined}className={cn(open? "max-h-48 select-text overflow-auto whitespace-pre-wrap break-words"@@ -664,6 +735,8 @@ export function RowsGrid({<ChangedValue after={value} before={before[c.name]} wrap={open} />) : text === "" ? ("null"+ ) : !open && value && typeof value === "object" ? (+ <ValuePreview value={value} />) : (text)}diff --git a/frontend/src/components/datasets/notebook/source.tsx b/frontend/src/components/datasets/notebook/source.tsxindex b6ac1e47..ee120bcb 100644--- a/frontend/src/components/datasets/notebook/source.tsx+++ b/frontend/src/components/datasets/notebook/source.tsx@@ -22,11 +22,24 @@ interface SourceArtifact {export function extractionStatus(spec: unknown): string | undefined {const progress = (spec as {- landing_progress?: { filename?: string; stage?: string; completed?: number; total?: number };+ landing_progress?: {+ filename?: string;+ stage?: string;+ completed?: number;+ total?: number;+ rows_done?: number;+ rows_total?: number | null;+ };} | null)?.landing_progress;if (!progress) return;if (progress.stage === "merging") return "Adding extracted rows";+ if (progress.stage === "writing" || progress.stage === "measuring")+ return progress.rows_done == null+ ? `${progress.stage === "writing" ? "Writing" : "Measuring"} rows`+ : `${progress.stage === "writing" ? "Writing" : "Measuring"} rows · ${progress.rows_done.toLocaleString()}${+ progress.rows_total ? ` of ${progress.rows_total.toLocaleString()}` : ""+ }`;const action = progress.stage === "extracting" ? "Extracting text" : "Reading file";const count =progress.total && progress.total > 1@@ -92,9 +105,6 @@ export function SourceDetails({><FileTypeIcon className="size-3" filename={source.filename} /><span className="min-w-0 max-w-sm truncate">{source.filename}</span>- <span className="shrink-0 text-muted-foreground">- {source.rows.toLocaleString()} rows- </span><Buttonaria-label={`Download ${source.filename}`}disabled={downloading !== null}diff --git a/frontend/src/components/entity-ref/cards.tsx b/frontend/src/components/entity-ref/cards.tsxindex 3c5e0481..95700d62 100644--- a/frontend/src/components/entity-ref/cards.tsx+++ b/frontend/src/components/entity-ref/cards.tsx@@ -16,7 +16,7 @@ import { userFacingJobError } from "@/components/finetuning/train/model-config";import { CreditsAmount } from "@/components/ui/credits";import { DateTime } from "@/components/ui/datetime";import { DeltaChip, fromScore } from "@/components/ui/delta-chip";-import { datasetDetailQuery, INTENT_LABEL, intentOf } from "@/hooks/use-datasets";+import { datasetDetailQuery, intentLabel, intentOf } from "@/hooks/use-datasets";import { jobCostUsd } from "@/lib/finetuning-cost";import { StatusBadge } from "@/lib/job-status";import { scorePct } from "@/lib/utils";@@ -94,7 +94,7 @@ export function DatasetCard({ id, name }: { id: string; name: string }) {subtitle={data.activeVersion ? `version ${data.activeVersion}` : "no version yet"}><Row label="Rows">{(data.rows ?? 0).toLocaleString()}</Row>- <Row label="Intent">{INTENT_LABEL[intentOf(data)]}</Row>+ <Row label="Intent">{intentLabel(intentOf(data), data.trainFormat)}</Row><Row label="Source">{SOURCE_KIND_LABEL[data.sourceKind] ?? data.sourceKind}</Row><Row label="Created">{data.createdAt ? <DateTime value={data.createdAt} /> : null}</Row></EntityCardShell>diff --git a/frontend/src/components/finetuning/train/setup-panel.tsx b/frontend/src/components/finetuning/train/setup-panel.tsxindex 9c3cca00..9a75af0b 100644--- a/frontend/src/components/finetuning/train/setup-panel.tsx+++ b/frontend/src/components/finetuning/train/setup-panel.tsx@@ -178,7 +178,7 @@ export function SetupPanel({<span className="text-xs text-muted-foreground">{d.activeVersion} · {count(d.rows ?? 0, "row")}</span>- <IntentBadge intent={d.intent} />+ <IntentBadge intent={d.intent} trainFormat={d.trainFormat} /></SelectItem>))}</SelectContent>@@ -333,7 +333,7 @@ export function SetupPanel({<span className="text-xs text-muted-foreground">{d.activeVersion} · {count(d.rows ?? 0, "row")}</span>- <IntentBadge intent={d.intent} />+ <IntentBadge intent={d.intent} trainFormat={d.trainFormat} /></SelectItem>))}</SelectContent>diff --git a/frontend/src/components/quickstart/prompt-agent-actions.tsx b/frontend/src/components/quickstart/prompt-agent-actions.tsxindex e7810c2a..5a4ef157 100644--- a/frontend/src/components/quickstart/prompt-agent-actions.tsx+++ b/frontend/src/components/quickstart/prompt-agent-actions.tsx@@ -68,6 +68,7 @@ export function PromptAgentActions({prompt,defaultAgent,inverted = false,+ quiet = false,onCopied,onCopyFailed,onOpenClicked,@@ -75,6 +76,8 @@ export function PromptAgentActions({prompt: string;defaultAgent?: string | null;inverted?: boolean;+ /** Outlined, for a page where copying the prompt is a secondary action. */+ quiet?: boolean;onCopied?: () => void;onCopyFailed?: () => void;onOpenClicked?: (agent: string) => void;@@ -88,7 +91,12 @@ export function PromptAgentActions({const colors = inverted? "bg-primary-foreground text-primary hover:bg-primary-foreground/90": "";- const divider = inverted ? "border-l-primary/40" : "border-l-primary-foreground/40";+ const divider = quiet+ ? "border-l-border/70"+ : inverted+ ? "border-l-primary/40"+ : "border-l-primary-foreground/40";+ const variant = quiet ? "outline" : undefined;async function copyPrompt() {try {@@ -110,10 +118,16 @@ export function PromptAgentActions({className={cn("rounded-r-none", colors)}onClick={() => void copyPrompt()}size="icon-sm"+ variant={variant}><Icon.copy /></Button>- <Button asChild className={cn("rounded-none", divider, colors)} size="sm">+ <Button+ asChild+ className={cn("rounded-none", divider, colors)}+ size="sm"+ variant={variant}+ ><aaria-label={`Open in ${agent.label}`}href={url}@@ -129,6 +143,7 @@ export function PromptAgentActions({className={cn(!mobile && "rounded-r-none", colors)}onClick={() => void copyPrompt()}size="sm"+ variant={variant}><Icon.copy />Copy prompt@@ -141,6 +156,7 @@ export function PromptAgentActions({aria-label="Choose coding agent"className={cn("rounded-l-none", divider, colors)}size="icon-sm"+ variant={variant}><Icon.chevronDown /></Button>diff --git a/frontend/src/components/ui/table-pagination.tsx b/frontend/src/components/ui/table-pagination.tsxindex f62e4ccc..018bd539 100644--- a/frontend/src/components/ui/table-pagination.tsx+++ b/frontend/src/components/ui/table-pagination.tsx@@ -55,8 +55,8 @@ export function TablePagination({</>) : pagination.count > 0 ? (<>- {pagination.startItem}–{pagination.endItem} of {pagination.total}{" "}- {pagination.total === 1 ? "row" : "rows"}+ {pagination.startItem.toLocaleString()}–{pagination.endItem.toLocaleString()} of{" "}+ {pagination.total.toLocaleString()} {pagination.total === 1 ? "row" : "rows"}</>) : ("0 rows"@@ -84,7 +84,7 @@ export function TablePagination({</Select></div><div className="whitespace-nowrap tabular-nums">- Page {page} of {pagination.totalPages}+ Page {page.toLocaleString()} of {pagination.totalPages.toLocaleString()}</div><div className="flex items-center gap-1"><Buttondiff --git a/frontend/src/hooks/use-datasets.ts b/frontend/src/hooks/use-datasets.tsindex 78e181f4..e066d31c 100644--- a/frontend/src/hooks/use-datasets.ts+++ b/frontend/src/hooks/use-datasets.ts@@ -28,13 +28,6 @@ export interface ColumnInfo {null_rate?: number;}-export interface CapabilityRank {- capability_id: string;- name: string;- score: number;- reason: string;-}-/** A page of the grid: `marks` says which rows are new and which values changed. */export interface RowsPage {rows: Array<Record<string, unknown> & { _index: number }>;@@ -104,13 +97,29 @@ export function traceSelectionBody(selection: TraceSelectionSpec) {};}+// One vocabulary for what a dataset is for: the cell, the table, the dialog and the canvas.export const INTENT_LABEL: Record<string, string> = {eval: "Eval",- explore: "Data exploration",- pending: "Pending",+ pending: "Not set",train: "Train",};+/** The role a partition gives its member dataset. */+export const SPLIT_LABEL: Record<string, string> = {+ calibration: "Calib",+ development: "Dev",+ final: "Test",+ train: "Train",+};++/** The intent as the Console names it, with the training format when one is set. */+export const TRAIN_FORMAT_LABEL: Record<string, string> = { decision: "Decision", sft: "SFT" };++export const intentLabel = (intent: string, trainFormat?: string | null): string =>+ intent === "train" && trainFormat+ ? `Train · ${TRAIN_FORMAT_LABEL[trainFormat] ?? trainFormat}`+ : (INTENT_LABEL[intent] ?? intent);+export const intentOf = (dataset: Dataset | null | undefined): Intent =>(dataset?.intent ?? "pending") as Intent;@@ -120,6 +129,7 @@ export const cellsOf = (dataset: Dataset | null | undefined): Cell[] =>export const isVisibleDatasetColumn = (column: { name: string }): boolean =>column.name !== "source_row" &&column.name !== "_overmind_provenance" &&+ column.name !== "_overmind_evidence" &&column.name !== "_overmind_document_id";export const columnsOf = (cell: Cell | null | undefined): ColumnInfo[] =>@@ -130,9 +140,6 @@ export const fitOf = (cell: Cell | null | undefined): { ok: boolean; reason: str? (cell.fits as { ok: boolean; reason: string }): { ok: false, reason: "" };-export const rankOf = (dataset: Dataset | null | undefined): CapabilityRank[] =>- Array.isArray(dataset?.capabilityRank) ? (dataset.capabilityRank as CapabilityRank[]) : [];-export const activeCellOf = (dataset: Dataset | null | undefined): Cell | null => {const ran = cellsOf(dataset).filter((c) => c.state === "ok" && c.fingerprint);if (dataset?.active) {@@ -142,6 +149,26 @@ export const activeCellOf = (dataset: Dataset | null | undefined): Cell | null =return ran.at(-1) ?? null;};+/** A count as a table shows it: exact below 10,000, then 48.2K and 1.3M. */+export const compactCount = (value: number): string => {+ if (value < 10_000) return value.toLocaleString();+ const [scaled, suffix] = value < 1_000_000 ? [value / 1_000, "K"] : [value / 1_000_000, "M"];+ return `${Number(scaled.toFixed(1)).toLocaleString()}${suffix}`;+};++/** The work a dataset is doing, with its measured counter: "Transforming · 12 of 500 batches". */+export const workText = (+ work: NonNullable<Dataset["work"]>,+ { compact = false }: { compact?: boolean } = {}+): string => {+ const { completed, label, total, unit } = work;+ if (typeof completed !== "number" || unit === "bytes") return label;+ const number = compact ? compactCount : (value: number) => value.toLocaleString();+ const count =+ typeof total === "number" ? `${number(completed)} of ${number(total)}` : number(completed);+ return `${label} · ${count}${unit ? ` ${unit}` : ""}`;+};+export const isBusy = (ds: Dataset | null | undefined): boolean =>!!ds &&(["queued", "running"].includes(ds.work?.status ?? "") ||@@ -339,6 +366,8 @@ export interface CreateDatasetInput {intent?: Intent;capabilityId?: string | null;source?: SourceRequest;+ /** Queue the assistant's first pass, which starts once the source lands. */+ prepare?: boolean;}export function useCreateDatasetMutation() {@@ -351,6 +380,7 @@ export function useCreateDatasetMutation() {capability: input.capabilityId,intent: input.intent,name: input.name,+ prepare: input.prepare,project: input.projectId,source: input.source,},@@ -372,6 +402,7 @@ export interface CreateDatasetSplitInput {groupBy?: string[];stratifyBy?: string;deduplicate?: boolean;+ prepare?: boolean;}/** One source landed as `<name> train` and `<name> eval`. */@@ -388,6 +419,7 @@ export function useCreateDatasetSplitMutation() {groupBy: input.groupBy,name: input.name,position: input.position,+ prepare: input.prepare,project: input.projectId,source: input.source,stratifyBy: input.stratifyBy,@@ -411,6 +443,7 @@ export interface DatasetPatch {name?: string;capability?: string | null;intent?: Intent;+ trainFormat?: "sft" | "decision" | "";active?: string | null;}diff --git a/frontend/src/lib/dataset-workspaces.ts b/frontend/src/lib/dataset-workspaces.tsindex feef8c2e..ea9c3324 100644--- a/frontend/src/lib/dataset-workspaces.ts+++ b/frontend/src/lib/dataset-workspaces.ts@@ -1,6 +1,10 @@import type { Dataset } from "@/openapi";-export function datasetWorkspaces(datasets: Dataset[]): Dataset[] {+/** A workspace row. ``useFormat`` is the training format its training member declares,+ * for a root whose own intent is not set. */+export type WorkspaceDataset = Dataset & { useFormat?: string };++export function datasetWorkspaces(datasets: Dataset[]): WorkspaceDataset[] {const byId = new Map(datasets.map((dataset) => [dataset.id, dataset]));const groups = new Map<string, Dataset[]>();for (const dataset of datasets) {@@ -19,6 +23,9 @@ export function datasetWorkspaces(datasets: Dataset[]): Dataset[] {...root,roles: [...new Set(members.flatMap((member) => member.roles))],updatedAt: latest.updatedAt,+ useFormat:+ members.find((member) => member.intent === "train" && member.trainFormat)?.trainFormat ??+ "",...(busy ? { work: busy.work } : {}),};});diff --git a/frontend/src/lib/schemas.test.ts b/frontend/src/lib/schemas.test.tsindex 97ef22d1..6ef23cff 100644--- a/frontend/src/lib/schemas.test.ts+++ b/frontend/src/lib/schemas.test.ts@@ -152,12 +152,12 @@ describe("schemas", () => {it("round-trips every filter a shared datasets link carries", () => {const result = datasetsSearchSchema.parse({ds_capability: "capability-1",- ds_role: "training",+ ds_role: "sft",ds_search: "golden",projectId: "proj-1",});expect(result.ds_capability).toBe("capability-1");- expect(result.ds_role).toBe("training");+ expect(result.ds_role).toBe("sft");expect(result.ds_search).toBe("golden");expect(result.projectId).toBe("proj-1");});diff --git a/frontend/src/lib/schemas.ts b/frontend/src/lib/schemas.tsindex a90eb91d..65c23a94 100644--- a/frontend/src/lib/schemas.ts+++ b/frontend/src/lib/schemas.ts@@ -157,7 +157,11 @@ export const datasetsSearchSchema = projectIdSearchSchema.extend({/** A capability id, or the `NO_CAPABILITY` sentinel for datasets attached to none. */ds_capability: z.string().optional().default("all"),ds_role: z- .enum(["all", "training", "development", "calibration", "evaluation", "source", "unassigned"])+ // Links saved before roles were intents still filter by the same use.+ .preprocess(+ (value) => ({ evaluation: "eval", training: "train" })[value as string] ?? value,+ z.enum(["all", "sft", "decision", "train", "eval", "pending"])+ ).optional().default("all").catch("all"),diff --git a/frontend/src/openapi/.openapi-generator/FILES b/frontend/src/openapi/.openapi-generator/FILESindex 824d47c2..891b9db7 100644--- a/frontend/src/openapi/.openapi-generator/FILES+++ b/frontend/src/openapi/.openapi-generator/FILES@@ -91,6 +91,7 @@ models/CapabilityStatusEnum.tsmodels/CapturedError.tsmodels/CatalogModel.tsmodels/Cell.ts+models/CellFit.tsmodels/CellStateEnum.tsmodels/CellTransformation.tsmodels/ChangeEnum.ts@@ -141,7 +142,6 @@ models/DatasetCreateRequest.tsmodels/DatasetOverlapResponse.tsmodels/DatasetPair.tsmodels/DatasetPreparation.ts-models/DatasetReadiness.tsmodels/DatasetSourceKindEnum.tsmodels/DatasetSplitCreateRequest.tsmodels/DatasetStateEnum.ts@@ -243,6 +243,7 @@ models/FinetuningRecommendationResponse.tsmodels/FinetuningSkillScore.tsmodels/FinetuningTimeEstimate.tsmodels/FinetuningTrainingMethod.ts+models/Fit.tsmodels/GraphEdge.tsmodels/GraphEdgeKindEnum.tsmodels/GuestClaimRequest.ts@@ -367,6 +368,7 @@ models/PlanUsageUnit.tsmodels/PositionEnum.tsmodels/PostResultsRequest.tsmodels/PreparationEdge.ts+models/PreparationEdgeKindEnum.tsmodels/PreparationNode.tsmodels/Project.tsmodels/ProjectInvite.ts@@ -435,6 +437,7 @@ models/TraceProviderEnum.tsmodels/TraceStatusEnum.tsmodels/TraceUsage.tsmodels/TracesServicesList200Response.ts+models/TrainFormatEnum.tsmodels/TrainingCheck.tsmodels/TrainingCheckpoint.tsmodels/TrainingEvidence.tsdiff --git a/frontend/src/openapi/models/Cell.ts b/frontend/src/openapi/models/Cell.tsindex a060f01a..ea404b3e 100644--- a/frontend/src/openapi/models/Cell.ts+++ b/frontend/src/openapi/models/Cell.ts@@ -13,6 +13,13 @@*/import { mapValues } from '../runtime';+import type { CellFit } from './CellFit';+import {+ CellFitFromJSON,+ CellFitFromJSONTyped,+ CellFitToJSON,+ CellFitToJSONTyped,+} from './CellFit';import type { DatasetAnalytics } from './DatasetAnalytics';import {DatasetAnalyticsFromJSON,@@ -27,13 +34,6 @@ import {CellTransformationToJSON,CellTransformationToJSONTyped,} from './CellTransformation';-import type { DatasetReadiness } from './DatasetReadiness';-import {- DatasetReadinessFromJSON,- DatasetReadinessFromJSONTyped,- DatasetReadinessToJSON,- DatasetReadinessToJSONTyped,-} from './DatasetReadiness';import type { CellStateEnum } from './CellStateEnum';import {CellStateEnumFromJSON,@@ -153,34 +153,22 @@ export interface Cell {readonly fits: { [key: string]: any; };/***- * @type {DatasetAnalytics}- * @memberof Cell- */- readonly analytics: DatasetAnalytics;- /**- *- * @type {{ [key: string]: any; }}+ * @type {CellFit}* @memberof Cell*/- readonly review: { [key: string]: any; };+ readonly fit: CellFit;/***- * @type {any}+ * @type {DatasetAnalytics}* @memberof Cell*/- readonly qualityReport: any | null;+ readonly analytics: DatasetAnalytics;/**** @type {{ [key: string]: any; }}* @memberof Cell*/- readonly preparationPlan: { [key: string]: any; } | null;- /**- *- * @type {DatasetReadiness}- * @memberof Cell- */- readonly readiness: DatasetReadiness;+ readonly review: { [key: string]: any; };/**** @type {number}@@ -236,11 +224,9 @@ export function instanceOfCell(value: object): value is Cell {if (!('intentReport' in value) || value['intentReport'] === undefined) return false;if (!('capabilityReport' in value) || value['capabilityReport'] === undefined) return false;if (!('fits' in value) || value['fits'] === undefined) return false;+ if (!('fit' in value) || value['fit'] === undefined) return false;if (!('analytics' in value) || value['analytics'] === undefined) return false;if (!('review' in value) || value['review'] === undefined) return false;- if (!('qualityReport' in value) || value['qualityReport'] === undefined) return false;- if (!('preparationPlan' in value) || value['preparationPlan'] === undefined) return false;- if (!('readiness' in value) || value['readiness'] === undefined) return false;if (!('seconds' in value) || value['seconds'] === undefined) return false;if (!('usedAt' in value) || value['usedAt'] === undefined) return false;if (!('usage' in value) || value['usage'] === undefined) return false;@@ -276,11 +262,9 @@ export function CellFromJSONTyped(json: any, ignoreDiscriminator: boolean): Cell'intentReport': json['intent_report'],'capabilityReport': json['capability_report'],'fits': json['fits'],+ 'fit': CellFitFromJSON(json['fit']),'analytics': DatasetAnalyticsFromJSON(json['analytics']),'review': json['review'],- 'qualityReport': json['quality_report'],- 'preparationPlan': json['preparation_plan'],- 'readiness': DatasetReadinessFromJSON(json['readiness']),'seconds': json['seconds'],'usedAt': (json['used_at'] == null ? null : new Date(json['used_at'])),'usage': json['usage'],@@ -293,7 +277,7 @@ export function CellToJSON(json: any): Cell {return CellToJSONTyped(json, false);}-export function CellToJSONTyped(value?: Omit<Cell, 'id'|'position'|'version'|'title'|'script'|'transformation'|'note'|'state'|'error'|'frozen'|'rows'|'columns'|'fingerprint'|'input_fingerprint'|'intent_report'|'capability_report'|'fits'|'analytics'|'review'|'quality_report'|'preparation_plan'|'readiness'|'seconds'|'used_at'|'usage'|'created_at'|'updated_at'> | null, ignoreDiscriminator: boolean = false): any {+export function CellToJSONTyped(value?: Omit<Cell, 'id'|'position'|'version'|'title'|'script'|'transformation'|'note'|'state'|'error'|'frozen'|'rows'|'columns'|'fingerprint'|'input_fingerprint'|'intent_report'|'capability_report'|'fits'|'fit'|'analytics'|'review'|'seconds'|'used_at'|'usage'|'created_at'|'updated_at'> | null, ignoreDiscriminator: boolean = false): any {if (value == null) {return value;}diff --git a/frontend/src/openapi/models/CellFit.ts b/frontend/src/openapi/models/CellFit.tsnew file mode 100644index 00000000..d16db4c8--- /dev/null+++ b/frontend/src/openapi/models/CellFit.ts@@ -0,0 +1,91 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+import type { Fit } from './Fit';+import {+ FitFromJSON,+ FitFromJSONTyped,+ FitToJSON,+ FitToJSONTyped,+} from './Fit';++/**+ *+ * @export+ * @interface CellFit+ */+export interface CellFit {+ /**+ *+ * @type {Fit}+ * @memberof CellFit+ */+ sft: Fit;+ /**+ *+ * @type {Fit}+ * @memberof CellFit+ */+ decision: Fit;+ /**+ *+ * @type {Fit}+ * @memberof CellFit+ */+ eval: Fit;+}++/**+ * Check if a given object implements the CellFit interface.+ */+export function instanceOfCellFit(value: object): value is CellFit {+ if (!('sft' in value) || value['sft'] === undefined) return false;+ if (!('decision' in value) || value['decision'] === undefined) return false;+ if (!('eval' in value) || value['eval'] === undefined) return false;+ return true;+}++export function CellFitFromJSON(json: any): CellFit {+ return CellFitFromJSONTyped(json, false);+}++export function CellFitFromJSONTyped(json: any, ignoreDiscriminator: boolean): CellFit {+ if (json == null) {+ return json;+ }+ return {++ 'sft': FitFromJSON(json['sft']),+ 'decision': FitFromJSON(json['decision']),+ 'eval': FitFromJSON(json['eval']),+ };+}++export function CellFitToJSON(json: any): CellFit {+ return CellFitToJSONTyped(json, false);+}++export function CellFitToJSONTyped(value?: CellFit | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'sft': FitToJSON(value['sft']),+ 'decision': FitToJSON(value['decision']),+ 'eval': FitToJSON(value['eval']),+ };+}diff --git a/frontend/src/openapi/models/Dataset.ts b/frontend/src/openapi/models/Dataset.tsindex cca38ed8..f2874edf 100644--- a/frontend/src/openapi/models/Dataset.ts+++ b/frontend/src/openapi/models/Dataset.ts@@ -41,13 +41,6 @@ import {IntentEnumToJSON,IntentEnumToJSONTyped,} from './IntentEnum';-import type { DatasetReadiness } from './DatasetReadiness';-import {- DatasetReadinessFromJSON,- DatasetReadinessFromJSONTyped,- DatasetReadinessToJSON,- DatasetReadinessToJSONTyped,-} from './DatasetReadiness';import type { DatasetStateEnum } from './DatasetStateEnum';import {DatasetStateEnumFromJSON,@@ -158,31 +151,25 @@ export interface Dataset {* @type {string}* @memberof Dataset*/- active?: string | null;+ trainFormat?: DatasetTrainFormatEnum;/**** @type {string}* @memberof Dataset*/- readonly activeVersion: string;- /**- *- * @type {number}- * @memberof Dataset- */- readonly rows: number;+ active?: string | null;/***- * @type {DatasetReadiness}+ * @type {string}* @memberof Dataset*/- readonly readiness: DatasetReadiness | null;+ readonly activeVersion: string;/***- * @type {{ [key: string]: any; }}+ * @type {number}* @memberof Dataset*/- readonly preparationPlan: { [key: string]: any; } | null;+ readonly rows: number;/**** @type {{ [key: string]: any; }}@@ -228,6 +215,16 @@ export interface Dataset {}+/**+ * @export+ */+export const DatasetTrainFormatEnum = {+ sft: 'sft',+ decision: 'decision',+ empty: ''+} as const;+export type DatasetTrainFormatEnum = typeof DatasetTrainFormatEnum[keyof typeof DatasetTrainFormatEnum];+/*** Check if a given object implements the Dataset interface.@@ -246,8 +243,6 @@ export function instanceOfDataset(value: object): value is Dataset {if (!('capabilityRank' in value) || value['capabilityRank'] === undefined) return false;if (!('activeVersion' in value) || value['activeVersion'] === undefined) return false;if (!('rows' in value) || value['rows'] === undefined) return false;- if (!('readiness' in value) || value['readiness'] === undefined) return false;- if (!('preparationPlan' in value) || value['preparationPlan'] === undefined) return false;if (!('operation' in value) || value['operation'] === undefined) return false;if (!('state' in value) || value['state'] === undefined) return false;if (!('error' in value) || value['error'] === undefined) return false;@@ -282,11 +277,10 @@ export function DatasetFromJSONTyped(json: any, ignoreDiscriminator: boolean): D'capabilityName': json['capability_name'],'capabilityRank': json['capability_rank'],'intent': json['intent'] == null ? undefined : IntentEnumFromJSON(json['intent']),+ 'trainFormat': json['train_format'] == null ? undefined : json['train_format'],'active': json['active'] == null ? undefined : json['active'],'activeVersion': json['active_version'],'rows': json['rows'],- 'readiness': DatasetReadinessFromJSON(json['readiness']),- 'preparationPlan': json['preparation_plan'],'operation': json['operation'],'state': DatasetStateEnumFromJSON(json['state']),'error': json['error'],@@ -301,7 +295,7 @@ export function DatasetToJSON(json: any): Dataset {return DatasetToJSONTyped(json, false);}-export function DatasetToJSONTyped(value?: Omit<Dataset, 'work'|'roles'|'workspace_id'|'id'|'project'|'brief'|'source_kind'|'source_spec'|'capability_name'|'capability_rank'|'active_version'|'rows'|'readiness'|'preparation_plan'|'operation'|'state'|'error'|'cells'|'created_by'|'created_at'|'updated_at'> | null, ignoreDiscriminator: boolean = false): any {+export function DatasetToJSONTyped(value?: Omit<Dataset, 'work'|'roles'|'workspace_id'|'id'|'project'|'brief'|'source_kind'|'source_spec'|'capability_name'|'capability_rank'|'active_version'|'rows'|'operation'|'state'|'error'|'cells'|'created_by'|'created_at'|'updated_at'> | null, ignoreDiscriminator: boolean = false): any {if (value == null) {return value;}@@ -312,6 +306,7 @@ export function DatasetToJSONTyped(value?: Omit<Dataset, 'work'|'roles'|'workspa'ocr_languages': value['ocrLanguages'],'capability': value['capability'],'intent': IntentEnumToJSON(value['intent']),+ 'train_format': value['trainFormat'],'active': value['active'],};}diff --git a/frontend/src/openapi/models/DatasetCreateRequest.ts b/frontend/src/openapi/models/DatasetCreateRequest.tsindex d6f45e40..dec9f431 100644--- a/frontend/src/openapi/models/DatasetCreateRequest.ts+++ b/frontend/src/openapi/models/DatasetCreateRequest.ts@@ -70,6 +70,12 @@ export interface DatasetCreateRequest {* @memberof DatasetCreateRequest*/source?: SourceRequest;+ /**+ * Queue the assistant's first pass, which starts once the source lands.+ * @type {boolean}+ * @memberof DatasetCreateRequest+ */+ prepare?: boolean;}@@ -98,6 +104,7 @@ export function DatasetCreateRequestFromJSONTyped(json: any, ignoreDiscriminator'capability': json['capability'] == null ? undefined : json['capability'],'intent': json['intent'] == null ? undefined : IntentEnumFromJSON(json['intent']),'source': json['source'] == null ? undefined : SourceRequestFromJSON(json['source']),+ 'prepare': json['prepare'] == null ? undefined : json['prepare'],};}@@ -118,5 +125,6 @@ export function DatasetCreateRequestToJSONTyped(value?: DatasetCreateRequest | n'capability': value['capability'],'intent': IntentEnumToJSON(value['intent']),'source': SourceRequestToJSON(value['source']),+ 'prepare': value['prepare'],};}diff --git a/frontend/src/openapi/models/DatasetReadiness.ts b/frontend/src/openapi/models/DatasetReadiness.tsdeleted file mode 100644index 5b08753a..00000000--- a/frontend/src/openapi/models/DatasetReadiness.ts+++ /dev/null@@ -1,132 +0,0 @@-/* tslint:disable */-/* eslint-disable */-/**- * Overbae API- * Backend API for the Overclaw / Overmind platform.- *- * The version of the OpenAPI document: 2.0.0- *- *- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).- * https://openapi-generator.tech- * Do not edit the class manually.- */--import { mapValues } from '../runtime';-/**- *- * @export- * @interface DatasetReadiness- */-export interface DatasetReadiness {- /**- *- * @type {{ [key: string]: string; }}- * @memberof DatasetReadiness- */- assessment: { [key: string]: string; };- /**- *- * @type {boolean}- * @memberof DatasetReadiness- */- formatValid: boolean;- /**- *- * @type {string}- * @memberof DatasetReadiness- */- formatReason: string;- /**- *- * @type {boolean}- * @memberof DatasetReadiness- */- qualityReviewed: boolean;- /**- *- * @type {boolean}- * @memberof DatasetReadiness- */- qualityPassed: boolean;- /**- *- * @type {string}- * @memberof DatasetReadiness- */- qualityReason: string;- /**- *- * @type {string}- * @memberof DatasetReadiness- */- trainingConfiguration: string;-}---/**- * @export- */-export const DatasetReadinessAssessmentEnum = {- pass: 'pass',- fail: 'fail',- partial: 'partial',- unknown: 'unknown'-} as const;-export type DatasetReadinessAssessmentEnum = typeof DatasetReadinessAssessmentEnum[keyof typeof DatasetReadinessAssessmentEnum];---/**- * Check if a given object implements the DatasetReadiness interface.- */-export function instanceOfDatasetReadiness(value: object): value is DatasetReadiness {- if (!('assessment' in value) || value['assessment'] === undefined) return false;- if (!('formatValid' in value) || value['formatValid'] === undefined) return false;- if (!('formatReason' in value) || value['formatReason'] === undefined) return false;- if (!('qualityReviewed' in value) || value['qualityReviewed'] === undefined) return false;- if (!('qualityPassed' in value) || value['qualityPassed'] === undefined) return false;- if (!('qualityReason' in value) || value['qualityReason'] === undefined) return false;- if (!('trainingConfiguration' in value) || value['trainingConfiguration'] === undefined) return false;- return true;-}--export function DatasetReadinessFromJSON(json: any): DatasetReadiness {- return DatasetReadinessFromJSONTyped(json, false);-}--export function DatasetReadinessFromJSONTyped(json: any, ignoreDiscriminator: boolean): DatasetReadiness {- if (json == null) {- return json;- }- return {-- 'assessment': json['assessment'],- 'formatValid': json['format_valid'],- 'formatReason': json['format_reason'],- 'qualityReviewed': json['quality_reviewed'],- 'qualityPassed': json['quality_passed'],- 'qualityReason': json['quality_reason'],- 'trainingConfiguration': json['training_configuration'],- };-}--export function DatasetReadinessToJSON(json: any): DatasetReadiness {- return DatasetReadinessToJSONTyped(json, false);-}--export function DatasetReadinessToJSONTyped(value?: DatasetReadiness | null, ignoreDiscriminator: boolean = false): any {- if (value == null) {- return value;- }-- return {-- 'assessment': value['assessment'],- 'format_valid': value['formatValid'],- 'format_reason': value['formatReason'],- 'quality_reviewed': value['qualityReviewed'],- 'quality_passed': value['qualityPassed'],- 'quality_reason': value['qualityReason'],- 'training_configuration': value['trainingConfiguration'],- };-}diff --git a/frontend/src/openapi/models/DatasetSplitCreateRequest.ts b/frontend/src/openapi/models/DatasetSplitCreateRequest.tsindex 02c025c5..85de8706 100644--- a/frontend/src/openapi/models/DatasetSplitCreateRequest.ts+++ b/frontend/src/openapi/models/DatasetSplitCreateRequest.ts@@ -95,6 +95,12 @@ export interface DatasetSplitCreateRequest {* @memberof DatasetSplitCreateRequest*/deduplicate?: boolean;+ /**+ * Queue the assistant's first pass, which starts once the source lands.+ * @type {boolean}+ * @memberof DatasetSplitCreateRequest+ */+ prepare?: boolean;}@@ -131,6 +137,7 @@ export function DatasetSplitCreateRequestFromJSONTyped(json: any, ignoreDiscrimi'groupBy': json['group_by'] == null ? undefined : json['group_by'],'stratifyBy': json['stratify_by'] == null ? undefined : json['stratify_by'],'deduplicate': json['deduplicate'] == null ? undefined : json['deduplicate'],+ 'prepare': json['prepare'] == null ? undefined : json['prepare'],};}@@ -155,5 +162,6 @@ export function DatasetSplitCreateRequestToJSONTyped(value?: DatasetSplitCreateR'group_by': value['groupBy'],'stratify_by': value['stratifyBy'],'deduplicate': value['deduplicate'],+ 'prepare': value['prepare'],};}diff --git a/frontend/src/openapi/models/Fit.ts b/frontend/src/openapi/models/Fit.tsnew file mode 100644index 00000000..66b7035a--- /dev/null+++ b/frontend/src/openapi/models/Fit.ts@@ -0,0 +1,74 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++import { mapValues } from '../runtime';+/**+ *+ * @export+ * @interface Fit+ */+export interface Fit {+ /**+ *+ * @type {boolean}+ * @memberof Fit+ */+ ok: boolean;+ /**+ *+ * @type {string}+ * @memberof Fit+ */+ reason: string;+}++/**+ * Check if a given object implements the Fit interface.+ */+export function instanceOfFit(value: object): value is Fit {+ if (!('ok' in value) || value['ok'] === undefined) return false;+ if (!('reason' in value) || value['reason'] === undefined) return false;+ return true;+}++export function FitFromJSON(json: any): Fit {+ return FitFromJSONTyped(json, false);+}++export function FitFromJSONTyped(json: any, ignoreDiscriminator: boolean): Fit {+ if (json == null) {+ return json;+ }+ return {++ 'ok': json['ok'],+ 'reason': json['reason'],+ };+}++export function FitToJSON(json: any): Fit {+ return FitToJSONTyped(json, false);+}++export function FitToJSONTyped(value?: Fit | null, ignoreDiscriminator: boolean = false): any {+ if (value == null) {+ return value;+ }++ return {++ 'ok': value['ok'],+ 'reason': value['reason'],+ };+}diff --git a/frontend/src/openapi/models/IntentEnum.ts b/frontend/src/openapi/models/IntentEnum.tsindex de6e0d77..ba795268 100644--- a/frontend/src/openapi/models/IntentEnum.ts+++ b/frontend/src/openapi/models/IntentEnum.ts@@ -16,14 +16,12 @@/*** * `train` - Train* * `eval` - Eval- * * `explore` - Explore* * `pending` - Pending* @export*/export const IntentEnum = {train: 'train',eval: 'eval',- explore: 'explore',pending: 'pending'} as const;export type IntentEnum = typeof IntentEnum[keyof typeof IntentEnum];diff --git a/frontend/src/openapi/models/PatchedDatasetRequest.ts b/frontend/src/openapi/models/PatchedDatasetRequest.tsindex 367d5618..117d69a2 100644--- a/frontend/src/openapi/models/PatchedDatasetRequest.ts+++ b/frontend/src/openapi/models/PatchedDatasetRequest.ts@@ -51,6 +51,12 @@ export interface PatchedDatasetRequest {* @memberof PatchedDatasetRequest*/intent?: IntentEnum;+ /**+ *+ * @type {string}+ * @memberof PatchedDatasetRequest+ */+ trainFormat?: PatchedDatasetRequestTrainFormatEnum;/**** @type {string}@@ -60,6 +66,16 @@ export interface PatchedDatasetRequest {}+/**+ * @export+ */+export const PatchedDatasetRequestTrainFormatEnum = {+ sft: 'sft',+ decision: 'decision',+ empty: ''+} as const;+export type PatchedDatasetRequestTrainFormatEnum = typeof PatchedDatasetRequestTrainFormatEnum[keyof typeof PatchedDatasetRequestTrainFormatEnum];+/*** Check if a given object implements the PatchedDatasetRequest interface.@@ -82,6 +98,7 @@ export function PatchedDatasetRequestFromJSONTyped(json: any, ignoreDiscriminato'ocrLanguages': json['ocr_languages'] == null ? undefined : json['ocr_languages'],'capability': json['capability'] == null ? undefined : json['capability'],'intent': json['intent'] == null ? undefined : IntentEnumFromJSON(json['intent']),+ 'trainFormat': json['train_format'] == null ? undefined : json['train_format'],'active': json['active'] == null ? undefined : json['active'],};}@@ -101,6 +118,7 @@ export function PatchedDatasetRequestToJSONTyped(value?: PatchedDatasetRequest |'ocr_languages': value['ocrLanguages'],'capability': value['capability'],'intent': IntentEnumToJSON(value['intent']),+ 'train_format': value['trainFormat'],'active': value['active'],};}diff --git a/frontend/src/openapi/models/PreparationEdge.ts b/frontend/src/openapi/models/PreparationEdge.tsindex cdfe8942..0055fe4f 100644--- a/frontend/src/openapi/models/PreparationEdge.ts+++ b/frontend/src/openapi/models/PreparationEdge.ts@@ -13,6 +13,14 @@*/import { mapValues } from '../runtime';+import type { PreparationEdgeKindEnum } from './PreparationEdgeKindEnum';+import {+ PreparationEdgeKindEnumFromJSON,+ PreparationEdgeKindEnumFromJSONTyped,+ PreparationEdgeKindEnumToJSON,+ PreparationEdgeKindEnumToJSONTyped,+} from './PreparationEdgeKindEnum';+/**** @export@@ -31,21 +39,30 @@ export interface PreparationEdge {* @memberof PreparationEdge*/target: string;+ /**+ *+ * @type {PreparationEdgeKindEnum}+ * @memberof PreparationEdge+ */+ kind: PreparationEdgeKindEnum;/**** @type {string}* @memberof PreparationEdge*/- label: string;+ value: string;}++/*** Check if a given object implements the PreparationEdge interface.*/export function instanceOfPreparationEdge(value: object): value is PreparationEdge {if (!('source' in value) || value['source'] === undefined) return false;if (!('target' in value) || value['target'] === undefined) return false;- if (!('label' in value) || value['label'] === undefined) return false;+ if (!('kind' in value) || value['kind'] === undefined) return false;+ if (!('value' in value) || value['value'] === undefined) return false;return true;}@@ -61,7 +78,8 @@ export function PreparationEdgeFromJSONTyped(json: any, ignoreDiscriminator: boo'source': json['source'],'target': json['target'],- 'label': json['label'],+ 'kind': PreparationEdgeKindEnumFromJSON(json['kind']),+ 'value': json['value'],};}@@ -78,6 +96,7 @@ export function PreparationEdgeToJSONTyped(value?: PreparationEdge | null, ignor'source': value['source'],'target': value['target'],- 'label': value['label'],+ 'kind': PreparationEdgeKindEnumToJSON(value['kind']),+ 'value': value['value'],};}diff --git a/frontend/src/openapi/models/PreparationEdgeKindEnum.ts b/frontend/src/openapi/models/PreparationEdgeKindEnum.tsnew file mode 100644index 00000000..9da594fb--- /dev/null+++ b/frontend/src/openapi/models/PreparationEdgeKindEnum.ts@@ -0,0 +1,59 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */+++/**+ * * `step` - step+ * * `condition` - condition+ * * `split` - split+ * * `derived` - derived+ * * `attachment` - attachment+ * @export+ */+export const PreparationEdgeKindEnum = {+ step: 'step',+ condition: 'condition',+ split: 'split',+ derived: 'derived',+ attachment: 'attachment'+} as const;+export type PreparationEdgeKindEnum = typeof PreparationEdgeKindEnum[keyof typeof PreparationEdgeKindEnum];+++export function instanceOfPreparationEdgeKindEnum(value: any): boolean {+ for (const key in PreparationEdgeKindEnum) {+ if (Object.prototype.hasOwnProperty.call(PreparationEdgeKindEnum, key)) {+ if (PreparationEdgeKindEnum[key as keyof typeof PreparationEdgeKindEnum] === value) {+ return true;+ }+ }+ }+ return false;+}++export function PreparationEdgeKindEnumFromJSON(json: any): PreparationEdgeKindEnum {+ return PreparationEdgeKindEnumFromJSONTyped(json, false);+}++export function PreparationEdgeKindEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): PreparationEdgeKindEnum {+ return json as PreparationEdgeKindEnum;+}++export function PreparationEdgeKindEnumToJSON(value?: PreparationEdgeKindEnum | null): any {+ return value as any;+}++export function PreparationEdgeKindEnumToJSONTyped(value: any, ignoreDiscriminator: boolean): PreparationEdgeKindEnum {+ return value as PreparationEdgeKindEnum;+}diff --git a/frontend/src/openapi/models/PreparationNode.ts b/frontend/src/openapi/models/PreparationNode.tsindex fd09a6fe..bd40e003 100644--- a/frontend/src/openapi/models/PreparationNode.ts+++ b/frontend/src/openapi/models/PreparationNode.ts@@ -51,6 +51,12 @@ export interface PreparationNode {* @memberof PreparationNode*/intent: string;+ /**+ *+ * @type {string}+ * @memberof PreparationNode+ */+ trainFormat: string;/**** @type {string}@@ -67,6 +73,7 @@ export function instanceOfPreparationNode(value: object): value is PreparationNoif (!('dataset' in value) || value['dataset'] === undefined) return false;if (!('datasetName' in value) || value['datasetName'] === undefined) return false;if (!('intent' in value) || value['intent'] === undefined) return false;+ if (!('trainFormat' in value) || value['trainFormat'] === undefined) return false;if (!('role' in value) || value['role'] === undefined) return false;return true;}@@ -85,6 +92,7 @@ export function PreparationNodeFromJSONTyped(json: any, ignoreDiscriminator: boo'dataset': json['dataset'],'datasetName': json['dataset_name'],'intent': json['intent'],+ 'trainFormat': json['train_format'],'role': json['role'],};}@@ -104,6 +112,7 @@ export function PreparationNodeToJSONTyped(value?: PreparationNode | null, ignor'dataset': value['dataset'],'dataset_name': value['datasetName'],'intent': value['intent'],+ 'train_format': value['trainFormat'],'role': value['role'],};}diff --git a/frontend/src/openapi/models/RolesEnum.ts b/frontend/src/openapi/models/RolesEnum.tsindex cff1d9c6..74ecfab1 100644--- a/frontend/src/openapi/models/RolesEnum.ts+++ b/frontend/src/openapi/models/RolesEnum.ts@@ -18,15 +18,13 @@* * `development` - development* * `calibration` - calibration* * `evaluation` - evaluation- * * `source` - source* @export*/export const RolesEnum = {training: 'training',development: 'development',calibration: 'calibration',- evaluation: 'evaluation',- source: 'source'+ evaluation: 'evaluation'} as const;export type RolesEnum = typeof RolesEnum[keyof typeof RolesEnum];diff --git a/frontend/src/openapi/models/TrainFormatEnum.ts b/frontend/src/openapi/models/TrainFormatEnum.tsnew file mode 100644index 00000000..07551b76--- /dev/null+++ b/frontend/src/openapi/models/TrainFormatEnum.ts@@ -0,0 +1,53 @@+/* tslint:disable */+/* eslint-disable */+/**+ * Overbae API+ * Backend API for the Overclaw / Overmind platform.+ *+ * The version of the OpenAPI document: 2.0.0+ *+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */+++/**+ * * `sft` - Sft+ * * `decision` - Decision+ * @export+ */+export const TrainFormatEnum = {+ sft: 'sft',+ decision: 'decision'+} as const;+export type TrainFormatEnum = typeof TrainFormatEnum[keyof typeof TrainFormatEnum];+++export function instanceOfTrainFormatEnum(value: any): boolean {+ for (const key in TrainFormatEnum) {+ if (Object.prototype.hasOwnProperty.call(TrainFormatEnum, key)) {+ if (TrainFormatEnum[key as keyof typeof TrainFormatEnum] === value) {+ return true;+ }+ }+ }+ return false;+}++export function TrainFormatEnumFromJSON(json: any): TrainFormatEnum {+ return TrainFormatEnumFromJSONTyped(json, false);+}++export function TrainFormatEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): TrainFormatEnum {+ return json as TrainFormatEnum;+}++export function TrainFormatEnumToJSON(value?: TrainFormatEnum | null): any {+ return value as any;+}++export function TrainFormatEnumToJSONTyped(value: any, ignoreDiscriminator: boolean): TrainFormatEnum {+ return value as TrainFormatEnum;+}diff --git a/frontend/src/openapi/models/TransferInputIntentEnum.ts b/frontend/src/openapi/models/TransferInputIntentEnum.tsindex b8872652..37dac54a 100644--- a/frontend/src/openapi/models/TransferInputIntentEnum.ts+++ b/frontend/src/openapi/models/TransferInputIntentEnum.ts@@ -16,13 +16,11 @@/*** * `train` - train* * `eval` - eval- * * `explore` - explore* @export*/export const TransferInputIntentEnum = {train: 'train',- eval: 'eval',- explore: 'explore'+ eval: 'eval'} as const;export type TransferInputIntentEnum = typeof TransferInputIntentEnum[keyof typeof TransferInputIntentEnum];diff --git a/frontend/src/openapi/models/index.ts b/frontend/src/openapi/models/index.tsindex c15cd8fe..bf8e96ef 100644--- a/frontend/src/openapi/models/index.ts+++ b/frontend/src/openapi/models/index.ts@@ -48,6 +48,7 @@ export * from './CapabilityStatusEnum';export * from './CapturedError';export * from './CatalogModel';export * from './Cell';+export * from './CellFit';export * from './CellStateEnum';export * from './CellTransformation';export * from './ChangeEnum';@@ -98,7 +99,6 @@ export * from './DatasetCreateRequest';export * from './DatasetOverlapResponse';export * from './DatasetPair';export * from './DatasetPreparation';-export * from './DatasetReadiness';export * from './DatasetSourceKindEnum';export * from './DatasetSplitCreateRequest';export * from './DatasetStateEnum';@@ -200,6 +200,7 @@ export * from './FinetuningRecommendationResponse';export * from './FinetuningSkillScore';export * from './FinetuningTimeEstimate';export * from './FinetuningTrainingMethod';+export * from './Fit';export * from './GraphEdge';export * from './GraphEdgeKindEnum';export * from './GuestClaimRequest';@@ -324,6 +325,7 @@ export * from './PlanUsageUnit';export * from './PositionEnum';export * from './PostResultsRequest';export * from './PreparationEdge';+export * from './PreparationEdgeKindEnum';export * from './PreparationNode';export * from './Project';export * from './ProjectInvite';@@ -392,6 +394,7 @@ export * from './TraceProviderEnum';export * from './TraceStatusEnum';export * from './TraceUsage';export * from './TracesServicesList200Response';+export * from './TrainFormatEnum';export * from './TrainingCheck';export * from './TrainingCheckpoint';export * from './TrainingEvidence';diff --git a/frontend/src/routes/_auth/datasets.index.tsx b/frontend/src/routes/_auth/datasets.index.tsxindex da3ed08c..9d2a32e6 100644--- a/frontend/src/routes/_auth/datasets.index.tsx+++ b/frontend/src/routes/_auth/datasets.index.tsx@@ -148,7 +148,12 @@ function ProjectDatasets({ projectId }: { projectId: string }) {aria-controls="assistant-datasets"aria-expanded={tableFocused}aria-label={tableFocused ? "Show composer" : "Focus datasets"}- className="assistant-dataset-handle absolute left-1/2 z-10 w-12 border border-border bg-card hover:bg-control"+ className={cn(+ "assistant-dataset-handle absolute left-1/2 z-10 h-5 w-10 border border-border bg-card hover:bg-control",+ tableFocused+ ? "rounded-t-none rounded-b-sm border-t-0"+ : "rounded-t-sm rounded-b-none border-b-0"+ )}onClick={() => setTableFocused((focused) => !focused)}size="icon-xs"variant="ghost"diff --git a/frontend/src/styles.css b/frontend/src/styles.cssindex b3f0ea6b..82f2d934 100644--- a/frontend/src/styles.css+++ b/frontend/src/styles.css@@ -1027,11 +1027,10 @@ body:has(top: 0;}+ /* A tab on the sheet's top border: it sits on the border while the sheet is+ lowered and hangs from it while raised. */.assistant-dataset-handle {top: 0;- border-bottom: 0;- border-bottom-right-radius: 0;- border-bottom-left-radius: 0;transform: translate(-50%, -100%);transition:transform 560ms cubic-bezier(0.22, 1, 0.36, 1),@@ -1039,7 +1038,6 @@ body:has(}.assistant-datasets[data-expanded="true"] .assistant-dataset-handle {- border: 0;transform: translate(-50%, 0);}diff --git a/overbae/api/dataset_serializers.py b/overbae/api/dataset_serializers.pyindex 0724aac0..254e1a10 100644--- a/overbae/api/dataset_serializers.py+++ b/overbae/api/dataset_serializers.py@@ -9,27 +9,24 @@ from overbae.services.datasets import (imports,lifecycle,list_activity,- review,transformation,)from overbae.services.datasets import (roles as dataset_role_service,)-from overbae.services.datasets.context import context_fingerprintfrom overbae.services.datasets.land import SPLIT_POSITIONSfrom overbae.services.datasets.workspaces import workspace_ids-class DatasetReadinessSerializer(serializers.Serializer):- assessment = serializers.DictField(- child=serializers.ChoiceField(choices=["pass", "fail", "partial", "unknown"])- )- format_valid = serializers.BooleanField()- format_reason = serializers.CharField(allow_blank=True)- quality_reviewed = serializers.BooleanField()- quality_passed = serializers.BooleanField()- quality_reason = serializers.CharField(allow_blank=True)- training_configuration = serializers.CharField()+class FitSerializer(serializers.Serializer):+ ok = serializers.BooleanField()+ reason = serializers.CharField(allow_blank=True)+++class CellFitSerializer(serializers.Serializer):+ sft = FitSerializer()+ decision = FitSerializer()+ eval = FitSerializer()class CellTransformationSerializer(serializers.Serializer):@@ -97,8 +94,7 @@ class CellSerializer(serializers.ModelSerializer):version = serializers.SerializerMethodField()frozen = serializers.SerializerMethodField()fits = serializers.SerializerMethodField()- readiness = serializers.SerializerMethodField()- preparation_plan = serializers.SerializerMethodField()+ fit = serializers.SerializerMethodField()usage = serializers.SerializerMethodField()transformation = serializers.SerializerMethodField()analytics = serializers.SerializerMethodField()@@ -124,11 +120,9 @@ class CellSerializer(serializers.ModelSerializer):"intent_report","capability_report","fits",+ "fit","analytics","review",- "quality_report",- "preparation_plan",- "readiness","seconds","used_at","usage",@@ -167,10 +161,6 @@ class CellSerializer(serializers.ModelSerializer):def get_usage(self, obj):return lifecycle.usage(obj) if obj.used_at else {}- @extend_schema_field(serializers.DictField(allow_null=True))- def get_preparation_plan(self, obj):- return obj.preparation_plan or None-def get_frozen(self, obj) -> bool:frozen_before = self.context.get("frozen_before")if frozen_before is None:@@ -182,13 +172,9 @@ class CellSerializer(serializers.ModelSerializer):ok, reason = obj.fits(intent)return {"ok": ok, "reason": reason}- @extend_schema_field(DatasetReadinessSerializer)- def get_readiness(self, obj):- return review.readiness(- self.context.get("dataset") or obj.dataset,- obj,- context=self.context.get("preparation_context"),- )+ @extend_schema_field(CellFitSerializer)+ def get_fit(self, obj):+ return obj.fit()class PreparationNodeSerializer(serializers.Serializer):@@ -196,13 +182,15 @@ class PreparationNodeSerializer(serializers.Serializer):dataset = serializers.UUIDField()dataset_name = serializers.CharField(allow_blank=True)intent = serializers.CharField()+ train_format = serializers.CharField(allow_blank=True)role = serializers.CharField(allow_blank=True)class PreparationEdgeSerializer(serializers.Serializer):source = serializers.UUIDField()target = serializers.UUIDField()- label = serializers.CharField(allow_blank=True)+ kind = serializers.ChoiceField(choices=["step", "condition", "split", "derived", "attachment"])+ value = serializers.CharField(allow_blank=True)class DatasetPreparationSerializer(serializers.Serializer):@@ -237,12 +225,10 @@ class DatasetSerializer(serializers.ModelSerializer):child=serializers.CharField(), max_length=4, required=False)operation = serializers.SerializerMethodField()- preparation_plan = serializers.SerializerMethodField()capability_name = serializers.CharField(source="capability.name", read_only=True, default=None)cells = serializers.SerializerMethodField()active_version = serializers.SerializerMethodField()rows = serializers.SerializerMethodField()- readiness = serializers.SerializerMethodField()class Meta:model = Dataset@@ -262,11 +248,10 @@ class DatasetSerializer(serializers.ModelSerializer):"capability_name","capability_rank","intent",+ "train_format","active","active_version","rows",- "readiness",- "preparation_plan","operation","state","error",@@ -278,7 +263,7 @@ class DatasetSerializer(serializers.ModelSerializer):read_only_fields = [ffor f in fields- if f not in ("name", "capability", "intent", "active", "ocr_languages")+ if f not in ("name", "capability", "intent", "train_format", "active", "ocr_languages")]@extend_schema_field(serializers.UUIDField())@@ -318,25 +303,6 @@ class DatasetSerializer(serializers.ModelSerializer):"landing_admission": admission.status(obj),}- @extend_schema_field(serializers.DictField(allow_null=True))- def get_preparation_plan(self, obj):- return obj.preparation_plan or None-- def _context_fingerprint(self, obj):- fingerprints = self.context.setdefault("capability_fingerprints", {})- if obj.capability_id not in fingerprints:- fingerprints[obj.capability_id] = context_fingerprint(obj.capability)- return fingerprints[obj.capability_id]-- @extend_schema_field(DatasetReadinessSerializer(allow_null=True))- def get_readiness(self, obj):- active = self._active(obj)- return (- review.readiness(obj, active, context=self._context_fingerprint(obj))- if active- else None- )-@extend_schema_field(CellSerializer(many=True))def get_cells(self, obj) -> list[dict]:if self.context.get("summary"):@@ -352,7 +318,6 @@ class DatasetSerializer(serializers.ModelSerializer):"frozen_before": frozen,"intent": obj.intent,"dataset": obj,- "preparation_context": self._context_fingerprint(obj),"transformations": transformation.records(obj, chain),},).data@@ -435,10 +400,16 @@ class DatasetCreateSerializer(serializers.Serializer):)intent = serializers.ChoiceField(choices=Dataset.Intent.choices, required=False)source = SourceSerializer(required=False)+ prepare = serializers.BooleanField(+ default=False,+ help_text="Queue the assistant's first pass, which starts once the source lands.",+ )def validate(self, attrs):if not attrs.get("source") and not attrs.get("brief"):raise serializers.ValidationError("Describe what you want to do or add source data.")+ if attrs.get("prepare") and not attrs.get("source"):+ raise serializers.ValidationError({"prepare": "The first pass needs source data."})if (attrs.get("source") or {}).get("llm_calls") and attrs.get("intent") not in (Dataset.Intent.TRAIN,Dataset.Intent.EVAL,@@ -467,6 +438,10 @@ class DatasetSplitCreateSerializer(serializers.Serializer):max_length=255, required=False, allow_null=True, default=None)deduplicate = serializers.BooleanField(default=True)+ prepare = serializers.BooleanField(+ default=False,+ help_text="Queue the assistant's first pass, which starts once the source lands.",+ )class DatasetPairSerializer(serializers.Serializer):diff --git a/overbae/api/dataset_transfers.py b/overbae/api/dataset_transfers.pyindex 79abe491..8b1432cf 100644--- a/overbae/api/dataset_transfers.py+++ b/overbae/api/dataset_transfers.py@@ -43,7 +43,7 @@ class TransferInputSerializer(TransferFileInputSerializer):files = TransferFileInputSerializer(many=True, required=False, min_length=1, max_length=100)dataset = serializers.UUIDField(required=False)capability = serializers.UUIDField(required=False)- intent = serializers.ChoiceField(choices=["train", "eval", "explore"], required=False)+ intent = serializers.ChoiceField(choices=["train", "eval"], required=False)brief = serializers.CharField(default="", allow_blank=True, max_length=10000)split = serializers.IntegerField(min_value=1, max_value=99, required=False)split_position = serializers.ChoiceField(choices=["head", "tail", "random"], default="tail")diff --git a/overbae/api/datasets.py b/overbae/api/datasets.pyindex 75292452..7a79cbdc 100644--- a/overbae/api/datasets.py+++ b/overbae/api/datasets.py@@ -4,7 +4,7 @@ import jsonimport loggingfrom django.conf import settings-from django.db import connections+from django.db import connections, transactionfrom django.db.models import Prefetchfrom django.http import FileResponse, StreamingHttpResponsefrom django.shortcuts import get_object_or_404@@ -29,6 +29,7 @@ from overbae.api.dataset_serializers import (from overbae.api.scoping import project_ids_forfrom overbae.api.workbench import WorkbenchActionsfrom overbae.models import Capability, Cell, Dataset, DatasetTransfer, Project+from overbae.services.assistant import threadsfrom overbae.services.datasets import diff as diff_svcfrom overbae.services.datasets import (dispatch,@@ -150,16 +151,19 @@ class DatasetViewSet(WorkbenchActions, viewsets.ModelViewSet):data = body.validated_dataproject, capability, source = self._create_target(request, data)try:- dataset = dispatch.create_dataset(- project=project,- user=request.user if request.user.is_authenticated else None,- name=data["name"].strip(),- source=source,- brief=data["brief"],- intent=data.get("intent"),- capability=capability,- infer_capability="capability" not in data,- )+ with transaction.atomic():+ dataset = dispatch.create_dataset(+ project=project,+ user=request.user if request.user.is_authenticated else None,+ name=data["name"].strip(),+ source=source,+ brief=data["brief"],+ intent=data.get("intent"),+ capability=capability,+ infer_capability="capability" not in data,+ )+ if data["prepare"] and source and request.user.is_authenticated:+ threads.queue_first_pass(dataset, request.user)except lifecycle.DatasetError as exc:raise ValidationError({"detail": exc.detail, "code": exc.code}) from excreturn Response(DatasetSerializer(dataset).data, status=status.HTTP_201_CREATED)@@ -176,20 +180,23 @@ class DatasetViewSet(WorkbenchActions, viewsets.ModelViewSet):data = body.validated_dataproject, capability, source = self._create_target(request, data)try:- train, evaluation = dispatch.create_split(- project=project,- user=request.user if request.user.is_authenticated else None,- name=data["name"].strip(),- source=source,- brief=data["brief"],- eval_percent=data["eval_percent"],- position=data["position"],- group_by=data["group_by"],- stratify_by=data["stratify_by"],- deduplicate=data["deduplicate"],- capability=capability,- infer_capability="capability" not in data,- )+ with transaction.atomic():+ train, evaluation = dispatch.create_split(+ project=project,+ user=request.user if request.user.is_authenticated else None,+ name=data["name"].strip(),+ source=source,+ brief=data["brief"],+ eval_percent=data["eval_percent"],+ position=data["position"],+ group_by=data["group_by"],+ stratify_by=data["stratify_by"],+ deduplicate=data["deduplicate"],+ capability=capability,+ infer_capability="capability" not in data,+ )+ if data["prepare"] and request.user.is_authenticated:+ threads.queue_first_pass(train, request.user, split=True)except lifecycle.DatasetError as exc:raise ValidationError({"detail": exc.detail, "code": exc.code}) from excreturn Response(diff --git a/overbae/management/commands/seed_demo.py b/overbae/management/commands/seed_demo.pyindex 8966a205..a420926e 100644--- a/overbae/management/commands/seed_demo.py+++ b/overbae/management/commands/seed_demo.py@@ -84,12 +84,13 @@ from overbae.services.activity import asset, recordfrom overbae.services.capabilities import identity as capability_identityfrom overbae.services.datasets import exploration as dataset_explorationfrom overbae.services.datasets import land as dataset_land+from overbae.services.datasets import lineage as dataset_lineagefrom overbae.services.datasets import measure as dataset_measurefrom overbae.services.datasets import partition_plansfrom overbae.services.datasets import paths as dataset_paths-from overbae.services.datasets import review as dataset_reviewfrom overbae.services.datasets import rows as row_storefrom overbae.services.datasets import store as dataset_store+from overbae.services.datasets.pipeline_execution import Parents, carryUser = get_user_model()NOW = timezone.now().replace(minute=0, second=0, microsecond=0)@@ -2503,19 +2504,17 @@ class Command(BaseCommand):previous = ds.active_cellcell = Cell.objects.create(dataset=ds, position=ds.cells.count(), title=title)output = dataset_paths.cell_path(ds.pk, cell.pk)- dataset_store.write_rows(output, records)source = dataset_paths.cell_path(ds.pk, previous.pk)- dataset_review.preserve_file_provenance(source, output, output)+ parents = Parents([(source, dataset_lineage.read(previous))], ())+ inherited = []+ dataset_store.write_rows(output, carry(records, parents, inherited))dataset_measure.frame(ds,cell,output,+ inherited=inherited,input_fingerprint=previous.fingerprint,- review={- "kind": "external",- "execution": "external_attributed",- **dataset_review.impact_files(source, output),- },+ review={"kind": "external", "execution": "external_attributed"},)Dataset.objects.filter(pk=ds.pk).update(active=cell, state="idle")ds.refresh_from_db()diff --git a/overbae/migrations/0059_data_plane_rebuild.py b/overbae/migrations/0059_data_plane_rebuild.pynew file mode 100644index 00000000..01328a2a--- /dev/null+++ b/overbae/migrations/0059_data_plane_rebuild.py@@ -0,0 +1,96 @@+from django.db import migrations, models++INTENTS = {"explore": "pending", "ft": "train", "unstructured": "eval"}+STATS = (+ "preparation_profile",+ "p95_token_length",+ "has_multi_turn_tool_calls",+ "length_profile_method",+)+REVIEW = (+ "impact",+ "rows_before",+ "rows_after",+ "rows_removed",+ "rows_added",+ "identity_preserved",+ "input_evidence_removed",+ "input_evidence_removed_examples",+ "instruction_changes",+ "instruction_change_examples",+ "decision_changes",+ "decision_rows_removed",+ "coverage_before",+ "coverage_after",+ "removed_examples",+ "input_examples",+ "output_examples",+ "validation",+)+RESULT = ("impact", "semantic_quality", "analytics", "source_columns")+++def _without(value, keys):+ return {key: item for key, item in (value or {}).items() if key not in keys}+++def forward(apps, schema_editor):+ Dataset = apps.get_model("overbae", "Dataset")+ Cell = apps.get_model("overbae", "Cell")+ Run = apps.get_model("overbae", "DatasetPipelineRun")+ for old, new in INTENTS.items():+ Dataset.objects.filter(intent=old).update(intent=new)+ for dataset in Dataset.objects.filter(intent="train").iterator():+ cell = (+ Cell.objects.filter(pk=dataset.active_id).first()+ if dataset.active_id+ else Cell.objects.filter(dataset=dataset, state="ok").order_by("-position").first()+ )+ train = ((cell.intent_report or {}).get("train") or {}) if cell else {}+ if train.get("ok"):+ dataset.train_format = "decision" if train.get("format") == "decision" else "sft"+ dataset.save(update_fields=["train_format"])+ for cell in Cell.objects.only("id", "stats", "review").iterator():+ stats, review = _without(cell.stats, STATS), _without(cell.review, REVIEW)+ # New step dicts: popping from the shared ones would hide the change from the check.+ if "steps" in review:+ review["steps"] = [_without(step, ("impact",)) for step in review["steps"] or []]+ if stats != cell.stats or review != cell.review:+ Cell.objects.filter(pk=cell.pk).update(stats=stats, review=review)+ for run in Run.objects.only("id", "result").iterator():+ result = _without(run.result, RESULT)+ if "steps" in result:+ result["steps"] = [+ _without(step, ("impact", "validation")) for step in result["steps"] or []+ ]+ if result != run.result:+ Run.objects.filter(pk=run.pk).update(result=result)+++class Migration(migrations.Migration):+ dependencies = [+ ("overbae", "0058_remove_dataset_preparation"),+ ]++ operations = [+ migrations.AddField(+ model_name="dataset",+ name="train_format",+ field=models.CharField(+ blank=True, choices=[("sft", "Sft"), ("decision", "Decision")], max_length=8+ ),+ ),+ migrations.AlterField(+ model_name="dataset",+ name="intent",+ field=models.CharField(+ choices=[("train", "Train"), ("eval", "Eval"), ("pending", "Pending")],+ default="pending",+ max_length=8,+ ),+ ),+ migrations.RunPython(forward, migrations.RunPython.noop),+ migrations.RemoveField(model_name="cell", name="preparation_plan"),+ migrations.RemoveField(model_name="cell", name="quality_report"),+ migrations.RemoveField(model_name="dataset", name="preparation_plan"),+ ]diff --git a/overbae/models/datasets.py b/overbae/models/datasets.pyindex 2d9c18c3..c749740d 100644--- a/overbae/models/datasets.py+++ b/overbae/models/datasets.py@@ -19,9 +19,12 @@ class Dataset(models.Model):class Intent(models.TextChoices):TRAIN = "train"EVAL = "eval"- EXPLORE = "explore"PENDING = "pending"+ class TrainFormat(models.TextChoices):+ SFT = "sft"+ DECISION = "decision"+class State(models.TextChoices):LANDING = "landing"IDLE = "idle"@@ -50,7 +53,8 @@ class Dataset(models.Model):# [{capability_id, name, score, reason}] best first, computed at landing.capability_rank = models.JSONField(default=list, blank=True)intent = models.CharField(max_length=8, choices=Intent.choices, default=Intent.PENDING)- preparation_plan = models.JSONField(default=dict, blank=True)+ # Which training a train dataset is for; blank until a person or a consumer decides.+ train_format = models.CharField(max_length=8, choices=TrainFormat.choices, blank=True)preparation_pipeline = models.ForeignKey("overbae.DatasetPipeline",on_delete=models.SET_NULL,@@ -225,11 +229,9 @@ class Cell(models.Model):intent_report = models.JSONField(default=dict, blank=True)# {ok, rows, rows_ok, reason} against the dataset's capability.capability_report = models.JSONField(default=dict, blank=True)- # The six numbers training planners read; see contract.stats.+ # The numbers training planners read, and decision analytics; see measure.describe_frame.stats = models.JSONField(default=dict, blank=True)review = models.JSONField(default=dict, blank=True)- quality_report = models.JSONField(default=dict, blank=True)- preparation_plan = models.JSONField(default=dict, blank=True)seconds = models.FloatField(default=0.0)used_at = models.DateTimeField(null=True, blank=True)created_by = models.ForeignKey(@@ -267,8 +269,6 @@ class Cell(models.Model):def fits(self, intent: str) -> tuple[bool, str]:"""Whether a consumer can read this version; quality findings are advisory."""- if intent == Dataset.Intent.EXPLORE:- return False, "Data exploration has no training or evaluation format."if intent not in (Dataset.Intent.TRAIN, Dataset.Intent.EVAL):return False, "The intent is still pending. Choose train or eval."if not self.ran:@@ -278,6 +278,30 @@ class Cell(models.Model):return False, str(shape.get("reason") or f"the table is not a {intent} table")return True, ""+ def fit(self) -> dict[str, dict]:+ """For each use, whether this version's rows fit it and why not."""+ report = self.intent_report or {}+ if not report:+ unmeasured = {"ok": False, "reason": "This version has not been measured."}+ return {use: dict(unmeasured) for use in ("sft", "decision", "eval")}+ train, evaluation = report.get("train") or {}, report.get("eval") or {}+ decision = train.get("format") == "decision"++ def use(ok, reason):+ return {"ok": bool(ok), "reason": "" if ok else str(reason or "")}++ return {+ Dataset.TrainFormat.SFT: use(+ train.get("ok") and not decision,+ train.get("reason") or "The rows are decisions, not conversations.",+ ),+ Dataset.TrainFormat.DECISION: use(+ train.get("ok") and decision,+ train.get("reason") or "The rows have no decision.",+ ),+ Dataset.Intent.EVAL: use(evaluation.get("ok"), evaluation.get("reason")),+ }+class DatasetHistory(models.Model):dataset = models.ForeignKey(Dataset, on_delete=models.CASCADE, related_name="history")diff --git a/overbae/services/assistant/prompt.py b/overbae/services/assistant/prompt.pyindex ba37aa11..1a2b04ef 100644--- a/overbae/services/assistant/prompt.py+++ b/overbae/services/assistant/prompt.py@@ -41,9 +41,14 @@ How you decideWhat you work with- You act through tools. Everything you make is a normal platform record the user can open.-- The first message about a dataset carries what the dataset holds now: its versions with- their columns and `path`, a measured profile, and its pipeline when it has one. Start from- these facts; do not fetch them again, and do not look up runtimes or earlier recipes.+- The first message about a dataset carries what the dataset holds now: its intent, the+ linked capability's contract, and its versions. Each version has its `path`, its `fit`+ (whether its rows already fit sft, decision or eval, and why not), its exact+ `duplicate_rows`, and for each column the kind, null rate, examples and, from a fixed+ sample of `profile_sample_rows`, distinct and most common values. Start from these facts+ and do not compute them again. Inspect only what they leave out when the request needs+ it: a profile marked unavailable, or columns past the first 40. Do not look up runtimes+ or earlier recipes.- You cannot reach the user's repository or machine, you cannot read web pages, and everydataset version comes from a source the user provided: you cannot create data from nothing.When a request needs one of these, say so in one sentence and name what you can do with the@@ -51,13 +56,21 @@ What you work withwritten here.Preparing data-1. Explore with `run_python`: the target, class balance, missing values, duplicates, leakage- between the inputs and the target. Put related checks in one cell. A version is at its- `path` once you list its cell id in `versions`.-2. Write the transformation as a pipeline package and run it with `run_pipeline`. Publish- directly; for a source above 100,000 rows run mode preview first and read its result. To+The goal of preparing a dataset is a published version whose `fit` is ok for the dataset's+intent: train with its format (sft or decision), or eval. With intent pending, choose the+use the rows are closest to from `fit`, the capability contract and the user's words, say+in a sentence which use you chose, and prepare for it. The final step's `consumer` sets the+intent. When the message names an evaluation dataset split from this one, prepare both with+the same cleaning steps; only the final formatting step differs by consumer.+1. Explore with `run_python` only what the brief does not answer: the target's meaning,+ leakage between the inputs and the target, and rows that need judgement. Put related+ checks in one cell. A version is at its `path` once you list its cell id in `versions`.+2. Write the transformation as a pipeline package and run it with `run_pipeline` in mode+ publish. Above 200 source rows it first runs the package on the first 200 rows and+ publishes nothing when that sample fails; a sample that keeps no rows does not stop the+ full run. Tocorrect the dataset's pipeline, call `run_pipeline` again with its id and the new files.-3. When training needs separate training and evaluation rows, `create_data_partition` on the+3. When the intent is train and the user wants it evaluated, `create_data_partition` on thepublished version. Each partition numbers its `source_row` again: compare partitions bytheir content, not by `source_row`.4. Check the published rows against the source with `query_dataset` or `run_python`.@@ -68,9 +81,11 @@ Preparing dataKernel and pipeline are different places- `run_python` is for exploration. Its kernel keeps variables between cells; when a cellreports that the kernel restarted, load what you need again.-- A pipeline step is the retained, repeatable transformation. It reads `input.jsonl` (one JSON- row per line) and writes `output.jsonl`. It cannot see the kernel's variables or files. Keep- `source_row` on every output row.+- A pipeline step is the retained, repeatable transformation. By default it reads+ `input.jsonl` (one JSON row per line) and writes `output.jsonl`; with `"io": "parquet"` in+ the step it reads `input.parquet` and writes `output.parquet`, which is faster for large or+ wide data. Set `batch_rows` when each row is processed on its own. A step cannot see the+ kernel's variables or files. Keep `source_row` on every output row.- A tool that starts a job waits for it and returns its result. Do not poll.Showing resultsdiff --git a/overbae/services/assistant/threads.py b/overbae/services/assistant/threads.pyindex d51aa496..b470a919 100644--- a/overbae/services/assistant/threads.py+++ b/overbae/services/assistant/threads.py@@ -1,16 +1,32 @@"""What a user does to a conversation: open it, send a message, change the queue."""+import json+from django.db import transactionfrom django.db.models import F, Maxfrom overbae.core.errors import InputValidationErrorfrom overbae.models import AssistantInput, AssistantThread, Cell, Datasetfrom overbae.services.assistant import log+from overbae.services.codebase.flow import build_capability_flow+from overbae.services.datasets import alignment, rows, storeQueued = AssistantInput.State.QUEUED# A wide dataset names its first columns; the model queries the rest.BRIEF_COLUMNS = 40-BRIEF_EXAMPLE_CHARS = 160+TOP_VALUE_CHARS = 80+CONTRACT_CHARS = 4000+CAPABILITY_FIELDS = (+ "description",+ "system_prompt",+ "input_schema",+ "output_fields",+ "expected_output",+ "output_schema",+ "success_criteria",+ "failure_modes",+ "vocabulary",+)def open_thread(dataset: Dataset) -> AssistantThread:@@ -40,35 +56,128 @@ def brief(thread) -> dict:"version": names.get(cell.pk),"rows": cell.rows,"path": f"data/{data_name(cell)}",- "column_count": len(cell.columns),- "columns": cell.columns[:BRIEF_COLUMNS],+ "fit": cell.fit(),+ **_profile(cell),}out = {- "dataset": {"id": str(dataset.pk), "name": dataset.name, "intent": dataset.intent},+ "dataset": {+ "id": str(dataset.pk),+ "name": dataset.name,+ "intent": dataset.intent,+ "train_format": dataset.train_format,+ },"versions": len(names),}+ if dataset.capability_id is not None:+ out["capability"] = capability_contract(dataset.capability)if source is not None and source.ran:- measured = (source.stats.get("preparation_profile") or {}).get("columns") or {}- out["source"] = version(source) | {- "profile": {- name: {- "empty_rows": column.get("empty_rows"),- "examples": [- example[:BRIEF_EXAMPLE_CHARS] for example in column.get("examples", [])[:2]- ],- }- for name, column in list(measured.items())[:BRIEF_COLUMNS]- }- }+ out["source"] = version(source)if active is not None and active != source:out["latest"] = version(active)recipe = dataset.preparation_pipelineif recipe is not None:out["pipeline"] = {"id": str(recipe.family), "name": recipe.name}+ split = (dataset.source_spec or {}).get("split") or {}+ sibling = Dataset.objects.filter(pk=split.get("sibling"), project=dataset.project_id).first()+ if sibling is not None:+ out["split"] = {+ "role": split.get("role"),+ "sibling": {+ "id": str(sibling.pk),+ "name": sibling.name,+ "intent": sibling.intent,+ "source_cell": str(sibling.source.pk) if sibling.source else None,+ },+ }return out+def _profile(cell) -> dict:+ """Each column's kind, nulls, examples and, from a fixed sample, its distinct and most+ common values; and the version's exact duplicate rows."""+ try:+ measured = store.frame_profile(+ rows.frame_path(cell), fingerprint=cell.fingerprint, duplicates=True+ )+ except (rows.RowStoreError, store.StoreError):+ measured = None+ by_name = {column["name"]: column for column in (measured or {}).get("columns", [])}+ columns = []+ for column in cell.columns[:BRIEF_COLUMNS]:+ stats = by_name.get(column["name"], {})+ columns.append(+ {+ key: value+ for key, value in {+ "name": column["name"],+ "type": column.get("type"),+ "null_rate": round(column.get("null_rate", 0.0), 4),+ "examples": column.get("examples", []),+ "distinct": stats.get("distinct"),+ "top": [+ {"value": str(top["value"])[:TOP_VALUE_CHARS], "count": top["count"]}+ for top in stats.get("top", [])+ ]+ or None,+ **{k: stats.get(k) for k in ("min", "max", "mean", "mean_len", "max_len")},+ }.items()+ if value is not None+ }+ )+ out = {"column_count": len(cell.columns), "columns": columns}+ if measured is None:+ out["profile"] = "unavailable"+ return out+ sample = next(iter(by_name.values()), {})+ out["duplicate_rows"] = measured["duplicate_rows"]+ out["profile_sample_rows"] = sample.get("sample_rows", measured["rows"])+ return out+++def capability_contract(capability) -> dict:+ """What the capability takes and returns, as its card states it, bounded."""+ card = build_capability_flow(capability)+ out = {"name": capability.name}+ for field in CAPABILITY_FIELDS:+ value = {+ "description": capability.description,+ "system_prompt": alignment.system_prompt(capability),+ # The schema alignment checks rows against, as the card states it.+ "output_schema": (+ (capability.improvement_metadata or {}).get("capability_card") or {}+ ).get("output_schema"),+ }.get(field, card.get(field))+ if not value:+ continue+ text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)+ out[field] = value if len(text) <= CONTRACT_CHARS else text[:CONTRACT_CHARS]+ tools = [+ t["name"] for t in card.get("tool_spec") or [] if isinstance(t, dict) and t.get("name")+ ]+ if tools:+ out["tools"] = tools+ return out+++FIRST_PASS = {+ Dataset.Intent.TRAIN: "Prepare this dataset for training.",+ Dataset.Intent.EVAL: "Prepare this dataset for evaluation.",+ Dataset.Intent.PENDING: "Prepare this dataset for the use its rows fit best.",+}+SPLIT_PASS = "Prepare this dataset for training and its evaluation split for evaluation."+FIRST_PASS_KEY = "first-pass:"+++def queue_first_pass(dataset: Dataset, user, *, split: bool = False) -> AssistantInput:+ """The first message of a dataset made with an intent or a brief: its turn starts once+ the source lands. A split prepares both halves in one conversation, with one script."""+ text = SPLIT_PASS if split else FIRST_PASS[dataset.intent]+ if dataset.brief.strip():+ text = f"{text}\n\n{dataset.brief.strip()}"+ return send(open_thread(dataset), user, request_key=f"{FIRST_PASS_KEY}{dataset.pk}", text=text)++def send(thread, user, *, request_key, text, cells=(), interaction=None) -> AssistantInput:"""Queue a message. The same key with the same message returns the first one."""cells = [str(cell) for cell in cells]diff --git a/overbae/services/assistant/tools.py b/overbae/services/assistant/tools.pyindex fd2d0b0e..b334b1ef 100644--- a/overbae/services/assistant/tools.py+++ b/overbae/services/assistant/tools.py@@ -19,7 +19,7 @@ from django.conf import settingsfrom django.db.models import Qfrom overbae.core.errors import InputValidationError-from overbae.models import AssistantThread, Cell, DatasetPipeline+from overbae.models import AssistantThread, Cell, DatasetPipeline, DatasetPipelineRunfrom overbae.services import workspacesfrom overbae.services.assistant import presentationfrom overbae.services.assistant.threads import data_name@@ -48,6 +48,8 @@ MAX_CODE_CHARS = 64_000RESULT_CHARS = 24_000# A job a call started is waited for within the turn, to this limit.JOB_SECONDS = 25 * 60+# Rows a publish runs first, so a broken package fails in seconds and publishes nothing.+SAMPLE_ROWS = 200POLL_SECONDS = 2OWN_TOOLS = {@@ -80,8 +82,10 @@ OWN_TOOLS = {"run_pipeline": ("Retain a transformation and run it on one dataset version; the result comes back ""when the run ends. `files` is the package: manifest.json and its entrypoints, as "- "the package contract says. Mode publish runs every row and adds the result to the "- "dataset as new versions. Mode preview runs the first rows and changes nothing. To "+ "the package contract says. Mode publish first runs the package on the first "+ f"{SAMPLE_ROWS} rows; when that fails it returns the error and publishes nothing, "+ "otherwise it runs every row and adds the result to the dataset as new versions. "+ "Mode preview runs the first rows and changes nothing. To ""correct a pipeline, pass its id as `pipeline` with the new files; that saves its ""next revision. To run a saved pipeline again, pass `pipeline` and no files. The ""platform sets the manifest's `runtime`: leave it out.",@@ -358,21 +362,48 @@ def _run_pipeline(turn: Turn, arguments) -> Outcome:run = {"dataset": dataset,"pipeline": revision,- "mode": arguments.get("mode"),"parameters": arguments.get("parameters") or {},- "request_key": turn.key("run"),**pinned,}+ mode = arguments.get("mode")+ if mode == "publish" and (source.rows or 0) > SAMPLE_ROWS:+ sample = {**run, "mode": "preview", "preview_rows": SAMPLE_ROWS}+ ok, finished = _run(turn, {**sample, "request_key": turn.key("sample")})+ if not ok and not _empty(finished):+ return Outcome(False, {**content, "sample": finished, "error": _error(finished)})+ # Stop lets started jobs finish; the full run has not started.+ if not turn.alive():+ return Outcome(False, {**content, "error": "The user stopped the conversation."})+ ok, finished = _run(turn, {**run, "mode": mode, "request_key": turn.key("run")})+ if ok:+ return Outcome(True, {**content, "run": finished})+ return Outcome(False, {**content, "run": finished, "error": _error(finished)})+++def _run(turn: Turn, run: dict) -> tuple[bool, dict]:ran = _invoke(turn, "run_dataset_pipeline", run)if ran.isError:- return Outcome(False, {**content, **ran.structuredContent})+ return False, ran.structuredContentreceipt = ran.structuredContent["job"]- finished = _wait(turn, receipt)- if finished.get("status") == "completed":- return Outcome(True, {**content, "run": finished})+ finished = {**_wait(turn, receipt), "id": receipt["id"]}+ return finished.get("status") == "completed", finished+++def _empty(finished: dict) -> bool:+ """A sample whose script ran but kept none of the first rows says nothing about the+ rest: the full run decides."""+ run = DatasetPipelineRun.objects.filter(pk=finished.get("id"), state="failed").first()+ steps = (run.result or {}).get("steps") or [] if run else []+ return bool(steps) and steps[-1].get("exit_code") == 0 and steps[-1].get("output_rows") == 0+++def _error(finished: dict) -> str:# The reader sees a failed step by its error, wherever the run recorded it.- error = (finished.get("details") or {}).get("error") or f"The run is {finished.get('status')}."- return Outcome(False, {**content, "run": finished, "error": error})+ return (+ finished.get("error", {}).get("message")+ if isinstance(finished.get("error"), dict)+ else (finished.get("details") or {}).get("error")+ ) or f"The run is {finished.get('status')}."def image_path(thread: AssistantThread, name: str) -> Path:diff --git a/overbae/services/assistant/turn.py b/overbae/services/assistant/turn.pyindex 14e2a0fa..61391a4a 100644--- a/overbae/services/assistant/turn.py+++ b/overbae/services/assistant/turn.py@@ -18,7 +18,14 @@ from django.utils import timezonefrom overbae.core.llms import IncompleteCompletionError, call_llm_tools, stream_llm_toolsfrom overbae.core.model_registry import TaskType, model_chain-from overbae.models import AssistantEvent, AssistantInput, AssistantThread, BillingService, Dataset+from overbae.models import (+ AssistantEvent,+ AssistantInput,+ AssistantThread,+ BillingService,+ Cell,+ Dataset,+)from overbae.models.assistant import STALEfrom overbae.services.assistant import log, prompt, threads, toolsfrom overbae.services.billing_ledger import InsufficientCredits, charge_llm_usage, ensure_credits@@ -56,10 +63,21 @@ def wake(thread: AssistantThread) -> None:transaction.on_commit(lambda: run_turn.delay(str(thread.pk)))+def ready(thread):+ """The queued messages a turn may take. The first pass prepares landed rows: after an+ import fails it stays queued for the landing that succeeds."""+ queued = thread.inputs.filter(state=Queued)+ if not Cell.objects.filter(+ dataset_id=thread.dataset_id, position=0, state=Cell.State.OK+ ).exists():+ queued = queued.exclude(request_key__startswith=threads.FIRST_PASS_KEY)+ return queued++def wake_dataset(dataset_id) -> None:"""The dataset's source landed: a message that waited for it may start its turn."""thread = AssistantThread.objects.filter(dataset_id=dataset_id).first()- if thread is not None and thread.inputs.filter(state=Queued).exists():+ if thread is not None and ready(thread).exists():wake(thread)@@ -83,7 +101,7 @@ def settle(thread: AssistantThread) -> AssistantThread:"detail": "The turn was interrupted. Send a message to continue.",},)- if held.inputs.filter(state=Queued).exists():+ if ready(held).exists():wake(held)thread.refresh_from_db()return thread@@ -106,7 +124,7 @@ def run(thread_id) -> None:_status(thread, "failed", "The turn failed. Send a message to continue.")if _held(thread).update(state=State.IDLE, stop_requested=False):log.changed(thread)- if thread.inputs.filter(state=Queued).exists():+ if ready(thread).exists():wake(thread)@@ -119,7 +137,7 @@ def _begin(thread_id) -> AssistantThread | None:.select_related("project", "dataset").get(pk=thread_id))- if thread.state == State.RUNNING or not thread.inputs.filter(state=Queued).exists():+ if thread.state == State.RUNNING or not ready(thread).exists():return None# A first message on a new dataset waits for its source; landing wakes the thread.if thread.dataset.state == Dataset.State.LANDING:@@ -156,12 +174,12 @@ def _stopped(thread) -> None:def _turn(thread) -> None:deadline = time.monotonic() + TURN_SECONDS- message = thread.inputs.filter(state=Queued).order_by("-urgent", "position").first()+ message = ready(thread).order_by("-urgent", "position").first()# Past the deadline the rest stay queued: ``run`` starts the next turn for them.while message is not None and time.monotonic() < deadline:if _deliver(thread, message):_answer(thread, deadline)- message = thread.inputs.filter(state=Queued).order_by("-urgent", "position").first()+ message = ready(thread).order_by("-urgent", "position").first()def _answer(thread, deadline: float) -> None:@@ -175,7 +193,7 @@ def _answer(thread, deadline: float) -> None:)return# A message sent "now" joins at the next model call.- for urgent in thread.inputs.filter(state=Queued, urgent=True).order_by("position"):+ for urgent in ready(thread).filter(urgent=True).order_by("position"):_deliver(thread, urgent)user = _actor(thread)if user is None:@@ -226,7 +244,10 @@ def _deliver(thread, message) -> bool:None,)# Saving a recipe updates the row, not the dataset this turn loaded.- thread.dataset.refresh_from_db(fields=["preparation_pipeline"])+ # A turn's publish changes these; the brief reads them fresh.+ thread.dataset.refresh_from_db(+ fields=["preparation_pipeline", "intent", "train_format", "capability", "source_spec"]+ )now = threads.brief(thread)with transaction.atomic():# The thread first, as every queue change locks it: a stop that came after thediff --git a/overbae/services/datasets/analytics.py b/overbae/services/datasets/analytics.pyindex cd2ffeb0..7840eb3a 100644--- a/overbae/services/datasets/analytics.py+++ b/overbae/services/datasets/analytics.py@@ -24,6 +24,7 @@ class Analytics:self.input_rows = 0self.structured_input_rows = self.weighted_rows = 0self.families = {}+ self.keys = {}def observe(self, decision, *, valid):self.rows += 1@@ -43,28 +44,28 @@ class Analytics:if key not in self.fields and len(self.fields) >= FIELD_LIMIT:self.field_overflow = Truecontinue- field = self.fields.setdefault(- key, {"present": 0, "empty": 0, "first": None, "varies": False}- )+ field = self.fields.setdefault(key, {"present": 0, "empty": 0, "varies": False})field["present"] += 1if missing(value):field["empty"] += 1- else:- signature = digest(value)- if field["first"] is None:- field["first"] = signature- field["varies"] |= signature != field["first"]+ elif "first" not in field:+ field["first"] = value+ elif not field["varies"]:+ first = field["first"]+ field["varies"] = type(value) is not type(first) or value != firstsemantics = decision.get("target_semantics") or "unknown"self.unknown += semantics == "unknown"options = decision["options"]- key = digest([decision["question"], decision["kind"], options, semantics])- if (- len(options) > OPTION_LIMIT- or key not in self.families- and len(self.families) >= FAMILY_LIMIT- ):- self.unlisted += 1- return+ identity = (decision["question"], decision["kind"], tuple(options), semantics)+ key = self.keys.get(identity)+ if key is None:+ # Only tracked families are cached: a frame of distinct questions stays small.+ if len(options) > OPTION_LIMIT or len(self.families) >= FAMILY_LIMIT:+ self.unlisted += 1+ return+ key = self.keys[identity] = digest(+ [decision["question"], decision["kind"], options, semantics]+ )family = self.families.setdefault(key,{@@ -118,7 +119,7 @@ class Analytics:count = self.input_rows - field["present"] + field["empty"]if count:missing_fields.append({"field": name[:120], "rows": count})- if field["first"] is not None and not field["varies"]:+ if "first" in field and not field["varies"]:constants.append(name[:120])def check(identifier, title, status, summary, metrics=None):diff --git a/overbae/services/datasets/attachments.py b/overbae/services/datasets/attachments.pyindex 0942895a..df409f1d 100644--- a/overbae/services/datasets/attachments.py+++ b/overbae/services/datasets/attachments.py@@ -1,16 +1,15 @@from __future__ import annotations+import itertoolsimport shutil-from itertools import chainfrom pathlib import Pathfrom typing import TYPE_CHECKINGfrom django.utils import timezonefrom overbae.models import Cell, Dataset-from overbae.services.datasets import measure, operations, paths, store+from overbae.services.datasets import lineage, measure, operations, paths, storefrom overbae.services.datasets.lifecycle import DatasetError-from overbae.services.datasets.partition import preserve_lineageif TYPE_CHECKING:from overbae.services.datasets.land import Landing@@ -30,7 +29,9 @@ def merge(dataset: Dataset, cell: Cell, previous: Cell, output: Path) -> Path:raise DatasetError("Row identities changed before this import. Add the files again.")def rows():- for index, row in enumerate(chain(store.iter_rows(before), store.iter_rows(batch_path))):+ for index, row in enumerate(+ itertools.chain(store.iter_rows(before), store.iter_rows(batch_path))+ ):if index % 1000 == 0:operations.check_cancelled(dataset.id)yield row@@ -60,7 +61,6 @@ def commit(dataset: Dataset, landing: Landing, *, user=None) -> Cell:operations.check_cancelled(dataset.id)row = dict(original)row[store.SOURCE_ROW] = next_row + offset- row["_overmind_provenance"] = preserve_lineage(row)yield rowsources = {item["id"]: item for item in dataset.source_spec.get("sources", [])}@@ -101,5 +101,14 @@ def commit(dataset: Dataset, landing: Landing, *, user=None) -> Cell:updated_at=timezone.now(),)dataset.refresh_from_db()- measure.frame(dataset, cell, output, input_fingerprint=previous.fingerprint, seconds=0.0)+ measure.frame(+ dataset,+ cell,+ output,+ inherited=itertools.chain(+ (keys for _, keys in lineage.read(previous)), itertools.repeat(lineage.NONE)+ ),+ input_fingerprint=previous.fingerprint,+ seconds=0.0,+ )return celldiff --git a/overbae/services/datasets/context.py b/overbae/services/datasets/context.pyindex 4cf2ce4a..5ca6e063 100644--- a/overbae/services/datasets/context.py+++ b/overbae/services/datasets/context.py@@ -1,13 +1,5 @@from __future__ import annotations-import hashlib-import json--from overbae.models import EvalMatrix-from overbae.services.codebase.flow import build_capability_flow-from overbae.services.datasets import paths, store-from overbae.services.datasets.profile import profile_records-CONSUMERS = {"decision_training": {"reads": ["decision"],@@ -43,7 +35,8 @@ CONSUMERS = {}-def workshop_context(dataset, *, measure_missing=True) -> dict:+def workshop_context(dataset) -> dict:+ """The consumer contracts, and the columns of the source and active versions."""versions = dataset.versions()profiles = {}for name, cell in (("source", dataset.source), ("active", dataset.active_cell)):@@ -51,68 +44,10 @@ def workshop_context(dataset, *, measure_missing=True) -> dict:continueif name == "active" and profiles.get("source", {}).get("cell") == str(cell.id):continue- path = paths.cell_path(dataset.id, cell.id)- if not path.exists():- profiles[name] = {"cell": str(cell.id), "error": "Frame unavailable"}- continueprofiles[name] = {"cell": str(cell.id),"version": versions.get(cell.id),- "fingerprint": cell.fingerprint,- **(- cell.stats.get("preparation_profile")- or (- profile_records(store.iter_rows(path))- if measure_missing- else {- "status": "unmeasured",- "next_action": "explore_dataset",- "source_cell": str(cell.id),- }- )- ),+ "rows": cell.rows,+ "columns": cell.columns,}- return {- "consumers": CONSUMERS,- "profiles": profiles,- "preparation_plan": dataset.preparation_plan,- }---def preparation_context(capability) -> dict:- if capability is None:- return {"capability": None, "expectations": []}- flow = build_capability_flow(capability)- metadata = capability.improvement_metadata or {}- card = metadata.get("capability_card") or {}- expectations = capability.eval_matrix.filter(enabled=True, type=EvalMatrix.Type.LLM)- return {- "capability": str(capability.id),- "name": capability.name,- "description": capability.description,- "decision_logic": capability.decision_logic,- "policy": capability.policy_markdown,- "output_schema": card.get("output_schema") or {},- **{- key: flow.get(key)- for key in (- "task",- "domain",- "modality",- "system_prompt",- "input_schema",- "expected_output",- "tool_spec",- "success_criteria",- "failure_modes",- )- },- "expectations": [- {"name": row.name, "expectation": row.source} for row in expectations.order_by("name")- ],- }---def context_fingerprint(capability) -> str:- raw = json.dumps(preparation_context(capability), sort_keys=True, default=str)- return hashlib.sha256(raw.encode()).hexdigest()+ return {"consumers": CONSUMERS, "profiles": profiles}diff --git a/overbae/services/datasets/contract.py b/overbae/services/datasets/contract.pyindex b7c9998c..30276fce 100644--- a/overbae/services/datasets/contract.py+++ b/overbae/services/datasets/contract.py@@ -5,7 +5,6 @@ from __future__ import annotationsimport contextlibimport jsonimport math-import randomimport refrom collections import Counterfrom typing import Any@@ -18,7 +17,6 @@ from modal_shared.decisions import (decision_line,decision_reference,)-from overbae.services.datasets import storefrom overbae.services.datasets.examples import identifier_only, normalize_recordfrom overbae.services.datasets.text import approx_tokensfrom overbae.services.finetuning_tool_validation import tool_schema_errors@@ -26,7 +24,6 @@ from overbae.services.finetuning_tool_validation import tool_schema_errorsTRAIN = "train"EVAL = "eval"PENDING = "pending"-EXPLORE = "explore"_LEGACY_INTENT = {"ft": TRAIN, "unstructured": EVAL}_FAILURE_SAMPLES = 10@@ -34,7 +31,7 @@ _FAILURE_SAMPLES = 10def public_intent(value: str | None) -> str:"""``ft`` → train, ``unstructured`` → eval; leftover rows were never rewritten."""raw = (value or "").strip()- if raw in (TRAIN, EVAL, PENDING, EXPLORE):+ if raw in (TRAIN, EVAL, PENDING):return rawreturn _LEGACY_INTENT.get(raw, PENDING)@@ -141,12 +138,22 @@ def training_line(record: dict[str, Any]) -> dict[str, Any]:return line-def _train_check(df: pd.DataFrame) -> dict[str, Any]:+def _train_check(df: pd.DataFrame, decision_problems=None) -> dict[str, Any]:# The validator also imports training_line for the shared export contract.- from overbae.services.finetuning_validator import validate_rows+ from overbae.services.finetuning_validator import ValidationResult, validate_rowsif "decision" in df.columns:- result = validate_rows(df[["decision"]].to_dict("records"))+ if decision_problems is None:+ result = validate_rows(df[["decision"]].to_dict("records"))+ else:+ errors = [+ f"Example {number}: {problem}"+ for number, problem in enumerate(decision_problems, 1)+ if problem is not None+ ][:20]+ result = ValidationResult(+ valid=not errors, format="decision", num_examples=len(df), errors=errors+ )semantics = Counter(value.get("target_semantics") or "unspecified_distribution"for value in df["decision"]@@ -209,10 +216,35 @@ def _eval_check(df: pd.DataFrame) -> dict[str, Any]:if "expected_output" in df.columns:reference_rows = sum(1 for v in df["expected_output"].tolist() if not _missing(v))if not reference_rows:+ # A frame of a batched output reports its types and its native decisions with+ # no reference: references in other frames clear only "no expected_output".+ # Tool schemas do not depend on references, so they fail here as in one frame.+ tool_failures = [+ {"row": index, "reason": reason}+ for index, value in enumerate(inputs)+ if isinstance(payload := normalize_record({"input": _as_obj(value)})["input"], dict)+ and "messages" in payload+ for reason in tool_schema_errors(payload.get("tools"))+ ]+ if tool_failures:+ return {+ "ok": False,+ "reason": tool_failures[0]["reason"],+ "failures": tool_failures[:_FAILURE_SAMPLES],+ "input_type": input_type,+ "input_types": dict(types),+ "has_reference": False,+ }return {"ok": False,"reason": "no expected_output values","input_type": input_type,+ "input_types": dict(types),+ "unreferenced_decisions": sum(+ isinstance(payload := normalize_record({"input": _as_obj(value)})["input"], dict)+ and "decision" in payload+ for value in inputs+ ),"has_reference": False,}failures = []@@ -234,6 +266,8 @@ def _eval_check(df: pd.DataFrame) -> dict[str, Any]:"ok": False,"reason": failures[0]["reason"],"failures": failures[:_FAILURE_SAMPLES],+ "input_type": input_type,+ "input_types": dict(types),"has_reference": True,}return {@@ -252,8 +286,9 @@ def _eval_check(df: pd.DataFrame) -> dict[str, Any]:}-def measure(df: pd.DataFrame) -> dict[str, Any]:- """``{rows, train: {ok, reason, …}, eval: {ok, reason, …}}``."""+def measure(df: pd.DataFrame, decision_problems=None) -> dict[str, Any]:+ """``{rows, train: {ok, reason, …}, eval: {ok, reason, …}}``. ``decision_problems``+ holds each row's decision-column problem when the caller already checked it."""rows = int(len(df))if rows == 0:return {@@ -261,21 +296,29 @@ def measure(df: pd.DataFrame) -> dict[str, Any]:"train": {"ok": False, "reason": "no rows"},"eval": {"ok": False, "reason": "no rows"},}- report = {"rows": rows, "train": _train_check(df), "eval": _eval_check(df)}+ report = {+ "rows": rows,+ "train": _train_check(df, decision_problems),+ "eval": _eval_check(df),+ }if not (report["train"]["ok"] or report["eval"]["ok"]) and not _has_text(df):for shape in (report["train"], report["eval"]):shape["fixable"] = Falsereturn report-def measure_path(path):+def measure_frames(frames, columns):+ """``measure`` over consecutive ``(frame, decision_problems)`` pairs, merged as one+ report."""result = Noneoffset = 0types = Counter()semantics = Counter()references = 0- for df in store.iter_frames(path):- part = measure(df)+ unreferenced = 0+ for df, decision_problems in frames:+ part = measure(df, decision_problems)+ unreferenced += part["eval"].get("unreferenced_decisions", 0)semantics.update(part["train"].get("target_semantics", {}))evaluation = part["eval"]references += evaluation.get("reference_rows", 0)@@ -304,7 +347,7 @@ def measure_path(path):target.pop("fixable", None)offset += len(df)if result is None:- return measure(pd.DataFrame(columns=[c["name"] for c in store.read_manifest(path)]))+ return measure(pd.DataFrame(columns=columns))evaluation = result["eval"]if semantics:result["train"].update(@@ -317,7 +360,12 @@ def measure_path(path):evaluation["has_reference"] = Trueevaluation["reference_rows"] = referencesif evaluation.get("reason") == "no expected_output values":- evaluation.update(ok=True, reason="")+ evaluation.update(+ ok=not unreferenced,+ reason=f"{unreferenced} decision inputs have no expected_output"+ if unreferenced+ else "",+ )if types:evaluation.update(input_types=dict(types), input_type=types.most_common(1)[0][0])return result@@ -338,12 +386,6 @@ def _has_text(df: pd.DataFrame) -> bool:return False-def stats(df: pd.DataFrame) -> dict[str, Any]:- """The six numbers training planners read. Input is ``messages`` when- present, else ``input``; output is ``expected_output``."""- return stats_rows(df.to_dict(orient="records"), set(df.columns))--class RowStatistics:def __init__(self, columns):self.in_col = (@@ -357,9 +399,7 @@ class RowStatistics:)self.out_col = "expected_output" if "expected_output" in columns else Noneself.n = self.total_in = self.total_out = self.max_tokens = 0- self.tool_calling = self.multi_turn = False- self.lengths = []- self.rng = random.Random(0)+ self.tool_calling = Falsedef observe(self, record):self.n += 1@@ -372,40 +412,19 @@ class RowStatistics:)self.total_in += len(in_str)self.total_out += len(out_str)- length = approx_tokens(in_str + out_str)- self.max_tokens = max(self.max_tokens, length)- if len(self.lengths) < 10000:- self.lengths.append(length)- else:- index = self.rng.randrange(self.n)- if index < len(self.lengths):- self.lengths[index] = length- turns = _tool_call_turns(inp)- self.tool_calling |= turns > 0- self.multi_turn |= turns > 1+ self.max_tokens = max(self.max_tokens, approx_tokens(in_str + out_str))+ self.tool_calling |= _tool_call_turns(inp) > 0def result(self):return {"num_examples": self.n,"has_tool_calling": self.tool_calling,- "has_multi_turn_tool_calls": self.multi_turn,"max_token_length": self.max_tokens,- "p95_token_length": sorted(self.lengths)[math.ceil(len(self.lengths) * 0.95) - 1]- if self.lengths- else 0,- "length_profile_method": "deterministic_reservoir_10000_character_estimate","avg_input_chars": round(self.total_in / self.n) if self.n else 0,"avg_output_chars": round(self.total_out / self.n) if self.n else 0,}-def stats_rows(records, columns) -> dict[str, Any]:- statistics = RowStatistics(columns)- for record in records:- statistics.observe(record)- return statistics.result()--def _tool_call_turns(inp: Any) -> int:messages = (inp if isinstance(inp, list) else inp.get("messages") if isinstance(inp, dict) else Nonediff --git a/overbae/services/datasets/diff.py b/overbae/services/datasets/diff.pyindex e58da655..72459935 100644--- a/overbae/services/datasets/diff.py+++ b/overbae/services/datasets/diff.py@@ -22,7 +22,11 @@ def _short(value: Any) -> Any:def _names(path: Path) -> list[str]:- return [c["name"] for c in store.read_manifest(path) if c["name"] != "_overmind_provenance"]+ return [+ c["name"]+ for c in store.read_manifest(path)+ if c["name"] not in ("_overmind_provenance", store.EVIDENCE)+ ]def _tracked(a: Path, b: Path) -> bool:diff --git a/overbae/services/datasets/examples.py b/overbae/services/datasets/examples.pyindex fd1d5040..659a749d 100644--- a/overbae/services/datasets/examples.py+++ b/overbae/services/datasets/examples.py@@ -28,12 +28,14 @@ def decode(value):def normalize_record(record: dict) -> dict:- row = copy.deepcopy(record)+ """``record`` with JSON-encoded transcript fields decoded; ``record`` is not changed."""+ row = dict(record)for key in ("messages", "tools"):if key in row:row[key] = None if missing(row[key]) else decode(row[key])payload = decode(row.get("input"))if isinstance(payload, dict) and "messages" in payload:+ payload = dict(payload)for key in ("messages", "tools"):if key in payload:payload[key] = None if missing(payload[key]) else decode(payload[key])diff --git a/overbae/services/datasets/exploration.py b/overbae/services/datasets/exploration.pyindex 027155c7..4f11ffd7 100644--- a/overbae/services/datasets/exploration.py+++ b/overbae/services/datasets/exploration.py@@ -10,9 +10,18 @@ from django.utils import timezonefrom overbae.core.errors import InputValidationErrorfrom overbae.models import Cell, DataExploration, Dataset, Project-from overbae.services.datasets import events, land, paths, profile, rows, sampling, store, use+from overbae.services.datasets import (+ events,+ land,+ lineage,+ paths,+ profile,+ rows,+ sampling,+ store,+ use,+)from overbae.services.datasets.examples import native_decision-from overbae.services.datasets.partition import preserve_lineagelogger = logging.getLogger(__name__)PROFILE_VERSION = 4@@ -137,17 +146,6 @@ def advance(identifier):}else:-- def records():- for index, record in enumerate(store.iter_rows(path)):- lineage = preserve_lineage(record)- lineage["derived_from"] = {- "cell": str(op.source_cell_id),- "fingerprint": op.source_fingerprint,- "row": index,- }- yield {**record, "_overmind_provenance": lineage}-with transaction.atomic():source = op.source_cell.datasetderived, _ = Dataset.objects.get_or_create(@@ -157,13 +155,18 @@ def advance(identifier):"name": op.name,"brief": source.brief,"intent": source.intent,+ "train_format": source.train_format,"capability_id": source.capability_id,},)if not derived.active_cell:land.commit(derived,- land.Landing(records(), spec={"derived_from": report["source"]}),+ land.Landing(+ store.iter_rows(path),+ spec={"derived_from": report["source"]},+ inherited=lineage.stream(op.source_cell),+ ),infer_capability=False,)rows.verify(derived.active_cell)diff --git a/overbae/services/datasets/files.py b/overbae/services/datasets/files.pyindex 3a812978..dcf39ff1 100644--- a/overbae/services/datasets/files.py+++ b/overbae/services/datasets/files.py@@ -261,10 +261,6 @@ class FileRows:}-def read_file_rows(path: Path, *, filename: str) -> list[dict[str, Any]]:- return list(FileRows(path, filename=filename))--def inspect_upload(upload_id: str, *, size: int, json_rows_field: str | None = None) -> dict[str, Any]:diff --git a/overbae/services/datasets/imports.py b/overbae/services/datasets/imports.pyindex 8960eaf9..be01ab01 100644--- a/overbae/services/datasets/imports.py+++ b/overbae/services/datasets/imports.py@@ -537,9 +537,8 @@ def reconcile():return {"processed": processed}-def _read_parts(run, targets):- source = run.inputs["source"]- split = run.inputs.get("split")+def _landing_progress(run, targets):+ """Each target's landing stage and counters, throttled, while this attempt owns it."""def progress(detail):for target in targets:@@ -557,7 +556,12 @@ def _read_parts(run, targets):target.pk, {"type": "land_progress", "dataset_id": str(target.pk), **detail})- progress = ProgressThrottle(progress)+ return ProgressThrottle(progress)+++def _read_parts(run, targets, progress):+ source = run.inputs["source"]+ split = run.inputs.get("split")extraction = {"project_id": run.dataset.project_id,"ocr_languages": source.get("ocr_languages", []),@@ -699,7 +703,8 @@ def execute(task_id, inputs):})events.publish(target.pk, {"type": "land_started", "dataset_id": str(target.pk)})- parts, state = _read_parts(run, targets)+ progress = _landing_progress(run, targets)+ parts, state = _read_parts(run, targets, progress)prepared = [(target,@@ -709,6 +714,8 @@ def execute(task_id, inputs):path=stage / f"{target.pk}.parquet",state=state,infer_capability=run.inputs.get("infer_capability", True),+ # Each half of a split counts its own rows.+ on_progress=_landing_progress(run, [target]),),)for target, part in partsdiff --git a/overbae/services/datasets/land.py b/overbae/services/datasets/land.pyindex 92d0b8fd..1f561a4a 100644--- a/overbae/services/datasets/land.py+++ b/overbae/services/datasets/land.py@@ -11,6 +11,7 @@ import jsonimport loggingimport shutilimport tempfile+import timeimport uuidfrom collections.abc import Callable, Iterable, Iteratorfrom dataclasses import dataclass, field, replace@@ -29,13 +30,14 @@ from overbae.services.datasets import (contract,documents,files,+ lineage,measure,operations,paths,selection,store,)-from overbae.services.datasets.partition import preserve_lineage, split_rows+from overbae.services.datasets.partition import split_rowslogger = logging.getLogger(__name__)@@ -55,6 +57,8 @@ class Landing:kind: str = "file"spec: dict[str, Any] = field(default_factory=dict)manifest: list[dict] | None = None+ # The lineage keys each row carries from an earlier version, in row order.+ inherited: Iterable[lineage.Keys] | None = Nonedef split(self, *, eval_percent: int, position: str, group_by=(), stratify_by=None, deduplicate=True@@ -83,7 +87,6 @@ def _stamp_source_rows(rows):for offset, row in enumerate(rows):row = dict(row)row[store.SOURCE_ROW] = offset- row["_overmind_provenance"] = preserve_lineage(row)yield row@@ -97,19 +100,28 @@ class PreparedLanding:sources: list[dict]-def prepare(dataset, landing, *, path, state=Dataset.State.IDLE, infer_capability=True):+def prepare(+ dataset, landing, *, path, state=Dataset.State.IDLE, infer_capability=True, on_progress=None+):manifest = landing.manifest- if manifest and not any(column["name"] == "_overmind_provenance" for column in manifest):- manifest = [*manifest, {"name": "_overmind_provenance", "type": "json"}]+ # Traces stream with no count up front; the counter then has no total.+ total = len(landing.rows) if hasattr(landing.rows, "__len__") else None++ def progress(detail):+ if on_progress:+ on_progress(detail)def checked_rows():for index, row in enumerate(_stamp_source_rows(landing.rows)):if index % 1000 == 0:operations.check_cancelled(dataset.id)+ progress({"stage": "writing", "rows_done": index, "rows_total": total})yield rowpath.parent.mkdir(parents=True, exist_ok=True)+ started = time.monotonic()store.write_rows(path, checked_rows(), manifest)+ written = time.monotonic()operations.check_cancelled(dataset.id)sources = landing.spec.get("sources", [])fields = {@@ -135,18 +147,35 @@ def prepare(dataset, landing, *, path, state=Dataset.State.IDLE, infer_capabilitfields["capability_id"] = best["capability_id"]measured.capability_id = best["capability_id"]source = dataset.cells.filter(position=0).first()- return PreparedLanding(+ prepared = PreparedLanding(dataset.pk,source.pk if source else uuid.uuid4(),path,fields,{- **measure.describe_frame(measured, path, report=contract.measure_path(path)),+ **measure.describe_frame(+ measured,+ path,+ inherited=landing.inherited,+ on_progress=lambda done: progress(+ {"stage": "measuring", "rows_done": done, "rows_total": total}+ ),+ ),"input_fingerprint": "","seconds": 0.0,},sources,)+ logger.info(+ "Landing measured",+ extra={+ "dataset": str(dataset.pk),+ "rows": prepared.cell_fields["rows"],+ "write_seconds": round(written - started, 3),+ "measure_seconds": round(time.monotonic() - written, 3),+ },+ )+ return prepared@transaction.atomic@@ -166,6 +195,7 @@ def publish(dataset, prepared, *, user=None):destination = paths.cell_path(locked.pk, prepared.cell_id)destination.parent.mkdir(parents=True, exist_ok=True)prepared.path.replace(destination)+ lineage.keys_path(prepared.path).replace(lineage.keys_path(destination))if source is None:Cell.objects.create(id=prepared.cell_id,@@ -176,13 +206,7 @@ def publish(dataset, prepared, *, user=None):**prepared.cell_fields,)else:- fields = dict(prepared.cell_fields)- if source.preparation_plan:- fields["preparation_plan"] = {- **source.preparation_plan,- "result_fingerprint": fields["fingerprint"],- }- Cell.objects.filter(pk=source.pk).update(**fields)+ Cell.objects.filter(pk=source.pk).update(**prepared.cell_fields)Dataset.objects.filter(pk=locked.pk).update(**prepared.dataset_fields, updated_at=timezone.now())@@ -281,40 +305,28 @@ def _read_one("staged_path": str(path),}return Landing(- EvidenceRows(rows, identity, filename, spool),+ SourceRows(rows, spool),spec={"filename": filename, "sources": [artifact]},)@dataclass-class EvidenceRows:+class SourceRows:+ """A file's rows, and the extraction spool they are read from while the landing runs."""+source: files.FileRows- identity: str- filename: strspool: tempfile.TemporaryDirectory | None = field(default=None, repr=False)def __len__(self):return len(self.source)- def __getitem__(self, index):- for offset, row in enumerate(self):- if offset == index:- return row- raise IndexError(index)-def __iter__(self):- for offset, original in enumerate(self.source):- row = dict(original)- row["_overmind_provenance"] = {- **preserve_lineage(row),- "file": {"sha256": self.identity, "filename": self.filename, "row": offset},- }- yield row+ return iter(self.source)@dataclassclass UploadRows:- sources: list[EvidenceRows]+ sources: list[SourceRows]def __len__(self):return sum(len(source) for source in self.sources)diff --git a/overbae/services/datasets/lifecycle.py b/overbae/services/datasets/lifecycle.pyindex 6111ebb0..06c67b7c 100644--- a/overbae/services/datasets/lifecycle.py+++ b/overbae/services/datasets/lifecycle.py@@ -44,15 +44,23 @@ def set_active(dataset: Dataset, cell: Cell | None) -> Dataset:return dataset-def set_intent(dataset: Dataset, intent: str) -> Dataset:+def set_intent(dataset: Dataset, intent: str, train_format: str = "") -> Dataset:_refuse_while_busy(dataset)- if intent not in (Dataset.Intent.TRAIN, Dataset.Intent.EVAL, Dataset.Intent.EXPLORE):- raise DatasetError("Choose Training, Eval, or Data exploration.", code="intent")+ if intent not in (Dataset.Intent.TRAIN, Dataset.Intent.EVAL):+ raise DatasetError("Choose training or evaluation.", code="intent")+ if train_format not in ("", *Dataset.TrainFormat.values) or (+ train_format and intent != Dataset.Intent.TRAIN+ ):+ raise DatasetError(+ "A training format is sft or decision, for training only.", code="intent"+ )if dataset.frozen_before >= 0:raise DatasetError("A version was used; the intent is fixed.", code="frozen")- if intent != dataset.intent:- _touch(dataset, intent=intent)- measure.capability_only(dataset)+ if (intent, train_format) != (dataset.intent, dataset.train_format):+ changed = intent != dataset.intent+ _touch(dataset, intent=intent, train_format=train_format)+ if changed:+ measure.capability_only(dataset)return datasetdiff --git a/overbae/services/datasets/lineage.py b/overbae/services/datasets/lineage.pynew file mode 100644index 00000000..01b1882b--- /dev/null+++ b/overbae/services/datasets/lineage.py@@ -0,0 +1,147 @@+"""Row lineage keys. Beside each frame, a key file holds every row's ``source_row`` and+its contamination keys: the row's own and those of the rows it came from. Leakage+counts, partitions and validation splits compare these keys across cells."""++from __future__ import annotations++import uuid+from collections.abc import Iterable, Iterator+from pathlib import Path++import pyarrow as pa+import pyarrow.parquet as pq++from overbae.services.datasets import paths, store+from overbae.services.datasets.partition import IDENTITY_COLUMNS, contamination_keys, group_keys++Keys = frozenset[tuple[str, str]]+NONE: Keys = frozenset()+# Kinds and canonical JSON values never hold a raw tab.+_SEP = "\t"+_SCHEMA = pa.schema([("source_row", pa.int64()), ("keys", pa.list_(pa.string()))])+++def keys_path(frame: Path) -> Path:+ return frame.with_suffix(".keys.parquet")+++def own_keys(row: dict) -> Keys:+ return frozenset(contamination_keys(row))+++class Writer:+ """A frame's key file, written as rows arrive: a measured frame holds no key set in+ memory, so a million rows leave nothing for the garbage collector to walk."""++ def __init__(self, frame: Path):+ self.destination = keys_path(frame)+ # Its own name: two readers that derive one legacy key file never share it.+ self.temporary = self.destination.with_suffix(f".{uuid.uuid4().hex}.tmp")+ self.writer = pq.ParquetWriter(self.temporary, _SCHEMA, compression="zstd")+ self.batch = []++ def add(self, source_row: int, keys: Keys) -> None:+ self.batch.append((source_row, sorted(f"{kind}{_SEP}{value}" for kind, value in keys)))+ if len(self.batch) == store.ROW_GROUP_SIZE:+ self.writer.write_table(_table(self.batch))+ self.batch = []++ def close(self) -> None:+ try:+ if self.batch:+ self.writer.write_table(_table(self.batch))+ self.writer.close()+ self.temporary.replace(self.destination)+ except BaseException:+ self.temporary.unlink(missing_ok=True)+ raise++ def abort(self) -> None:+ self.writer.close()+ self.temporary.unlink(missing_ok=True)+++def write(frame: Path, rows: Iterable[tuple[int, Keys]]) -> None:+ """``rows`` in frame order: each row's ``source_row`` and its full key set."""+ writer = Writer(frame)+ try:+ for source_row, keys in rows:+ writer.add(source_row, keys)+ except BaseException:+ writer.abort()+ raise+ writer.close()+++def _table(batch) -> pa.Table:+ return pa.Table.from_arrays(+ [+ pa.array([row for row, _ in batch], pa.int64()),+ pa.array([keys for _, keys in batch], pa.list_(pa.string())),+ ],+ schema=_SCHEMA,+ )+++def load(frame: Path) -> list[tuple[int, Keys]]:+ table = pq.read_table(keys_path(frame))+ return [+ (source_row, frozenset(tuple(key.split(_SEP, 1)) for key in keys))+ for source_row, keys in zip(+ table.column("source_row").to_pylist(), table.column("keys").to_pylist(), strict=True+ )+ ]+++def _derived(cell) -> Path:+ """The cell's frame, with its key file. A frame written before key files carries its+ lineage in ``_overmind_provenance``; its key file is derived from that once."""+ frame = paths.cell_path(cell.dataset_id, cell.id)+ if not keys_path(frame).exists():+ write(+ frame,+ ((row.get(store.SOURCE_ROW), own_keys(row)) for row in store.iter_rows(frame)),+ )+ return frame+++def read(cell) -> list[tuple[int, Keys]]:+ """The cell's rows in frame order."""+ return load(_derived(cell))+++def head(cell, rows: int) -> list[tuple[int, Keys]]:+ """The cell's first ``rows`` rows in frame order, read no further than that."""+ keys = pq.ParquetFile(keys_path(_derived(cell)))+ found = []+ for batch in keys.iter_batches(batch_size=min(max(rows, 1), 65536)):+ for source_row, row in zip(+ batch.column(0).to_pylist(), batch.column(1).to_pylist(), strict=True+ ):+ if len(found) == rows:+ return found+ found.append((source_row, frozenset(tuple(key.split(_SEP, 1)) for key in row)))+ return found+++def stream(cell) -> Iterator[Keys]:+ """The cell's key sets in frame order, one row group at a time."""+ keys = pq.ParquetFile(keys_path(_derived(cell)))+ for batch in keys.iter_batches(columns=["keys"]):+ for row in batch.column(0).to_pylist():+ yield frozenset(tuple(key.split(_SEP, 1)) for key in row)+++def grouped(frame: Path, keyed, group_by) -> Iterator[tuple[int, Keys]]:+ """``keyed`` plus the keys of declared group columns outside the fixed identity set."""+ extra = set(group_by) - set(IDENTITY_COLUMNS)+ if not extra:+ yield from keyed+ return+ columns = sorted({*extra, *(column.split(".", 1)[0] for column in extra)})+ for (source_row, keys), row in zip(keyed, store.iter_rows(frame, columns=columns), strict=True):+ yield source_row, keys | group_keys(row, extra)+++def with_groups(cell, group_by) -> Iterator[tuple[int, Keys]]:+ return grouped(paths.cell_path(cell.dataset_id, cell.id), read(cell), group_by)diff --git a/overbae/services/datasets/list_activity.py b/overbae/services/datasets/list_activity.pyindex b35a9b55..2a26167d 100644--- a/overbae/services/datasets/list_activity.py+++ b/overbae/services/datasets/list_activity.py@@ -1,5 +1,44 @@from overbae.models import Activity, AssistantThread, DatasetPipelineRun, DatasetTransfer+LANDING_STAGES = {"writing": "Writing", "measuring": "Measuring"}+RUN_STAGES = {+ "writing": "Writing",+ "checking_rows": "Checking rows",+ "measuring": "Measuring",+ "publishing": "Publishing",+}+++def run_progress(run) -> dict:+ """A run's stage as the Console names it, with its counter: the sandbox's completed+ batches while a batched step executes, then the rows written and measured so far."""+ result = run.result or {}+ stage = str(result.get("stage") or "")+ steps = result.get("steps") or []+ label = "Previewing" if run.mode == "preview" else "Transforming"+ progress = {"label": label, "completed": None, "total": None, "unit": ""}+ if stage.startswith("step_"):+ index, _, phase = stage.removeprefix("step_").partition("_")+ receipt = steps[int(index) - 1] if index.isdigit() and int(index) <= len(steps) else {}+ if phase in RUN_STAGES:+ progress["label"] = RUN_STAGES[phase]+ elif (receipt.get("runtime") or {}).get("stage") == "waiting_for_sandbox":+ progress["label"] = "Waiting for sandbox"+ batches = receipt.get("batches") or {}+ if phase in ("writing", "measuring") and result.get("rows_done") is not None:+ # The output's size is known only once it is written.+ total = receipt.get("output_rows") if phase == "measuring" else None+ progress |= {"completed": result["rows_done"], "total": total, "unit": "rows"}+ if phase == "executing" and batches.get("total"):+ progress |= {+ "completed": batches["completed"],+ "total": batches["total"],+ "unit": "batches",+ }+ elif stage in RUN_STAGES:+ progress["label"] = RUN_STAGES[stage]+ return progress+def current_work(datasets):ids = [str(dataset.pk) for dataset in datasets]@@ -18,13 +57,24 @@ def current_work(datasets):)for run in runs:work[str(run.dataset_id)] = {- "label": "Previewing" if run.mode == "preview" else "Transforming",+ **run_progress(run),"status": run.state,"actor_kind": actors.get(str(run.pk)),- "completed": None,- "total": None,- "unit": "",}+ for dataset in datasets:+ landing = (dataset.source_spec or {}).get("landing_progress") or {}+ if dataset.state == "landing" and landing.get("stage") in LANDING_STAGES:+ work.setdefault(+ str(dataset.pk),+ {+ "label": LANDING_STAGES[landing["stage"]],+ "status": "running",+ "actor_kind": None,+ "completed": landing.get("rows_done"),+ "total": landing.get("rows_total"),+ "unit": "rows" if landing.get("rows_done") is not None else "",+ },+ )for transfer in DatasetTransfer.objects.filter(specification__dataset__in=ids, state="uploading").order_by("created_at"):diff --git a/overbae/services/datasets/measure.py b/overbae/services/datasets/measure.pyindex c6a0f096..78c5d87b 100644--- a/overbae/services/datasets/measure.py+++ b/overbae/services/datasets/measure.py@@ -1,70 +1,138 @@-"""Everything a cell records about the frame it left."""+"""Everything a cell records about the frame it left, in one pass over its rows."""from __future__ import annotations+import itertools+from collections.abc import Callable, Iterablefrom pathlib import Path-from typing import Any-import pandas as pd+import pyarrow.parquet as pqfrom django.utils import timezone+from modal_shared.decisions import decision_linefrom overbae.models import Cell, Dataset-from overbae.services.datasets import alignment, contract, store-from overbae.services.datasets.profile import profile_records+from overbae.services.datasets import alignment, contract, lineage, store+from overbae.services.datasets.analytics import Analytics+from overbae.services.datasets.examples import missing, native_decision++EXAMPLES = 2+EXAMPLE_CHARS = 200+# Rows between progress reports while a frame is measured.+PROGRESS_ROWS = 10_000def describe_frame(dataset: Dataset,path: Path,*,- df: pd.DataFrame | None = None,- report: dict[str, Any] | None = None,+ inherited: Iterable[lineage.Keys] | None = None,+ on_progress: Callable[[int], None] | None = None,) -> dict:- report = report or (contract.measure(df) if df is not None else contract.measure_path(path))+ """The cell fields for the frame at ``path``. Writes its key file: each row's own+ keys and ``inherited``, the keys of the rows it came from, in frame order.+ ``on_progress`` receives the rows measured so far."""manifest = store.read_manifest(path)+ names = [column["name"] for column in manifest]+ statistics = contract.RowStatistics(set(names))+ analytics = Analytics()+ examples = {name: [] for name in names if not name.startswith("_overmind_")}+ keys = lineage.Writer(path)+ inherited = iter(inherited) if inherited is not None else itertools.repeat(lineage.NONE)+ capability = []+ # Each batch's decision-column problems, when this pass checked that exact value.+ problems = []++ def observed():+ for count, row in enumerate(store.iter_rows(path)):+ if on_progress and count % PROGRESS_ROWS == 0:+ on_progress(count)+ statistics.observe(row)+ decision = native_decision(row)+ problem = _problem(decision)+ analytics.observe(decision, valid=problem is None)+ if problems is not None:+ if "decision" in row and decision is not row["decision"]:+ problems_off()+ else:+ problems.append(problem)+ keys.add(row.get(store.SOURCE_ROW), lineage.own_keys(row) | next(inherited))+ for name, found in examples.items():+ if len(found) < EXAMPLES and not missing(value := row.get(name)):+ text = value if isinstance(value, str) else store.json_dumps(value)+ # PostgreSQL JSON cannot hold NUL.+ text = text.replace("\x00", "\\u0000")+ if text and text[:EXAMPLE_CHARS] not in found:+ found.append(text[:EXAMPLE_CHARS])+ yield row++ def problems_off():+ nonlocal problems+ problems = None++ def frames():+ nonlocal problems+ # One frame per stored row group: the store bounds those by rows and by bytes, so+ # wide rows never build a gigabyte-scale frame.+ rows = observed()+ metadata = pq.read_metadata(path)+ for group in range(metadata.num_row_groups):+ batch = list(itertools.islice(rows, metadata.row_group(group).num_rows))+ if not batch:+ continue+ df = store.frame(batch, manifest)+ if dataset.capability_id is not None:+ capability.append(+ alignment.capability_contract(dataset.capability, df, dataset.intent)+ )+ checked = problems if "decision" in df.columns else None+ problems = []+ yield df, checked++ try:+ report = contract.measure_frames(frames(), names)+ except BaseException:+ keys.abort()+ raise+ keys.close()null_rates = store.null_rates(path)- capability_report = (- capability_path(dataset.capability, path, dataset.intent)- if dataset.capability_id is not None- else {}- )fingerprint = store.file_sha256(path)- statistics = contract.RowStatistics({column["name"] for column in manifest})- profile = profile_records(store.iter_rows(path), observe=statistics.observe)- analytics = {**profile.pop("analytics"), "fingerprint": fingerprint}+ stats = statistics.result()+ if analytics.decisions:+ stats["analytics"] = {**analytics.report(), "fingerprint": fingerprint}return dict(state=Cell.State.OK,error="",rows=store.row_count(path),- columns=[{**c, "null_rate": null_rates.get(c["name"], 0.0)} for c in manifest],+ columns=[+ {+ **c,+ "null_rate": null_rates.get(c["name"], 0.0),+ "examples": examples.get(c["name"], []),+ }+ for c in manifest+ ],fingerprint=fingerprint,intent_report={"train": report["train"], "eval": report["eval"]},- capability_report=capability_report,- stats={- **statistics.result(),- "preparation_profile": profile,- "analytics": analytics,- },+ capability_report=_merged(capability),+ stats=stats,updated_at=timezone.now(),)-def frame(dataset: Dataset, cell: Cell, path: Path, *, df=None, report=None, **fields) -> Cell:- measured = describe_frame(dataset, path, df=df, report=report)- if cell.preparation_plan:- fields["preparation_plan"] = {- **cell.preparation_plan,- "result_fingerprint": measured["fingerprint"],- }- Cell.objects.filter(pk=cell.pk).update(**{**measured, **fields})- cell.refresh_from_db()- return cell+def _problem(decision) -> str | None:+ """Why ``decision`` is not a valid decision line, or None when it is."""+ if not isinstance(decision, dict):+ return "decision must be an object"+ try:+ decision_line({"decision": decision})+ except (ValueError, TypeError, AttributeError) as exc:+ return str(exc)+ return None-def capability_path(capability, path, intent):+def _merged(parts: list[dict]) -> dict:report = {}- for df in store.iter_frames(path):- part = alignment.capability_contract(capability, df, intent)+ for part in parts:if not report:report = partcontinue@@ -79,6 +147,21 @@ def capability_path(capability, path, intent):return report+def frame(+ dataset: Dataset,+ cell: Cell,+ path: Path,+ *,+ inherited: Iterable[lineage.Keys] | None = None,+ **fields,+) -> Cell:+ Cell.objects.filter(pk=cell.pk).update(+ **{**describe_frame(dataset, path, inherited=inherited), **fields}+ )+ cell.refresh_from_db()+ return cell++def capability_only(dataset: Dataset) -> None:"""Re-measure the capability contract on every cell that ran, after thecapability or the intent changed."""@@ -89,7 +172,12 @@ def capability_only(dataset: Dataset) -> None:if not path.exists():continuereport = (- capability_path(dataset.capability, path, dataset.intent)+ _merged(+ [+ alignment.capability_contract(dataset.capability, df, dataset.intent)+ for df in store.iter_frames(path)+ ]+ )if dataset.capability_id is not Noneelse {})diff --git a/overbae/services/datasets/partition.py b/overbae/services/datasets/partition.pyindex 616b9f7e..f6727fa3 100644--- a/overbae/services/datasets/partition.py+++ b/overbae/services/datasets/partition.py@@ -24,6 +24,8 @@ _IDENTITY = {"origin_trace_id","conversation_id","_overmind_provenance",+ # Where a document row came from is lineage, not content: repeated text is a duplicate.+ "_overmind_evidence",}@@ -82,26 +84,35 @@ def present(value) -> bool:)-def contamination_keys(row: dict, group_by=()) -> set[tuple[str, str]]:- keys = {("content", content_key(row))}- for column in {- "trace_id",- "source_trace_id",- "origin_trace_id",- "span_id",- "conversation_id",- "group_id",- "document_id",- "_overmind_document_id",- *group_by,- }:+IDENTITY_COLUMNS = (+ "trace_id",+ "source_trace_id",+ "origin_trace_id",+ "span_id",+ "conversation_id",+ "group_id",+ "document_id",+ "_overmind_document_id",+)+++def group_keys(row: dict, columns) -> set[tuple[str, str]]:+ keys = set()+ for column in set(columns):+ # A plain name the row lacks has no value: field_value would only raise.+ if column not in row and "." not in column:+ continuetry:value = field_value(row, column)except ValueError:continueif present(value):- kind = GROUP_ALIASES.get(column, column)- keys.add((kind, _canonical(value)))+ keys.add((GROUP_ALIASES.get(column, column), _canonical(value)))+ return keys+++def contamination_keys(row: dict, group_by=()) -> set[tuple[str, str]]:+ keys = {("content", content_key(row))} | group_keys(row, {*IDENTITY_COLUMNS, *group_by})for value in input_objects(row):for column in ("packet_id", "onboarding_packet_id", "case_id", "example_id"):if present(value.get(column)) and isinstance(value[column], (str, int)):@@ -120,19 +131,6 @@ def contamination_keys(row: dict, group_by=()) -> set[tuple[str, str]]:return keys-def preserve_lineage(row: dict, *, group_by=(), keys=None) -> dict:- provenance = row.get("_overmind_provenance")- if isinstance(provenance, str):- with suppress(ValueError):- provenance = json.loads(provenance)- keys = contamination_keys(row, group_by) if keys is None else keys- return {- **(provenance if isinstance(provenance, dict) else {}),- "source_content_keys": sorted(value for kind, value in keys if kind == "content"),- "source_group_keys": sorted([kind, value] for kind, value in keys if kind != "content"),- }--def split_rows(rows: list[dict],*,diff --git a/overbae/services/datasets/partition_plans.py b/overbae/services/datasets/partition_plans.pyindex 14175216..fd61a527 100644--- a/overbae/services/datasets/partition_plans.py+++ b/overbae/services/datasets/partition_plans.py@@ -14,9 +14,9 @@ from django.utils import timezonefrom overbae.core.errors import InputValidationErrorfrom overbae.models import DataPartitionMember, DataPartitionPlan, Dataset, Project-from overbae.services.datasets import land, paths, rows, store, use+from overbae.services.datasets import land, lineage, paths, rows, store, usefrom overbae.services.datasets.examples import field_value, native_decision, prepare_native_record-from overbae.services.datasets.partition import GROUP_ALIASES, contamination_keys, preserve_lineage+from overbae.services.datasets.partition import GROUP_ALIASESROLES = ("train", "development", "calibration", "final")@@ -129,11 +129,16 @@ def assign(cell, recipe, destination, *, progress=None):"CREATE TABLE identities (kind TEXT, value TEXT, owner INTEGER, PRIMARY KEY(kind,value))")db.execute("CREATE TABLE observations (row INTEGER PRIMARY KEY, stratum TEXT, forced TEXT)")- for index, record in enumerate(store.iter_rows(rows.frame_path(cell))):+ for index, (record, (_, keys)) in enumerate(+ zip(+ store.iter_rows(rows.frame_path(cell)),+ lineage.with_groups(cell, recipe["group_by"]),+ strict=True,+ )+ ):if progress and index % 10000 == 0:progress("grouping", index, cell.rows)parents.append(index)- keys = contamination_keys(record, recipe["group_by"])if unresolved_groups:group_kinds = {kind for kind, _ in keys if kind != "content"}unresolved_groups = {@@ -304,31 +309,22 @@ def build(plan_id):streams = {role: (work / f"{role}.jsonl").open("w") for role in plan.recipe["fractions"]}+ inherited = {role: [] for role in plan.recipe["fractions"]}try:with (work / "assignments.jsonl").open() as assignments:- for index, (record, line) in enumerate(+ for index, (record, (_, keys), line) in enumerate(zip(store.iter_rows(rows.frame_path(plan.source_cell)),+ lineage.with_groups(plan.source_cell, plan.recipe["group_by"]),assignments,strict=True,)):if index % 10000 == 0:progress("writing", index, plan.source_cell.rows)- assignment = json.loads(line)- preserved = {- **record,- "_overmind_provenance": preserve_lineage(- record, group_by=plan.recipe["group_by"]- ),- }- preserved.setdefault("_overmind_provenance", {})["partition"] = {- "plan": str(plan.pk),- "role": assignment["role"],- "source_cell": str(plan.source_cell_id),- "source_row": assignment["row"],- }- streams[assignment["role"]].write(json.dumps(preserved) + "\n")+ role = json.loads(line)["role"]+ streams[role].write(json.dumps(record) + "\n")+ inherited[role].append(keys)finally:for stream in streams.values():stream.close()@@ -355,6 +351,7 @@ def build(plan_id):dataset,land.Landing(prepared_member_rows(source, role),+ inherited=inherited[role],spec={"partition_plan": str(plan.pk),"role": role,diff --git a/overbae/services/datasets/pipeline_execution.py b/overbae/services/datasets/pipeline_execution.pyindex 1050c6c2..65e98e79 100644--- a/overbae/services/datasets/pipeline_execution.py+++ b/overbae/services/datasets/pipeline_execution.py@@ -1,72 +1,148 @@-from itertools import islice+from pathlib import Path-from overbae.services.datasets import contract, store+from overbae.services.datasets import lineage, store+PARENT_ROWS = "_overmind_parent_rows"+# Identity columns an output row keeps from its parents when every parent agrees.+INHERITED = ("trace_id", "source_trace_id", "conversation_id", store.EVIDENCE)+_INTEGER_JSON = ("'BIGINT'", "'UBIGINT'", "'HUGEINT'")-def execute_rows(run, index, source, directory, step, files, progress, executor):- batch_rows = step.get("batch_rows")- total = store.row_count(source)- if not batch_rows or not total:- yield from executor(run, index, source, directory, step, files, progress)- return- receipt = run.result["steps"][index]- receipt["batches"] = {- "completed": 0,- "total": (total + batch_rows - 1) // batch_rows,- "input_rows": 0,- "output_rows": 0,- }- facts = receipt["batches"]- records = iter(store.iter_rows(source))- manifest = store.read_manifest(source)- for offset in range(0, total, batch_rows):- facts["current"] = facts["completed"] + 1- for field in (- "runtime",- "exit_code",- "provider_execution",- "container",- "submission_started_at",- ):- receipt.pop(field, None)- if not progress():- raise ValueError("Publication was cancelled before the next batch.")- working = directory / f"{index}-batch-{facts['current']}"- working.mkdir(parents=True, exist_ok=True)- incoming = working / "input.parquet"- store.write_rows(incoming, islice(records, batch_rows), manifest)- produced = 0- try:- for row in executor(run, index, incoming, working, step, files, progress):- produced += 1- yield row- finally:- incoming.unlink(missing_ok=True)- facts["completed"] += 1- facts["input_rows"] += min(batch_rows, total - offset)- facts["output_rows"] += produced- if not progress():- raise ValueError("Publication was cancelled after batch execution.")--def check_consumer(path, consumer):- if not consumer:+def contract_violation(path: Path, contract: dict) -> str | None:+ """The first row whose value does not match the declared column type, read from the+ stored columns rather than decoded rows."""+ kinds = {column["name"]: column["type"] for column in store.read_manifest(path)}+ missing = sorted(set(contract) - set(kinds))+ if missing:+ return f"Missing required input columns: {', '.join(missing)}."+ checks = {name: _matches(name, kinds[name], kind) for name, kind in contract.items()}+ checks = {name: check for name, check in checks.items() if check != "true"}+ if not checks:+ return None+ literal = str(path).replace("'", "''")+ # Rows are named by source_row: DuckDB's file_row_number option refuses a frame that+ # has a column of that name.+ row = store.quote_identifier(store.SOURCE_ROW) if store.SOURCE_ROW in kinds else "NULL"+ failures = [+ f"(SELECT CASE WHEN count(*) > 0 THEN coalesce(min({row}), -1) END "+ f"FROM read_parquet('{literal}') "+ f"WHERE NOT coalesce({check}, false))"+ for check in checks.values()+ ]+ with store.connect() as con:+ rows = con.execute("SELECT " + ", ".join(failures)).fetchone()+ found = [(row, name) for row, name in zip(rows, checks, strict=True) if row is not None]+ if not found:return None+ row, name = min(found)+ where = f"Row {row} column" if row >= 0 else "Column"+ return f"{where} {name} does not match {contract[name]}."+++def _matches(name: str, stored: str, declared: str) -> str:+ column = store.quote_identifier(name)+ json_type = f"json_type({column})"+ if declared == "any":+ return "true"+ if declared == "null":+ return f"{column} IS NULL"+ if stored == "json":+ return {+ "string": f"{json_type} = 'VARCHAR'",+ "integer": f"{json_type} IN ({', '.join(_INTEGER_JSON)})",+ "number": f"{json_type} IN ({', '.join(_INTEGER_JSON)}, 'DOUBLE')",+ "boolean": f"{json_type} = 'BOOLEAN'",+ "object": f"{json_type} = 'OBJECT'",+ "array": f"{json_type} = 'ARRAY'",+ }[declared]+ accepted = {+ "string": {"string", "datetime"},+ "integer": {"integer"},+ "number": {"integer", "number"},+ "boolean": {"boolean"},+ }.get(declared, set())+ return f"{column} IS NOT NULL" if stored in accepted else "false"+++class Parents:+ """The rows a step reads: each one's lineage keys, with the declared group keys, and+ the identity columns its outputs inherit."""++ def __init__(self, inputs: list[tuple[Path, list[tuple[int, lineage.Keys]]]], group_by):+ self.keys = {}+ self.values = {}+ self.columns = set()+ for frame, keyed in inputs:+ names = {column["name"] for column in store.read_manifest(frame)}+ columns = sorted(names & {*INHERITED, *group_by})+ self.columns.update(columns)+ values = store.iter_rows(frame, columns=columns) if columns else None+ for source_row, keys in lineage.grouped(frame, keyed, group_by):+ if source_row is None or source_row in self.keys:+ raise ValueError(+ "The source has ambiguous row identities. Select an earlier intact version."+ )+ self.keys[source_row] = keys+ if values is not None:+ self.values[source_row] = next(values)+++def carry(records, parents: Parents, inherited: list[lineage.Keys]):+ """Output rows with their identity resolved against ``parents``. Appends each row's+ inherited lineage keys to ``inherited`` in output order."""+ next_id = max(parents.keys, default=0) + 1+ assigned = set()+ for row in records:+ explicit = row.pop(PARENT_ROWS, None)+ identity = row.get(store.SOURCE_ROW)+ parent_ids = explicit if explicit is not None else [identity]+ if not isinstance(parent_ids, list) or not parent_ids or len(parent_ids) > 10000:+ raise ValueError(+ "A merged row needs _overmind_parent_rows containing its contributing source_row identities."+ )+ keys = set()+ values = []+ # Each ID is checked before deduplication: True would otherwise fold into 1.+ for parent in parent_ids:+ if isinstance(parent, bool) or not isinstance(parent, int) or parent < 0:+ raise ValueError(+ "Preserve source_row, or declare _overmind_parent_rows for a split or merge."+ )+ for parent in dict.fromkeys(parent_ids):+ if parent not in parents.keys:+ raise ValueError("A parent row is not present in the bound source version.")+ keys |= parents.keys[parent]+ values.append(parents.values.get(parent, {}))+ if explicit is not None or identity in assigned:+ identity, next_id = next_id, next_id + 1+ assigned.add(identity)+ row[store.SOURCE_ROW] = identity+ for column in sorted(parents.columns):+ found = [value.get(column) for value in values]+ if all(value == found[0] for value in found):+ if found[0] is not None:+ row[column] = found[0]+ else:+ # Parents that disagree give the merged row no single identity.+ row.pop(column, None)+ row.pop("human_reviewed", None)+ inherited.append(frozenset(keys))+ yield row+++def check_consumer(report: dict, consumer: str) -> dict:+ """Whether the measured output is the format ``consumer`` reads."""native = consumer.startswith("decision")- intent = "train" if consumer.endswith("train") else "eval"- for index, row in enumerate(store.iter_rows(path)):- is_decision = (- "decision" in row- if intent == "train"- else contract.eval_input_type(row.get("input")) == "decision"- )- if native != is_decision:- raise ValueError(f"{consumer}: row {index} has an incompatible format.")- report = contract.measure_path(path)- result = report[intent]+ use = "train" if consumer.endswith("train") else "eval"+ result = report[use]if not result["ok"]:raise ValueError(f"{consumer}: {result['reason']}")- actual = result.get("format") if intent == "train" else result.get("input_type")- if native != (actual == "decision"):+ if use == "train":+ decision = result.get("format") == "decision"+ else:+ types = set(result.get("input_types") or {})+ decision = types == {"decision"} if native else "decision" in types+ if native != decision:+ actual = result.get("format") if use == "train" else result.get("input_type")raise ValueError(f"{consumer}: output has incompatible format {actual!r}.")- return {"consumer": consumer, "rows": report["rows"], "passed": True}+ return {"consumer": consumer, "passed": True}diff --git a/overbae/services/datasets/pipeline_packages.py b/overbae/services/datasets/pipeline_packages.pyindex 15b09f81..eb7603ea 100644--- a/overbae/services/datasets/pipeline_packages.py+++ b/overbae/services/datasets/pipeline_packages.py@@ -96,6 +96,7 @@ def validate_manifest(manifest, files, *, require_runtime=True):"checks","batch_rows","consumer",+ "io",}:raise error("Each step needs a name, entrypoint, column contracts and optional row checks."@@ -117,6 +118,11 @@ def validate_manifest(manifest, files, *, require_runtime=True):raise error("batch_rows must be an integer between 1 and 100000. Only declare it for independent row transformations.")+ if not isinstance(step.get("io", "jsonl"), str) or step.get("io", "jsonl") not in {+ "jsonl",+ "parquet",+ }:+ raise error("io is jsonl (the default) or parquet.")if step.get("consumer") not in {None,"decision_train",diff --git a/overbae/services/datasets/pipeline_runner.py b/overbae/services/datasets/pipeline_runner.pyindex 5aee6e41..a63aa165 100644--- a/overbae/services/datasets/pipeline_runner.py+++ b/overbae/services/datasets/pipeline_runner.py@@ -8,13 +8,14 @@ from contextlib import contextmanagerfrom pathlib import Pathimport httpx+import pyarrow as pa+import pyarrow.parquet as pqimport redisfrom django.conf import settings-from django.core.serializers.json import DjangoJSONEncoderfrom django.utils import timezonefrom overbae.models import DatasetPipelineRunner-from overbae.services.datasets import store, workbench+from overbae.services.datasets import storefrom sandbox import packagesfrom sandbox.protocol import FramingError, HeaderReader, header_bytes@@ -114,7 +115,17 @@ def _refusal(response) -> str:)+BUSY_SECONDS = 2+# How long a step waits for a full sandbox before the run fails as unstarted.+BUSY_LIMIT_SECONDS = QUEUE_SECONDS+# Columns that carry platform lineage, not data the script transforms.+# Platform lineage: scripts never see it, and carry() restores what rows inherit.+HIDDEN = ("_overmind_parent_rows", "_overmind_provenance", store.EVIDENCE)+MAX_LINE = 4 * 1024 * 1024++def execute_script(run, index, source, directory, step, files, progress):+ """Runs the step's entrypoint on ``source`` in the sandbox and yields its output rows."""if not settings.SANDBOX_URL or not settings.SANDBOX_TOKEN:raise RuntimeUnavailableError("The isolated sandbox is not configured.")manifest = run.pipeline.package.manifest@@ -122,6 +133,7 @@ def execute_script(run, index, source, directory, step, files, progress):raise RuntimeUnavailableError("The pinned runtime is unavailable. Save a new package revision with the advertised sandbox runtime identity.")+ io = step.get("io", "jsonl")receipt = run.result["steps"][index]started, checkpoint, stage = time.monotonic(), time.monotonic(), Nonetimings = {}@@ -151,45 +163,70 @@ def execute_script(run, index, source, directory, step, files, progress):payload.write_text(json.dumps(files, ensure_ascii=False))if payload.stat().st_size > packages.MAX_PACKAGE_BYTES:raise RuntimeUnavailableError("The encoded package exceeds 20 MiB.")- incoming, output = root / "input.jsonl", root / "output.jsonl"phase("input_transfer")- with incoming.open("wb") as stream:- for row in store.iter_rows(source):- row.pop("_overmind_parent_rows", None)- stream.write(- (- json.dumps(row, ensure_ascii=False, allow_nan=False, cls=DjangoJSONEncoder)- + "\n"- ).encode()- )- if stream.tell() > packages.MAX_OUTPUT_BYTES:- raise RuntimeUnavailableError(- "The input exceeds 2 GiB. Declare batch_rows for independent rows."- )+ incoming = root / "input.parquet"+ parquet = pq.ParquetFile(source)+ columns = [name for name in parquet.schema_arrow.names if name not in HIDDEN]+ schema = pa.schema(+ [parquet.schema_arrow.field(name) for name in columns],+ metadata=parquet.schema_arrow.metadata,+ )+ # One stored row group at a time: those are bounded by bytes, so the worker never+ # holds more than one.+ with pq.ParquetWriter(incoming, schema, compression="zstd") as writer:+ for group in range(parquet.num_row_groups):+ writer.write_table(parquet.read_row_group(group, columns=columns))+ metadata = pq.read_metadata(incoming)header = {"mode": "package",+ "rows": metadata.num_rows,+ **({"batch_rows": step["batch_rows"]} if step.get("batch_rows") else {}),"input_bytes": incoming.stat().st_size,+ "expanded_bytes": sum(+ metadata.row_group(group).total_byte_size+ for group in range(metadata.num_row_groups)+ ),"package_bytes": payload.stat().st_size,"runtime": manifest["runtime"],"entrypoint": step["entrypoint"],"parameters": run.specification["parameters"],"limits": manifest.get("limits", {}),+ "io": io,}+ output = root / f"output.{io}"+ receipt["submission_started_at"] = timezone.now().isoformat()+ result = _submit(header, (payload, incoming), output, phase, receipt)+ receipt["exit_code"] = result.get("exit_code")+ receipt["runtime"].update(result.get("runtime") or {})+ receipt["runtime"]["execution_seconds"] = result.get("seconds")+ (directory / f"{index}-stdout.log").write_text(result.get("stdout", ""))+ (directory / f"{index}-stderr.log").write_text(result.get("error", ""))+ if not result.get("ok"):+ progress()+ raise RuntimeUnavailableError(result.get("error") or "The sandbox package failed.")+ phase("output_reading")+ if io == "parquet":+ yield from _parquet_rows(output, result.get("segments") or [output.stat().st_size])+ else:+ yield from _jsonl_rows(output)+ phase("completed")- def body():- yield header_bytes(header)- for path in (payload, incoming):- with path.open("rb") as stream:- while chunk := stream.read(64 * 1024):- yield chunk+def _submit(header, parts, output, phase, receipt) -> dict:+ """The sandbox's final reply, with the output written to ``output``. A busy sandbox+ has read nothing yet, so the request is sent again until it has room."""++ def body():+ yield header_bytes(header)+ for path in parts:+ with path.open("rb") as stream:+ while chunk := stream.read(64 * 1024):+ yield chunk++ waited_until = time.monotonic() + BUSY_LIMIT_SECONDS+ while True:reader = HeaderReader()try:- receipt["submission_started_at"] = timezone.now().isoformat()- if not progress():- raise RuntimeUnavailableError(- "Publication was cancelled before sandbox submission."- )with (httpx.stream("POST",@@ -201,40 +238,80 @@ def execute_script(run, index, source, directory, step, files, progress):) as response,output.open("wb") as stream,):+ if response.status_code == 503:+ if time.monotonic() > waited_until:+ raise RuntimeUnavailableError(+ "The sandbox stayed full for 15 minutes; the step did not start."+ )+ phase("waiting_for_sandbox")+ time.sleep(BUSY_SECONDS)+ continueif response.status_code != 200:raise RuntimeUnavailableError(_refusal(response))for chunk in response.iter_bytes():pending = reader.feed(chunk)while reader.header is not None and "progress" in reader.header:+ if "batches" in reader.header["progress"]:+ receipt["batches"] = reader.header["progress"]["batches"]phase("script_execution")reader = HeaderReader()pending = reader.feed(pending)if stream.tell() + len(pending) > packages.MAX_OUTPUT_BYTES:raise RuntimeUnavailableError("The sandbox output exceeds 2 GiB.")stream.write(pending)- result = reader.finish()- receipt["exit_code"] = result.get("exit_code")- receipt["runtime"].update(result.get("runtime") or {})- receipt["runtime"]["execution_seconds"] = result.get("seconds")- (directory / f"{index}-stdout.log").write_text(result.get("stdout", ""))- (directory / f"{index}-stderr.log").write_text(result.get("error", ""))- if not result.get("ok"):- progress()- raise RuntimeUnavailableError(result.get("error") or "The sandbox package failed.")- phase("output_reading")- with output.open("rb") as rows:- for line in iter(lambda: rows.readline(4 * 1024 * 1024 + 1), b""):- if len(line) > 4 * 1024 * 1024:- raise RuntimeUnavailableError("An output row exceeds 4 MiB.")- row = json.loads(line)- if not isinstance(row, dict) or len(row) > 200:- raise RuntimeUnavailableError(- "Every output line must be an object with at most 200 columns."- )- workbench.digest(row)- yield row- phase("completed")+ return reader.finish()except (httpx.TransportError, FramingError) as exc:raise RuntimeUnavailableError("The sandbox result is unconfirmed. No script was replayed.") from exc+++def _checked(row):+ if not isinstance(row, dict) or len(row) > 200:+ raise RuntimeUnavailableError(+ "Every output line must be an object with at most 200 columns."+ )+ return row+++def _jsonl_rows(path):+ with path.open("rb") as rows:+ for line in iter(lambda: rows.readline(MAX_LINE + 1), b""):+ if len(line) > MAX_LINE:+ raise RuntimeUnavailableError("An output row exceeds 4 MiB.")+ try:+ row = store.json_loads_finite(line)+ except ValueError as exc:+ raise RuntimeUnavailableError(+ "Every output line must be one finite JSON object."+ ) from exc+ yield _checked(row)+++def _parquet_rows(path, segments):+ """Rows of each batch's output.parquet, which arrive one after another in ``path``."""+ with path.open("rb") as combined:+ for size in segments:+ part = path.with_suffix(".part.parquet")+ with part.open("wb") as stream:+ remaining = size+ while remaining:+ chunk = combined.read(min(remaining, 1 << 20))+ if not chunk:+ raise RuntimeUnavailableError("The sandbox output ended early.")+ stream.write(chunk)+ remaining -= len(chunk)+ try:+ parquet = pq.ParquetFile(part)+ except (OSError, pa.ArrowException) as exc:+ raise RuntimeUnavailableError(+ "output.parquet is not a readable Parquet file."+ ) from exc+ if len(parquet.schema_arrow.names) > 200:+ raise RuntimeUnavailableError("The output has more than 200 columns.")+ for batch in parquet.iter_batches(batch_size=1024):+ for row in batch.to_pylist():+ if not store.finite(row):+ raise RuntimeUnavailableError("Provide finite values in output.parquet.")+ yield row+ part.unlink()diff --git a/overbae/services/datasets/preparation.py b/overbae/services/datasets/preparation.pyindex 0a9e47be..b50594f8 100644--- a/overbae/services/datasets/preparation.py+++ b/overbae/services/datasets/preparation.py@@ -30,6 +30,7 @@ def describe(dataset, *, cell=None):"dataset": str(current.dataset_id),"dataset_name": current.dataset.name,"intent": current.dataset.intent,+ "train_format": current.dataset.train_format,"role": role,}member = (@@ -49,7 +50,8 @@ def describe(dataset, *, cell=None):edges[(str(parent.pk), identity)] = {"source": str(parent.pk),"target": identity,- "label": member.role,+ "kind": "split",+ "value": member.role,}add_members(member.plan)return@@ -72,7 +74,8 @@ def describe(dataset, *, cell=None):edges[(str(parent.pk), identity)] = {"source": str(parent.pk),"target": identity,- "label": "Derived source",+ "kind": "derived",+ "value": "",}returnif (current.review or {}).get("kind") == "attachment" and current.input_fingerprint:@@ -92,7 +95,8 @@ def describe(dataset, *, cell=None):edges[(str(parent.pk), identity)] = {"source": str(parent.pk),"target": identity,- "label": "Added sources",+ "kind": "attachment",+ "value": "",}returntry:@@ -134,7 +138,8 @@ def describe(dataset, *, cell=None):edges[(str(parent.pk), identity)] = {"source": str(parent.pk),"target": identity,- "label": step.get("condition", ""),+ "kind": "condition" if step.get("condition") else "step",+ "value": step.get("condition", ""),}if current.pk == run.output_id and run.pk not in visited_runs:visited_runs.add(run.pk)diff --git a/overbae/services/datasets/profiler.py b/overbae/services/datasets/profiler.pyindex e22d3ab6..b54a57c4 100644--- a/overbae/services/datasets/profiler.py+++ b/overbae/services/datasets/profiler.py@@ -234,13 +234,6 @@ def dataset_has_closed_form_reference(dataset, *, sample_size: int = _SAMPLE_SIZreturn seen > 0 and hits / seen >= 0.6-def closed_form_reference_for(*, capability=None, dataset=None) -> bool:- # Capability is accepted so card-sync can pass it; a sibling eval set- # must not rewrite this dataset's evaluator.- _ = capability- return dataset_has_closed_form_reference(dataset)--def enqueue_refresh(dataset_id) -> None:# Lazy: overbae.tasks imports this module through the recommendation services.from overbae.tasks import refresh_dataset_context # noqa: PLC0415diff --git a/overbae/services/datasets/review.py b/overbae/services/datasets/review.pyindex 017c63ee..d272d36d 100644--- a/overbae/services/datasets/review.py+++ b/overbae/services/datasets/review.py@@ -1,484 +1,17 @@-from __future__ import annotations--import json-import sqlite3-import tempfile-from collections import Counter-from contextlib import contextmanager, nullcontext-from pathlib import Path+"""The warnings a dataset version's consumers show."""-import pandas as pd+from __future__ import annotations-from overbae.services.datasets import store-from overbae.services.datasets.context import context_fingerprintfrom overbae.services.datasets.contract import public_intent-from overbae.services.datasets.examples import (- decode,- identifier_only,- instructions,- messages,- native_decision,-)-from overbae.services.datasets.partition import contamination_keys, preserve_lineage--PROVENANCE_COLUMN = "_overmind_provenance"-_COVERAGE_COLUMNS = (- "source",- "kind",- "label",- "class",- "intent",- "language",- "behaviour",- "behaviour_key",- "capability_id",- "mode",- "worker_mode",- "task_type",-)---def decision_changed(original, row):- decision = native_decision(original)- if decision is None:- return False- if decision != native_decision(row):- return True- payload = decode(row.get("input"))- if isinstance(payload, dict) and "decision" in payload:- return payload["decision"] != {- key: decision.get(key) for key in ("state", "question", "kind", "options")- } or decode(row.get("expected_output")) != (- {"mean": decision["target_mean"], "values": decision.get("option_values")}- if "target_mean" in decision- else {"probabilities": decision.get("target_probabilities")}- )- return False---def summary(report: dict) -> dict:- result = {key: value for key, value in report.items() if not key.endswith("_examples")}- if result.get("semantic_audit"):- audit = result["semantic_audit"]- result["semantic_audit"] = {- "method": audit["method"],- "contract": audit["contract"],- "definitions": audit["definitions"],- "processed_rows": len(audit.get("results", {})),- "batches": len(audit.get("batches", [])),- }- return result---def preview_examples(frame: pd.DataFrame) -> list:- def clip(value):- if isinstance(value, str):- return value if len(value) <= 2000 else value[:2000] + "…[preview truncated]"- if isinstance(value, list):- return [clip(v) for v in value[:20]]- if isinstance(value, dict):- return {k: clip(v) for k, v in list(value.items())[:30]}- return value-- return clip(json.loads(frame.head(5).to_json(orient="records")))---def distribution(frame: pd.DataFrame) -> dict:- return {- column: dict(Counter(str(value) for value in frame[column].tolist()).most_common(50))- for column in _COVERAGE_COLUMNS- if column in frame.columns- }---def impact(before: pd.DataFrame, after: pd.DataFrame) -> dict:- tracked = (- store.SOURCE_ROW in before- and store.SOURCE_ROW in after- and before[store.SOURCE_ROW].is_unique- and after[store.SOURCE_ROW].is_unique- )- removed = before.iloc[:0]- inputs = before.iloc[:0]- evidence_removed = []- prompt_changes = []- decision_changes = 0- if tracked:- removed = before[~before[store.SOURCE_ROW].isin(after[store.SOURCE_ROW])]- preview_ids = after.head(5)[store.SOURCE_ROW]- preview_ids = preview_ids[preview_ids.isin(before[store.SOURCE_ROW])]- inputs = before.set_index(store.SOURCE_ROW, drop=False).loc[preview_ids]- originals = before.set_index(store.SOURCE_ROW).to_dict(orient="index")- for row in after.to_dict(orient="records"):- original = originals.get(row[store.SOURCE_ROW], {})- decision_changes += decision_changed(original, row)- original_prompt = instructions(original)- if original_prompt and original_prompt != instructions(row):- prompt_changes.append(row[store.SOURCE_ROW])- context = messages(original.get("messages")) or original.get("input")- if context and not identifier_only(context) and identifier_only(row.get("input")):- evidence_removed.append(row[store.SOURCE_ROW])- return {- "rows_before": len(before),- "rows_after": len(after),- "rows_removed": len(removed) if tracked else None,- "rows_added": int((~after[store.SOURCE_ROW].isin(before[store.SOURCE_ROW])).sum())- if tracked- else None,- "identity_preserved": tracked,- "input_evidence_removed": len(evidence_removed),- "input_evidence_removed_examples": evidence_removed[:20],- "instruction_changes": len(prompt_changes),- "instruction_change_examples": prompt_changes[:20],- "decision_changes": decision_changes,- "decision_rows_removed": sum(- native_decision(row) is not None for row in removed.to_dict(orient="records")- ),- "coverage_before": distribution(before),- "coverage_after": distribution(after),- "removed_examples": preview_examples(removed),- "input_examples": preview_examples(inputs),- "output_examples": preview_examples(after),- }---def distribution_file(path: Path) -> dict:- columns = {c["name"] for c in store.read_manifest(path)}- result = {}- with store.connect(t=path) as con:- for column in _COVERAGE_COLUMNS:- if column in columns:- result[column] = dict(- con.execute(- f"SELECT coalesce(CAST(\"{column}\" AS VARCHAR), 'None'), count(*) "- f"FROM t GROUP BY 1 ORDER BY 2 DESC, 1 LIMIT 50"- ).fetchall()- )- return result---def progress_rows(records, progress, phase, total):- completed = 0- for completed, row in enumerate(records, 1):- yield row- if progress and completed % 1000 == 0:- progress(phase, completed, total)- if progress:- progress(phase, completed, total)--@contextmanager-def indexed_rows(path, *, parent_paths=None, progress=None, scratch=None):- with tempfile.TemporaryDirectory(prefix="review_", dir=scratch) as directory:- con = sqlite3.connect(Path(directory) / "rows.sqlite")- con.execute("PRAGMA cache_size=-16384")- con.execute(- "CREATE TABLE original (identity TEXT PRIMARY KEY, body TEXT, cell TEXT, fingerprint TEXT)"- )- con.execute("CREATE TABLE selected (identity TEXT PRIMARY KEY)")- tracked = True- try:- for parent in parent_paths or [path]:- fingerprint = store.file_sha256(parent)- for row in progress_rows(- store.iter_rows(parent), progress, "indexing_source", store.row_count(parent)- ):- identity = row.get(store.SOURCE_ROW)- if identity is None:- tracked = False- count = con.execute(- "INSERT OR IGNORE INTO original(identity, body, cell, fingerprint) VALUES (?, ?, ?, ?)",- (json.dumps(identity), store.json_dumps(row), parent.stem, fingerprint),- ).rowcount- tracked = tracked and bool(count)- con.commit()- yield con, tracked- finally:- con.close()--def impact_files(before: Path, after: Path, *, index=None, progress=None) -> dict:- columns = {c["name"] for c in store.read_manifest(after)}- evidence = prompts = added = decision_changes = decision_removed = 0- evidence_examples, prompt_examples, inputs = [], [], []- output = store.head(after, 5)- with indexed_rows(before) if index is None else nullcontext(index) as (con, tracked):- tracked = tracked and store.SOURCE_ROW in columns- for i, row in enumerate(- progress_rows(- store.iter_rows(after), progress, "comparing_rows", store.row_count(after)- )- ):- identity = json.dumps(row.get(store.SOURCE_ROW))- unique = con.execute("INSERT OR IGNORE INTO selected VALUES (?)", (identity,)).rowcount- tracked = tracked and bool(unique) and row.get(store.SOURCE_ROW) is not None- found = con.execute(- "SELECT body FROM original WHERE identity=?", (identity,)- ).fetchone()- original = json.loads(found[0]) if found else {}- decision_changes += decision_changed(original, row)- if found:- if i < 5:- inputs.append(original)- else:- added += 1- prompt = instructions(original)- if prompt and prompt != instructions(row):- prompts += 1- if len(prompt_examples) < 20:- prompt_examples.append(row.get(store.SOURCE_ROW))- context = messages(original.get("messages")) or original.get("input")- if context and not identifier_only(context) and identifier_only(row.get("input")):- evidence += 1- if len(evidence_examples) < 20:- evidence_examples.append(row.get(store.SOURCE_ROW))- removed = con.execute(- "SELECT count(*) FROM original WHERE NOT EXISTS (SELECT 1 FROM selected WHERE selected.identity=original.identity)"- ).fetchone()[0]- for (body,) in con.execute(- "SELECT body FROM original WHERE NOT EXISTS (SELECT 1 FROM selected WHERE selected.identity=original.identity)"- ):- decision_removed += native_decision(json.loads(body)) is not None- removed_examples = [- json.loads(r[0])- for r in con.execute(- "SELECT body FROM original WHERE NOT EXISTS (SELECT 1 FROM selected WHERE selected.identity=original.identity) LIMIT 5"- )- ]- return {- "rows_before": store.row_count(before),- "rows_after": store.row_count(after),- "rows_removed": removed if tracked else None,- "rows_added": added if tracked else None,- "identity_preserved": tracked,- "input_evidence_removed": evidence if tracked else 0,- "input_evidence_removed_examples": evidence_examples if tracked else [],- "instruction_changes": prompts if tracked else 0,- "decision_changes": decision_changes if tracked else 0,- "decision_rows_removed": decision_removed if tracked else 0,- "instruction_change_examples": prompt_examples if tracked else [],- "coverage_before": distribution_file(before),- "coverage_after": distribution_file(after),- "removed_examples": preview_examples(pd.DataFrame(removed_examples)) if tracked else [],- "input_examples": preview_examples(pd.DataFrame(inputs)) if tracked else [],- "output_examples": preview_examples(pd.DataFrame(output)),- }---def preserve_file_provenance(- before: Path,- after: Path,- destination: Path,- *,- group_by=(),- parent_paths=None,- index=None,- strip_review=False,- progress=None,-):- columns = {c["name"] for c in store.read_manifest(before)}- inherited = {- "trace_id",- "source_trace_id",- "conversation_id",- "human_reviewed",- *group_by,- } & columns- if store.SOURCE_ROW not in columns:- raise ValueError("The source has no record identities.")- with (- indexed_rows(before, parent_paths=parent_paths) if index is None else nullcontext(index)- ) as (con, tracked):- if not tracked:- raise ValueError(- "The source has ambiguous row identities. Select an earlier intact version."- )- largest = (- con.execute("SELECT max(CAST(identity AS INTEGER)) FROM original").fetchone()[0] or 0- )- con.execute("CREATE TABLE assigned (identity INTEGER PRIMARY KEY)")-- def records():- next_id = largest + 1- for row in store.iter_rows(after):- explicit = row.pop("_overmind_parent_rows", None)- identity = row.get(store.SOURCE_ROW)- parent_ids = explicit if explicit is not None else [identity]- if not isinstance(parent_ids, list) or not parent_ids or len(parent_ids) > 10000:- raise ValueError(- "A merged row needs _overmind_parent_rows containing its contributing source_row identities."- )- originals = []- parents = []- for parent in dict.fromkeys(parent_ids):- if isinstance(parent, bool) or not isinstance(parent, int) or parent < 0:- raise ValueError(- "Preserve source_row, or declare _overmind_parent_rows for a split or merge."- )- found = con.execute(- "SELECT body, cell, fingerprint FROM original WHERE identity=?",- (json.dumps(parent),),- ).fetchone()- if found is None:- raise ValueError("A parent row is not present in the bound source version.")- originals.append(json.loads(found[0]))- parents.append({"cell": found[1], "fingerprint": found[2], "row": parent})- if (- explicit is not None- or con.execute(- "SELECT 1 FROM assigned WHERE identity=?", (identity,)- ).fetchone()- ):- identity, next_id = next_id, next_id + 1- con.execute("INSERT INTO assigned VALUES (?)", (identity,))- row[store.SOURCE_ROW] = identity- if (- (parent_paths is None or len(parent_paths) == 1)- and explicit is None- and len(originals) == 1- and row == originals[0]- ):- yield row- continue- keys = set().union(- *(contamination_keys(original, group_by) for original in originals)- )- provenance = (- preserve_lineage(originals[0], group_by=group_by, keys=keys)- if len(originals) == 1- else {"kind": "transform"}- )- row[PROVENANCE_COLUMN] = {- **provenance,- "parents": parents,- "source_content_keys": sorted(v for k, v in keys if k == "content"),- "source_group_keys": sorted([k, v] for k, v in keys if k != "content"),- }- for column in inherited:- values = [original.get(column) for original in originals]- if values[0] is not None and all(value == values[0] for value in values):- row[column] = values[0]- yield row-- checked = progress_rows(records(), progress, "preserving_rows", store.row_count(after))- store.write_rows(- destination,- (- {key: value for key, value in row.items() if key != "human_reviewed"}- for row in checked- )- if strip_review- else checked,- )---def readiness(dataset, cell, *, context: str | None = None) -> dict:- valid, reason = cell.fits(public_intent(dataset.intent))- report = cell.quality_report or {}- plan = cell.preparation_plan or {}- reviewed = bool(- report.get("fingerprint") == cell.fingerprint- and report.get("context_fingerprint")- == (context or context_fingerprint(dataset.capability))- and report.get("intent") == public_intent(dataset.intent)- and report.get("checks")- and report.get("plan_id") == plan.get("id")- )- blockers = (- quality_blockers(cell, plan=plan) if reviewed else ["No current workshop quality review."]- )- blockers.extend(+def warnings(dataset, cell, *, capability=None) -> list[str]:+ findings = list((cell.intent_report.get(public_intent(dataset.intent)) or {}).get("warnings", []))contract = cell.capability_report or {}if contract and not contract.get("ok"):- blockers.append(contract.get("reason") or "Rows do not match the capability.")- return {- "format_valid": valid,- "format_reason": reason,- "quality_reviewed": reviewed,- "quality_passed": reviewed and not blockers,- "quality_reason": "; ".join(blockers),- "training_configuration": "not_checked",- "assessment": assessment(plan, report if reviewed else {}, valid),- }---def assessment(plan, report, valid):- measured = {check["name"]: check for check in report.get("checks", [])}- result = {}- for category in ("technical", "preservation", "coverage", "semantic"):- checks = [- check- for check in plan.get("specification", {}).get("checks", [])- if check["category"] == category- ]- states = [- measured.get(check["name"], {}).get("result", "unknown")- if check["method"] != "unmeasured"- else "unknown"- for check in checks- ]- if category == "technical":- states.append("pass" if valid else "fail")- result[category] = (- "fail"- if "fail" in states- else "pass"- if states and all(s == "pass" for s in states)- else "partial"- if "pass" in states- else "unknown"- )- return result---def quality_blockers(cell, *, plan=None) -> list[str]:- checks = (cell.quality_report or {}).get("checks") or []- indexed = {check["name"]: check for check in checks}- blockers = []- if (cell.quality_report or {}).get("audit", {}).get("method") not in {- "row_results",- "semantic_decisions",- }:- blockers.append("Quality claims have no executed row-level audit.")- required = {- check["name"]: check["question"]- for check in (plan or {}).get("specification", {}).get("checks", [])- }- if not required:- blockers.append("No preparation plan defines the scope of this review.")- for name in required:- label = name.replace("_", " ").capitalize()- check = indexed.get(name)- if check is None:- blockers.append(f"{label}: not reviewed")- elif check.get("result") != "pass":- blockers.append(f"{label}: {check.get('result', 'unknown')}")- elif check.get("rows_checked") != cell.rows:- blockers.append(f"{label}: not reviewed across all {cell.rows} rows")- blockers.extend(- f"{check['name']}: {check['result']}"- for check in checks- if check["name"] not in required and check["result"] != "pass"- )- return blockers---def warnings(dataset, cell, *, capability=None) -> list[str]:- status = readiness(dataset, cell)- findings = [status["quality_reason"]] if status["quality_reason"] else []+ findings.append(contract.get("reason") or "Rows do not match the capability.")if capability is not None and dataset.capability_id != capability.id:findings.append(f"This dataset has not been reviewed for {capability.name}.")return findings---def group_columns(dataset, cell):- return sorted(- set(dataset.source_spec.get("split", {}).get("group_by", []))- | {- column- for family in cell.preparation_plan.get("specification", {}).get("families", [])- for column in family.get("group_columns", [])- }- )diff --git a/overbae/services/datasets/roles.py b/overbae/services/datasets/roles.pyindex adf18467..840ac144 100644--- a/overbae/services/datasets/roles.py+++ b/overbae/services/datasets/roles.py@@ -1,8 +1,8 @@from django.db.models import Q-from overbae.models import Cell, DataPartitionMember, EvalRun, FinetuningJob, NativeEvaluationPlan+from overbae.models import DataPartitionMember, EvalRun, FinetuningJob, NativeEvaluationPlan-ROLE_NAMES = ("training", "development", "calibration", "evaluation", "source")+ROLE_NAMES = ("training", "development", "calibration", "evaluation")PARTITION_ROLES = {"train": "training","development": "development",@@ -53,17 +53,6 @@ def dataset_roles(datasets):for identity, role in zip(row, fields.values(), strict=True):add(identity, role)- sources = set()- transformed = set()- for identity, position in (- Cell.objects.filter(dataset_id__in=ids, state="ok")- .exclude(fingerprint="")- .values_list("dataset_id", "position")- ):- (sources if position == 0 else transformed).add(identity)- for identity in sources - transformed:- if not roles[identity]:- add(identity, "source")return {str(identity): [role for role in ROLE_NAMES if role in assigned]for identity, assigned in roles.items()diff --git a/overbae/services/datasets/rows.py b/overbae/services/datasets/rows.pyindex 95a5f34c..1dfac2d1 100644--- a/overbae/services/datasets/rows.py+++ b/overbae/services/datasets/rows.py@@ -12,9 +12,8 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any-from overbae.services.datasets import paths, store+from overbae.services.datasets import lineage, paths, storefrom overbae.services.datasets.examples import missing, normalize_record-from overbae.services.datasets.partition import contamination_keysclass RowStoreError(RuntimeError):@@ -126,18 +125,18 @@ def contamination(train, evaluation) -> dict:group_by = set(train.dataset.source_spec.get("split", {}).get("group_by", []))group_by.update(evaluation.dataset.source_spec.get("split", {}).get("group_by", []))keys = set()- for record in store.iter_rows(frame_path(evaluation)):- keys.update(contamination_keys(record, group_by))+ for _, row_keys in lineage.with_groups(evaluation, group_by):+ keys.update(row_keys)count = 0examples = []- for index, record in enumerate(store.iter_rows(frame_path(train))):- shared = contamination_keys(record, group_by) & keys+ for index, (source_row, row_keys) in enumerate(lineage.with_groups(train, group_by)):+ shared = row_keys & keysif shared:count += 1if len(examples) < 20:examples.append({- "row": record.get(store.SOURCE_ROW, index),+ "row": index if source_row is None else source_row,"matches": sorted({key[0] for key in shared}),})@@ -165,15 +164,9 @@ def sample_rows(dataset: Any, limit: int) -> list[DatasetRow]:return [row_from_record(i, rec) for i, rec in enumerate(sample_records(dataset, limit))]-def sample_expected_outputs(dataset: Any, limit: int) -> list[Any]:- out = [rec.get("expected_output") for rec in sample_records(dataset, limit * 2)]- return [v for v in out if v not in (None, "")][:limit]--EMPTY_STATS = {"num_examples": 0,"has_tool_calling": False,- "has_multi_turn_tool_calls": False,"max_token_length": 0,"avg_input_chars": 0,"avg_output_chars": 0,diff --git a/overbae/services/datasets/statistics.py b/overbae/services/datasets/statistics.pyindex d5656833..167b2c7f 100644--- a/overbae/services/datasets/statistics.py+++ b/overbae/services/datasets/statistics.py@@ -18,7 +18,8 @@ class StatisticsUnavailableError(ValueError):pass-def profile(path, manifest, *, fingerprint="", top=5):+def profile(path, manifest, *, fingerprint="", top=5, duplicates=False):+ """The frame's column statistics from a fixed sample, and its exact duplicate rows."""path = Path(path).resolve()stat = path.stat()identity = hashlib.sha256(@@ -30,6 +31,7 @@ def profile(path, manifest, *, fingerprint="", top=5):"mtime": stat.st_mtime_ns,"inode": stat.st_ino,"top": top,+ "duplicates": duplicates,"sample": SAMPLE_ROWS,"implementation": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),"method": "deterministic_reservoir",@@ -66,6 +68,7 @@ def profile(path, manifest, *, fingerprint="", top=5):str(path),json.dumps(manifest),str(top),+ "duplicates" if duplicates else "",],capture_output=True,text=True,@@ -92,7 +95,7 @@ def profile(path, manifest, *, fingerprint="", top=5):fcntl.flock(lock, fcntl.LOCK_UN)-def compute(path, manifest, top):+def compute(path, manifest, top, duplicates=False):with duckdb.connect(config={"memory_limit": "256MB", "threads": 1}) as con:literal = str(path).replace("'", "''")con.execute(f"CREATE VIEW source AS SELECT * FROM read_parquet('{literal}')")@@ -101,6 +104,19 @@ def compute(path, manifest, top):f"CREATE TEMP TABLE sample AS SELECT * FROM source USING SAMPLE reservoir({SAMPLE_ROWS} ROWS) REPEATABLE (73491)")n = con.execute("SELECT count(*) FROM sample").fetchone()[0]+ compared = [+ '"' + spec["name"].replace('"', '""') + '"'+ for spec in manifest+ if spec["name"] != "source_row" and not spec["name"].startswith("_overmind_")+ ]+ # Exact over every row, and only on request: the column card does not read it.+ duplicate_rows = (+ con.execute(+ f"SELECT count(*) - count(DISTINCT hash({', '.join(compared)})) FROM source"+ ).fetchone()[0]+ if duplicates and compared+ else None+ )result = []for spec in manifest:name, kind = spec["name"], spec["type"]@@ -136,8 +152,17 @@ def compute(path, manifest, top):).fetchall()entry["top"] = [{"value": v, "count": int(c)} for v, c in values]result.append(entry)- return result+ return {"columns": result, "duplicate_rows": duplicate_rows, "rows": int(total)}if __name__ == "__main__":- print(json.dumps(compute(Path(sys.argv[1]), json.loads(sys.argv[2]), int(sys.argv[3]))))+ print(+ json.dumps(+ compute(+ Path(sys.argv[1]),+ json.loads(sys.argv[2]),+ int(sys.argv[3]),+ duplicates=sys.argv[4] == "duplicates",+ )+ )+ )diff --git a/overbae/services/datasets/store.py b/overbae/services/datasets/store.pyindex fbce72e7..58a86e54 100644--- a/overbae/services/datasets/store.py+++ b/overbae/services/datasets/store.py@@ -10,9 +10,11 @@ from __future__ import annotationsimport datetime as dtimport hashlib+import itertoolsimport jsonimport mathimport pickle+import reimport tempfileimport threadingfrom collections.abc import Iterable@@ -21,6 +23,7 @@ from pathlib import Pathfrom typing import Anyimport duckdb+import orjsonimport pandas as pdimport pyarrow as paimport pyarrow.parquet as pq@@ -29,6 +32,8 @@ from django.conf import settingsfrom overbae.services.datasets.statistics import StatisticsUnavailableError, profileSOURCE_ROW = "source_row"+# Where a document row came from (file, page, element) and how its text was read.+EVIDENCE = "_overmind_evidence"ROW_GROUP_SIZE = 10_000ROW_GROUP_BYTES = 16 * 1024 * 1024_MANIFEST_KEY = b"overmind.columns"@@ -78,14 +83,66 @@ def json_dumps(value: Any) -> str:return json.dumps(value, ensure_ascii=False, default=str, sort_keys=True)+_LONG_DIGITS = re.compile(r"\d{19}")+++def json_loads(text: str) -> Any:+ """orjson for speed. The standard library decodes what orjson refuses (NaN, Infinity)+ and any text with a 19-digit run, since orjson turns integers beyond 64 bits into floats."""+ if _LONG_DIGITS.search(text):+ return json.loads(text)+ try:+ return orjson.loads(text)+ except orjson.JSONDecodeError:+ return json.loads(text)+++def json_loads_finite(text: str | bytes) -> Any:+ """``json_loads`` that refuses NaN and Infinity."""+ if isinstance(text, bytes):+ text = text.decode()+ if _LONG_DIGITS.search(text):+ return json.loads(text, parse_constant=_refuse_constant, parse_float=_finite_float)+ return orjson.loads(text)+++def _refuse_constant(name):+ raise ValueError(f"{name} is not a finite JSON value.")+++def _finite_float(text):+ value = float(text)+ if not math.isfinite(value):+ raise ValueError(f"{text} is not a finite JSON value.")+ return value+++def finite(value: Any) -> bool:+ if isinstance(value, float):+ return math.isfinite(value)+ if isinstance(value, dict):+ return all(finite(item) for item in value.values())+ if isinstance(value, (list, tuple)):+ return all(finite(item) for item in value)+ return True+++class _Json(str):+ """A nested value already encoded by ``json_dumps`` while a row was buffered."""++def _coerce(value: Any, kind: str) -> Any:if _is_missing(value):return Noneif kind == "json":+ if isinstance(value, _Json):+ return str(value)if hasattr(value, "tolist"):value = value.tolist()return json_dumps(value)if kind == "string":+ if isinstance(value, _Json):+ return str(value)if isinstance(value, (dict, list)):return json_dumps(value)if isinstance(value, bytes):@@ -118,13 +175,6 @@ def _coerce(value: Any, kind: str) -> Any:return value-def _infer_kind(values: list[Any]) -> str:- builder = ManifestBuilder()- for value in values:- builder.add({"value": value})- return builder.manifest()[0]["type"] if values else "string"--class ManifestBuilder:def __init__(self):self.kinds = {}@@ -136,7 +186,7 @@ class ManifestBuilder:kinds = self.kinds.setdefault(name, set())if _is_missing(value):continue- if isinstance(value, (dict, list, tuple)):+ if isinstance(value, (dict, list, tuple, _Json)):kinds.add("json")elif isinstance(value, bool):kinds.add("boolean")@@ -167,25 +217,6 @@ class ManifestBuilder:return result-def manifest_from_frame(df: pd.DataFrame) -> list[dict[str, str]]:- out: list[dict[str, str]] = []- for name in df.columns:- series = df[name]- if pd.api.types.is_bool_dtype(series):- kind = "boolean"- elif pd.api.types.is_integer_dtype(series):- maximum = series.max()- kind = "json" if pd.notna(maximum) and maximum >= 2**63 else "integer"- elif pd.api.types.is_float_dtype(series):- kind = "number"- elif pd.api.types.is_datetime64_any_dtype(series):- kind = "datetime"- else:- kind = _infer_kind(series.tolist())- out.append({"name": str(name), "type": kind})- return out--def _table_from_columns(columns: dict[str, list[Any]], manifest: list[dict[str, str]]) -> pa.Table:arrays = []fields = []@@ -198,18 +229,21 @@ def _table_from_columns(columns: dict[str, list[Any]], manifest: list[dict[str,return pa.Table.from_arrays(arrays, schema=schema)-def _row_batches(rows, batch_size):- if batch_size < 1:- raise ValueError("batch_size must be positive.")+def _row_batches(rows):+ """Row groups of at most ROW_GROUP_SIZE rows or about ROW_GROUP_BYTES. Nested values+ are encoded once here, which is also how their size is known."""batch, size = [], 0for row in rows:- record = dict(row)- encoded_size = len(pickle.dumps(record, protocol=pickle.HIGHEST_PROTOCOL))- if batch and (len(batch) >= batch_size or size + encoded_size > ROW_GROUP_BYTES):+ record = {}+ for name, value in row.items():+ if isinstance(value, (dict, list, tuple)):+ value = _Json(json_dumps(value))+ record[str(name)] = value+ size += len(value) if isinstance(value, (str, bytes)) else 8+ batch.append(record)+ if len(batch) >= ROW_GROUP_SIZE or size >= ROW_GROUP_BYTES:yield batchbatch, size = [], 0- batch.append(record)- size += encoded_sizeif batch:yield batch@@ -217,13 +251,14 @@ def _row_batches(rows, batch_size):def write_rows(path: Path, rows: Iterable[dict[str, Any]], manifest: list[dict[str, str]] | None = None) -> list[dict[str, str]]:+ """Writes rows under ``manifest``, or under the manifest inferred from every row: then+ row groups wait in a private spool until the last row fixes each column's kind."""path.parent.mkdir(parents=True, exist_ok=True)temporary = path.with_suffix(".parquet.tmp")- # Infer over every row before writing Arrow's fixed schema, without retaining the corpus.with tempfile.TemporaryFile() if manifest is None else nullcontext() as spool:if manifest is None:builder = ManifestBuilder()- for batch in _row_batches(rows, ROW_GROUP_SIZE):+ for batch in _row_batches(rows):for record in batch:builder.add(record)pickle.dump(batch, spool, protocol=pickle.HIGHEST_PROTOCOL)@@ -239,7 +274,7 @@ def write_rows(pending = batches()else:- pending = _row_batches(rows, ROW_GROUP_SIZE)+ pending = _row_batches(rows)schema = _table_from_columns({c["name"]: [] for c in manifest}, manifest).schematry:with pq.ParquetWriter(temporary, schema, compression="zstd") as writer:@@ -253,20 +288,6 @@ def write_rows(return manifest-def write_frame(path: Path, df: pd.DataFrame) -> list[dict[str, str]]:- manifest = manifest_from_frame(df)- columns = {spec["name"]: df[spec["name"]].tolist() for spec in manifest}- _write_table(path, _table_from_columns(columns, manifest))- return manifest---def _write_table(path: Path, table: pa.Table) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- tmp = path.with_suffix(".parquet.tmp")- pq.write_table(table, tmp, row_group_size=ROW_GROUP_SIZE, compression="zstd")- tmp.replace(path)--def file_sha256(path: Path) -> str:digest = hashlib.sha256()with open(path, "rb") as fh:@@ -312,7 +333,7 @@ def _decode(value: Any, kind: str) -> Any:return Noneif kind == "json":try:- return json.loads(value)+ return json_loads(value)except (TypeError, ValueError):return valueif kind == "datetime":@@ -337,27 +358,46 @@ def read_frame(path: Path) -> pd.DataFrame:return df-def iter_rows(path: Path, batch_size: int = 256):- """Decoded dict rows, streaming by row group."""- manifest = read_manifest(path)- kinds = {spec["name"]: spec["type"] for spec in manifest}+def iter_rows(path: Path, batch_size: int = 1024, columns: list[str] | None = None):+ """Decoded dict rows, streaming by row group; only ``columns`` when given."""+ kinds = {spec["name"]: spec["type"] for spec in read_manifest(path)}pf = pq.ParquetFile(path)- for batch in pf.iter_batches(batch_size=batch_size):- for record in batch.to_pylist():- yield {k: _decode(v, kinds.get(k, "string")) for k, v in record.items()}+ if columns is not None:+ columns = [name for name in columns if name in kinds]+ for batch in pf.iter_batches(batch_size=batch_size, columns=columns):+ names = batch.schema.names+ if not names:+ yield from ({} for _ in range(batch.num_rows))+ continue+ decoded = [+ [_decode(v, kinds.get(name, "string")) for v in batch.column(name).to_pylist()]+ for name in names+ ]+ for values in zip(*decoded, strict=True):+ yield dict(zip(names, values, strict=True))-def iter_frames(path: Path, batch_size: int = ROW_GROUP_SIZE):+def frame(rows, manifest) -> pd.DataFrame:+ """Decoded rows as a DataFrame that keeps JSON values and nullable integers as objects."""+ columns = {}+ for spec in manifest:+ values = [row.get(spec["name"]) for row in rows]+ preserve_scalars = spec["type"] == "json" or (+ spec["type"] == "integer" and any(value is None for value in values)+ )+ columns[spec["name"]] = pd.Series(values, dtype=object if preserve_scalars else None)+ return pd.DataFrame(columns)+++def iter_frames(path: Path):+ """One frame per stored row group, which the writer bounds by rows and by bytes."""manifest = read_manifest(path)- for batch in _row_batches(iter_rows(path), batch_size):- columns = {}- for spec in manifest:- values = [row.get(spec["name"]) for row in batch]- preserve_scalars = spec["type"] == "json" or (- spec["type"] == "integer" and any(value is None for value in values)- )- columns[spec["name"]] = pd.Series(values, dtype=object if preserve_scalars else None)- yield pd.DataFrame(columns)+ rows = iter_rows(path)+ metadata = pq.read_metadata(path)+ for group in range(metadata.num_row_groups):+ batch = list(itertools.islice(rows, metadata.row_group(group).num_rows))+ if batch:+ yield frame(batch, manifest)def read_rows(path: Path, indices: list[int]) -> list[dict[str, Any]]:@@ -540,13 +580,21 @@ def page(return {"rows": rows, "total": int(total), "columns": manifest}-def column_stats(path: Path, *, top: int = 5, fingerprint: str = "") -> list[dict[str, Any]]:+def frame_profile(+ path: Path, *, top: int = 5, fingerprint: str = "", duplicates: bool = False+) -> dict[str, Any]:try:- return profile(path, read_manifest(path), fingerprint=fingerprint, top=top)- except StatisticsUnavailableError as exc:+ return profile(+ path, read_manifest(path), fingerprint=fingerprint, top=top, duplicates=duplicates+ )+ except (StatisticsUnavailableError, OSError) as exc:raise StoreError(str(exc)) from exc+def column_stats(path: Path, *, top: int = 5, fingerprint: str = "") -> list[dict[str, Any]]:+ return frame_profile(path, top=top, fingerprint=fingerprint)["columns"]++def connect_sandboxed(**tables: Path) -> duckdb.DuckDBPyConnection:con = duckdb.connect(config={diff --git a/overbae/services/datasets/transfers.py b/overbae/services/datasets/transfers.pyindex 18149e67..18cc9e4f 100644--- a/overbae/services/datasets/transfers.py+++ b/overbae/services/datasets/transfers.py@@ -214,7 +214,12 @@ def complete(transfer):transfer.user,name + (" train" if spec.get("split") else ""),source,- "train" if spec.get("split") else spec.get("intent"),+ # A reservation made before intent lost "explore" lands with no intent.+ "train"+ if spec.get("split")+ else spec.get("intent")+ if spec.get("intent") in ("train", "eval")+ else None,capability,spec.get("brief", ""),)diff --git a/overbae/services/datasets/workbench.py b/overbae/services/datasets/workbench.pyindex 66584c95..339d701d 100644--- a/overbae/services/datasets/workbench.py+++ b/overbae/services/datasets/workbench.py@@ -26,6 +26,7 @@ from overbae.services import activity, operational_progressfrom overbae.services.datasets import (events,lifecycle,+ lineage,measure,operations,paths,@@ -33,13 +34,17 @@ from overbae.services.datasets import (pipeline_graph,pipeline_packages,preparation,- review,rows,store,)from overbae.services.datasets.lifecycle import DatasetError+from overbae.services.datasets.pipeline_execution import Parentslogger = logging.getLogger(__name__)+# Seconds between row counts while a step's output is written and measured.+ROW_REPORT_SECONDS = 2.0+SCRATCH_BYTES = 8 * 1024**3+SCRATCH_FREE_BYTES = 512 * 1024**2def digest(value):@@ -357,13 +362,30 @@ def execute(run_id, *, script_executor=None):receipts = []local_files = ExitStack()+ rows_done = None+ # Cell files copied into place; removed again unless their transaction commits.+ placed = []+def progress(next_stage, *, heartbeat=False, measurement=None):- nonlocal checkpoint, stage, stage_started_at+ nonlocal checkpoint, stage, stage_started_at, rows_done+ if next_stage != stage:+ rows_done = Nonenow = time.monotonic()if stage is not None:stage_seconds[stage] = round(stage_seconds.get(stage, 0) + now - checkpoint, 3)if next_stage != stage:stage_started_at = timezone.now().isoformat()+ if stage is not None:+ logger.info(+ "Pipeline stage finished",+ extra={+ "run": str(run.pk),+ "dataset": str(run.dataset_id),+ "stage": stage,+ "seconds": stage_seconds[stage],+ "source_rows": run.source.rows,+ },+ )checkpoint, stage = now, next_stagerun.result = {"stage": stage,@@ -374,6 +396,7 @@ def execute(run_id, *, script_executor=None):"stage_seconds": dict(stage_seconds),"seconds": round(now - started, 3),"steps": receipts,+ **({"rows_done": rows_done} if rows_done is not None else {}),"mode": run.mode,"attempt": str(run.attempt),"revision_fingerprint": run.pipeline.fingerprint if run.pipeline_id else None,@@ -418,12 +441,35 @@ def execute(run_id, *, script_executor=None):)return changed+ reported_at = 0.0++ def counting(next_stage, done):+ # A count every few seconds: each report is one write to the run row.+ nonlocal rows_done, reported_at+ now = time.monotonic()+ if next_stage != stage or now - reported_at >= ROW_REPORT_SECONDS:+ # One run must not fill the worker's volume for every other run on it.+ used = sum(item.stat().st_size for item in directory.rglob("*") if item.is_file())+ if used > SCRATCH_BYTES or shutil.disk_usage(directory).free < SCRATCH_FREE_BYTES:+ raise ValueError("Workshop scratch capacity reached; no version was published.")+ if next_stage != stage and not progress(next_stage):+ raise ValueError("The run stopped; no version was published.")+ rows_done, reported_at = done, now+ if not progress(next_stage, heartbeat=True):+ raise ValueError("The run stopped; no version was published.")++ def written(rows, index):+ # The script's rows arrive once its sandbox run ended: writing them is a stage.+ for done, row in enumerate(rows):+ if done % measure.PROGRESS_ROWS == 0:+ counting(f"step_{index + 1}_writing", done)+ yield row+try:if not progress("verifying_source"):returnif run.source.fingerprint != run.source_fingerprint:raise ValueError("The pinned source fingerprint changed before execution.")- rows.verify(run.source)if run.pipeline_id:recipe = run.pipelineexpected = digest(@@ -457,6 +503,8 @@ def execute(run_id, *, script_executor=None):rows.verify(run.artifact)directory = local_files.enter_context(scratch())input_path = directory / f"{run.source_id}.parquet"+ if shutil.disk_usage(directory).free - source_path.stat().st_size < SCRATCH_FREE_BYTES:+ raise ValueError("Workshop scratch capacity reached; no version was published.")shutil.copyfile(source_path, input_path)if store.file_sha256(input_path) != run.source_fingerprint:raise ValueError("The copied source does not match its pinned fingerprint.")@@ -476,6 +524,13 @@ def execute(run_id, *, script_executor=None):flow = pipeline_graph.describe(steps, files=package_files)step_inputs = {"source": input_path}outputs = []+ group_by = run.dataset.source_spec.get("split", {}).get("group_by", [])+ # Outputs are measured for the intent publication gives the dataset.+ pinned = (run.dataset.intent, run.dataset.capability_id)+ for field, value in declared_intent(run.dataset, steps[-1].get("consumer")).items():+ setattr(run.dataset, field, value)+ # A preview reads only the key rows of its sample.+ step_keys = {"source": lineage.head(run.source, store.row_count(input_path))}for index, step in enumerate(steps):node = flow["nodes"][index]parent_paths = [step_inputs[identity] for identity in node["inputs"]]@@ -495,6 +550,18 @@ def execute(run_id, *, script_executor=None):f"Step {node['id']} has incompatible columns or types across inputs. ""Normalize each branch explicitly before merging; no values were coerced.")+ identities = [+ {+ row[store.SOURCE_ROW]+ for row in store.iter_rows(path, columns=[store.SOURCE_ROW])+ }+ for path in parent_paths+ ]+ if len(set().union(*identities)) != sum(map(len, identities)):+ raise ValueError(+ f"Step {node['id']} has overlapping source_row identities across inputs. "+ "Use disjoint branches; no rows were deduplicated or published."+ )input_path = directory / f"{index}-inputs.parquet"store.write_rows(input_path,@@ -503,18 +570,17 @@ def execute(run_id, *, script_executor=None):if not any(store.row_count(path) for path in parent_paths)else None,)- with review.indexed_rows(input_path) as (_, tracked):- if not tracked:- raise ValueError(- f"Step {node['id']} has overlapping source_row identities across inputs. "- "Use disjoint branches; no rows were deduplicated or published."- )- raw, output = directory / f"{index}-raw.parquet", directory / f"{uuid.uuid4()}.parquet"+ parents = Parents(+ [(step_inputs[identity], step_keys[identity]) for identity in node["inputs"]],+ group_by,+ )+ output = directory / f"{uuid.uuid4()}.parquet"+ fingerprints = {path: store.file_sha256(path) for path in {input_path, *parent_paths}}receipt = {"index": index,"name": step.get("name", step.get("operation", "Transformation")),"state": "running",- "input_fingerprint": store.file_sha256(input_path),+ "input_fingerprint": fingerprints[input_path],"input_rows": store.row_count(input_path),"started_at": timezone.now().isoformat(),"step_id": node["id"],@@ -523,7 +589,7 @@ def execute(run_id, *, script_executor=None):"inputs": [{"step": identity,- "fingerprint": store.file_sha256(path),+ "fingerprint": fingerprints[path],"rows": store.row_count(path),}for identity, path in zip(node["inputs"], parent_paths, strict=True)@@ -539,20 +605,13 @@ def execute(run_id, *, script_executor=None):if not progress(f"step_{index + 1}_executing"):returnstep_started = time.monotonic()- manifest = store.read_manifest(input_path)if package_files is not None:- missing = set(step.get("input_schema", {})) - {- column["name"] for column in manifest- }- if missing:- raise ValueError(- f"Missing required input columns: {', '.join(sorted(missing))}."- )- for _ in pipeline_packages.check_rows(- store.iter_rows(input_path), step.get("input_schema", {})- ):- pass- records = pipeline_execution.execute_rows(+ violation = pipeline_execution.contract_violation(+ input_path, step.get("input_schema", {})+ )+ if violation:+ raise ValueError(violation)+ records = script_executor(run,index,input_path,@@ -560,26 +619,40 @@ def execute(run_id, *, script_executor=None):step,package_files,lambda index=index: progress(f"step_{index + 1}_executing", heartbeat=True),- script_executor,)records = pipeline_packages.check_rows(external_rows(records), step.get("output_schema", {}))script = package_files[step["entrypoint"]]- manifest = Noneelse:records = external_rows(store.iter_rows(paths.cell_path(run.artifact.dataset_id, run.artifact_id))if run.artifact_idelse run.specification["rows"])- script, manifest = "", None- store.write_rows(raw, records, manifest)- if step.get("consumer"):- if not progress(f"step_{index + 1}_validating_consumer"):- return- receipt["consumer_check"] = pipeline_execution.check_consumer(raw, step["consumer"])- count = store.row_count(raw)+ script = ""+ inherited = []+ store.write_rows(+ output, pipeline_execution.carry(written(records, index), parents, inherited)+ )+ count = store.row_count(output)+ if not count:+ store.write_rows(+ output,+ [],+ [+ {+ "name": name,+ "type": kind+ if kind in {"string", "integer", "number", "boolean"}+ else "json",+ }+ for name, kind in {+ **step.get("output_schema", {}),+ store.SOURCE_ROW: "integer",+ }.items()+ ],+ )receipt["output_rows"] = countchecks = step.get("checks", {})check_results = {"passed": {}, "failed": {}, "deferred": {}}@@ -609,84 +682,30 @@ def execute(run_id, *, script_executor=None):raise ValueError(f"Step {node['id']} row checks failed: {json.dumps(check_results['failed'])}.")- if not progress(f"step_{index + 1}_preserving_lineage"):+ if not progress(f"step_{index + 1}_measuring"):return- last_validation_update = 0.0-- def validation_progress(phase, completed, total, receipt=receipt):- nonlocal last_validation_update- now = time.monotonic()- if now - last_validation_update < 2 and completed != total:- return- last_validation_update = now- receipt["validation"] = {- "phase": phase,- "completed": completed,- "total": total,- "unit": "rows",- "updated_at": timezone.now().isoformat(),- }- used = sum(item.stat().st_size for item in directory.rglob("*") if item.is_file())- if used > 8 * 1024**3 or shutil.disk_usage(directory).free < 512 * 1024**2:- raise ValueError(- "Workshop scratch capacity reached; source versions remain unchanged."- )- if not progress(stage, measurement=receipt["validation"]):- raise ValueError("Publication was cancelled during validation.")-- with review.indexed_rows(- input_path,- parent_paths=parent_paths,- progress=validation_progress,- scratch=directory,- ) as source_index:- if count:- review.preserve_file_provenance(- input_path,- raw,- output,- group_by=review.group_columns(run.dataset, run.source),- parent_paths=parent_paths,- index=source_index,- strip_review=not run.pipeline_id or package_files is not None,- progress=validation_progress,- )- else:- empty_manifest = manifest or [- {- "name": name,- "type": kind- if kind in {"string", "integer", "number", "boolean"}- else "json",- }- for name, kind in {- **step.get("output_schema", {}),- store.SOURCE_ROW: "integer",- }.items()- ]- store.write_rows(- output,- [],- [column for column in empty_manifest if column["name"] != "human_reviewed"],- )- if not progress("measuring_impact"):- return- impact = review.impact_files(- input_path, output, index=source_index, progress=validation_progress+ measured = measure.describe_frame(+ run.dataset,+ output,+ inherited=inherited,+ on_progress=lambda done, index=index: counting(f"step_{index + 1}_measuring", done),+ )+ if step.get("consumer"):+ receipt["consumer_check"] = pipeline_execution.check_consumer(+ measured["intent_report"], step["consumer"])receipt.update(state="completed",- output_rows=count,- output_fingerprint=store.file_sha256(output),+ output_fingerprint=measured["fingerprint"],seconds=round(time.monotonic() - step_started, 3),- impact=impact,checks=checks,completed_at=timezone.now().isoformat(),)if run.mode == "preview":receipt["sample"] = bounded_sample(output)- outputs.append((output, script, receipt))+ outputs.append((output, script, receipt, measured))step_inputs[node["id"]] = output+ step_keys[node["id"]] = lineage.load(output)if run.mode == "preview":with transaction.atomic():Dataset.objects.select_for_update().get(pk=run.dataset_id)@@ -707,11 +726,6 @@ def execute(run_id, *, script_executor=None):if outputs:if not progress("publishing"):return- measured = {}- for output, _, _ in outputs:- measured[output.stem] = measure.describe_frame(run.dataset, output)- if not progress("publishing"):- returnwith transaction.atomic():binding = Noneif run.binding_id:@@ -719,10 +733,7 @@ def execute(run_id, *, script_executor=None):pk=run.binding_id)dataset = Dataset.objects.select_for_update().get(pk=run.dataset_id)- if (dataset.intent, dataset.capability_id) != (- run.dataset.intent,- run.dataset.capability_id,- ):+ if (dataset.intent, dataset.capability_id) != pinned:raise ValueError("The dataset settings changed during publication. Run the pinned recipe again.")@@ -731,7 +742,7 @@ def execute(run_id, *, script_executor=None):returnposition = (dataset.cells.aggregate(n=Max("position"))["n"] or 0) + 1input_cells = {"source": str(run.source_id)}- for index, (output, script, receipt) in enumerate(outputs):+ for index, (output, script, receipt, measured) in enumerate(outputs):receipt["input_cells"] = [input_cells[identity] for identity in receipt["input_steps"]]@@ -749,7 +760,9 @@ def execute(run_id, *, script_executor=None):)destination = paths.cell_path(dataset.pk, cell.pk)destination.parent.mkdir(parents=True, exist_ok=True)+ placed.extend([destination, lineage.keys_path(destination)])shutil.copyfile(output, destination)+ shutil.copyfile(lineage.keys_path(output), lineage.keys_path(destination))report = {"kind": "pipeline" if run.pipeline_id else "external","status": "accepted",@@ -761,9 +774,8 @@ def execute(run_id, *, script_executor=None):if package_fileselse "external_attributed",**receipt,- **receipt["impact"],}- Cell.objects.filter(pk=cell.pk).update(**measured[output.stem], review=report)+ Cell.objects.filter(pk=cell.pk).update(**measured, review=report)cell.refresh_from_db()receipt["output_cell"] = str(cell.pk)input_cells[receipt["step_id"]] = str(cell.pk)@@ -774,16 +786,17 @@ def execute(run_id, *, script_executor=None):result={**run.result,"rows": cell.rows,- "impact": receipts[-1]["impact"],"seconds": round(time.monotonic() - started, 3),- "semantic_quality": "unmeasured",- "analytics": cell.stats["analytics"],},lease_until=None,updated_at=timezone.now(),)Dataset.objects.filter(pk=dataset.pk).update(- active=cell, state=Dataset.State.IDLE, error="", updated_at=timezone.now()+ active=cell,+ state=Dataset.State.IDLE,+ error="",+ updated_at=timezone.now(),+ **declared_intent(dataset, steps[-1].get("consumer")),)activity.record(key=f"mcp-task:{dataset.project_id}:dataset_pipeline:{run.pk}",@@ -802,6 +815,7 @@ def execute(run_id, *, script_executor=None):transaction.on_commit(lambda: events.publish(dataset.pk, {"type": "dataset_changed"}))+ placed.clear()except (ValueError, rows.RowStoreError, DatasetError) as exc:fail(run_id, str(exc)[:1000])except Exception:@@ -811,9 +825,29 @@ def execute(run_id, *, script_executor=None):"Transformation failed. Inspect the recipe and source columns; no version was published.",)finally:+ for path in placed:+ path.unlink(missing_ok=True)local_files.close()+CONSUMER_INTENTS = {+ "chat_train": (Dataset.Intent.TRAIN, Dataset.TrainFormat.SFT),+ "decision_train": (Dataset.Intent.TRAIN, Dataset.TrainFormat.DECISION),+ "model_eval": (Dataset.Intent.EVAL, ""),+ "decision_eval": (Dataset.Intent.EVAL, ""),+}+++def declared_intent(dataset, consumer) -> dict:+ """The intent a published consumer states, for a dataset no person has given one."""+ if consumer not in CONSUMER_INTENTS or dataset.intent != Dataset.Intent.PENDING:+ return {}+ if dataset.frozen_before >= 0:+ return {}+ intent, train_format = CONSUMER_INTENTS[consumer]+ return {"intent": intent, "train_format": train_format}++def bounded_sample(path):sample, size = [], 0for row in islice(store.iter_rows(path), 5):@@ -830,7 +864,8 @@ def external_rows(records):yield {key: valuefor key, value in record.items()- if key not in {"human_reviewed", "_overmind_provenance", "_overmind_document_id"}+ # Platform lineage comes from the bound parents (carry), never from the output.+ if key not in {"_overmind_provenance", "_overmind_document_id", store.EVIDENCE}}@@ -946,8 +981,11 @@ def update_dataset(dataset, **fields):dataset.save(update_fields=["ocr_languages", "updated_at"])if "name" in fields:lifecycle.rename(dataset, fields["name"])- if "intent" in fields:- lifecycle.set_intent(dataset, fields["intent"])+ if "intent" in fields or "train_format" in fields:+ intent = fields.get("intent", dataset.intent)+ # A format survives a request that keeps the intent train and does not name one.+ kept = dataset.train_format if intent == Dataset.Intent.TRAIN else ""+ lifecycle.set_intent(dataset, intent, fields.get("train_format", kept))if "capability" in fields:lifecycle.set_capability(dataset, fields["capability"])if "active" in fields:diff --git a/overbae/services/finetuning_split.py b/overbae/services/finetuning_split.pyindex 67c4c4c7..bad30212 100644--- a/overbae/services/finetuning_split.py+++ b/overbae/services/finetuning_split.py@@ -8,14 +8,21 @@ def _get(row, key, default=None):def split_datapoint_ids(- datapoints, val_ratio: float, *, method="random", group_by=(), stratify_by=None+ datapoints, val_ratio: float, *, method="random", group_by=(), stratify_by=None, lineage=None):+ """Training and validation ids, keeping rows that share content, lineage or a declared+ group on one side. ``lineage`` holds each row's lineage keys, in datapoint order."""if not 0 < val_ratio < 1 or method not in {"ordered", "random"}:raise ValueError("Choose a validation ratio between zero and one and a random or ordered split.")records = []- for row in datapoints:+ keyed = (+ zip(datapoints, lineage, strict=True)+ if lineage is not None+ else ((row, frozenset()) for row in datapoints)+ )+ for row, inherited in keyed:record = {**(_get(row, "extra", {}) or {}),"source_row": _get(row, "id"),@@ -23,7 +30,7 @@ def split_datapoint_ids("expected_output": _get(row, "expected_output"),"source_trace_id": _get(row, "source_trace_id", ""),}- keys = contamination_keys(record, group_by)+ keys = contamination_keys(record, group_by) | inheritedrecords.append({"source_row": record["source_row"],diff --git a/overbae/services/finetuning_validator.py b/overbae/services/finetuning_validator.pyindex 1ead3760..3e9308ed 100644--- a/overbae/services/finetuning_validator.py+++ b/overbae/services/finetuning_validator.py@@ -19,6 +19,7 @@ from typing import Anyfrom modal_shared.decisions import decision_linefrom overbae.models import Cell, Dataset+from overbae.services.datasets import lineagefrom overbae.services.datasets import rows as row_storefrom overbae.services.datasets.contract import training_linefrom overbae.services.datasets.examples import normalize_record@@ -74,7 +75,7 @@ def validate_decision_rows(rows) -> ValidationResult:for count, row in enumerate(rows, 1):try:decision_line(row)- except (ValueError, AttributeError) as exc:+ except (ValueError, TypeError, AttributeError) as exc:if len(errors) < 20:errors.append(f"Example {count}: {exc}")if not count:@@ -140,6 +141,7 @@ def _validate_native_dataset(method=split_method,group_by=split.get("group_by", []),stratify_by=split.get("stratify_by"),+ lineage=lineage.stream(checkpoint),)result.stats.update(train_examples=len(training), val_examples=len(validation), validation_mode="split"@@ -148,6 +150,10 @@ def _validate_native_dataset(except ValueError as exc:result.valid = Falseresult.errors.append(str(exc))+ except OSError:+ # A version from before key files writes its key file on first read.+ result.valid = False+ result.errors.append("The version's lineage could not be read. Retry the check.")return result@@ -238,6 +244,7 @@ def validate_dataset(method=split_method,group_by=split.get("group_by", []),stratify_by=split.get("stratify_by"),+ lineage=lineage.stream(checkpoint),)split_stats.update(train_examples=len(training), val_examples=len(validation), validation_mode="split"@@ -246,6 +253,10 @@ def validate_dataset(except ValueError as exc:result.valid = Falseresult.errors.append(str(exc))+ except OSError:+ # A version from before key files writes its key file on first read.+ result.valid = False+ result.errors.append("The version's lineage could not be read. Retry the check.")result.stats.update(split_stats)return resultdiff --git a/overbae/services/mcp/__init__.py b/overbae/services/mcp/__init__.pyindex 463788da..89ca7ba9 100644--- a/overbae/services/mcp/__init__.py+++ b/overbae/services/mcp/__init__.py@@ -1,3 +1,3 @@"""MCP protocol and catalog services."""-CONTRACT_VERSION = "8.0.0"+CONTRACT_VERSION = "9.0.0"diff --git a/overbae/services/mcp/contracts/datasets.py b/overbae/services/mcp/contracts/datasets.pyindex 9316da9f..7fa2c159 100644--- a/overbae/services/mcp/contracts/datasets.py+++ b/overbae/services/mcp/contracts/datasets.py@@ -13,7 +13,7 @@ from urllib.parse import quotefrom pydantic import AliasChoices, Field, field_validator, model_validatorfrom overbae.models import Cell, Dataset-from overbae.services.datasets import analytics, imports, review, transformation+from overbae.services.datasets import analytics, imports, transformationfrom overbae.services.datasets.admission import status as landing_admission_statusfrom overbae.services.datasets.context import workshop_contextfrom overbae.services.datasets.contract import public_intent@@ -89,23 +89,6 @@ def _bounded(value, limit=2500):return text + "…"-def _quality_summary(report):- result = review.summary(report or {})- for key in ("audit", "audits"):- if key in result:- result[key] = _bounded(result[key], 500)- result["checks"] = [- {**check, "evidence": _clip(check.get("evidence", ""), 160)}- for check in result.get("checks", [])- ]- if result.get("semantic_audit"):- result["semantic_audit"] = {- **result["semantic_audit"],- "definitions": _bounded(result["semantic_audit"].get("definitions", []), 1000),- }- return result--def _source_summary(source):# Page whole entries: clipping extraction metadata can erase OCR limitations.return {@@ -168,7 +151,8 @@ class ActiveVersion(MCPModel):class DatasetListItem(MCPModel):id: strname: str = Field(default="", max_length=255)- intent: Literal["train", "eval", "explore", "pending"]+ intent: Literal["train", "eval", "pending"]+ train_format: Literal["sft", "decision", ""] = ""source_kind: Literal["file", "traces", "llm_calls", "pending"]state: Literal["landing", "idle", "running", "error"]capability: CapabilityRef | None = None@@ -191,7 +175,6 @@ class CellTransformation(MCPModel):class CellSummary(MCPModel):analytics: dict[str, Any] = Field(default_factory=dict)- preparation_plan: dict[str, Any] = Field(default_factory=dict)id: strposition: int = Field(ge=0)version: str = Field(min_length=1, max_length=32)@@ -211,10 +194,9 @@ class CellSummary(MCPModel):intent_report: dict[str, Any] = Field(default_factory=dict)capability_report: dict[str, Any] = Field(default_factory=dict)fits: FitReport+ fit: dict[str, FitReport] = Field(default_factory=dict)seconds: float = 0.0review: dict[str, Any] = Field(default_factory=dict)- quality_report: dict[str, Any] = Field(default_factory=dict)- readiness: dict[str, Any] = Field(default_factory=dict)used_at: datetime | None = Noneresource: ResourceLinkContract@@ -253,7 +235,6 @@ class DatasetDetail(DatasetListItem):default=None,description="Latest file stage; completed/total count files. PDF OCR adds pages_total, ocr_pages_completed and ocr_pages_total. Not an ETA or overall percentage.",)- preparation_plan: dict[str, Any] = Field(default_factory=dict)brief: str = Field(default="", max_length=8000)sources: list[dict[str, Any]] = Field(default_factory=list, max_length=100)sources_total: int = Field(default=0, ge=0)@@ -304,7 +285,7 @@ class DatasetMutationOutput(MCPModel):class ListDatasetsInput(MCPModel):capability: str | None = Field(default=None, min_length=1, max_length=255)- intent: Literal["train", "eval", "explore", "pending"] | None = None+ intent: Literal["train", "eval", "pending"] | None = Nonestate: Literal["landing", "idle", "running", "error"] | None = Nonesearch: str | None = Field(default=None, min_length=1, max_length=255)limit: int = Field(default=20, ge=1, le=_LIST_CAP)@@ -522,7 +503,7 @@ def mutation_output(class StartDatasetInput(MCPModel):brief: str = Field(min_length=1, max_length=8000)name: str = Field(default="Untitled dataset", min_length=1, max_length=255)- intent: Literal["train", "eval", "explore", "pending"] = "pending"+ intent: Literal["train", "eval", "pending"] = "pending"capability: str | None = Field(default=None, max_length=255)@@ -576,6 +557,7 @@ def _list_fields(dataset, chain: list[Cell]) -> dict[str, Any]:"id": str(dataset.id),"name": dataset.name or "","intent": public_intent(dataset.intent),+ "train_format": dataset.train_format,"source_kind": dataset.source_kind,"state": dataset.state,"capability": _capability_ref(dataset),@@ -617,11 +599,9 @@ def _cell_summary(intent_report=_jsonable(cell.intent_report or {}),capability_report=_jsonable(cell.capability_report or {}),review=_bounded(cell.review),- quality_report=_jsonable(_quality_summary(cell.quality_report)),analytics=analytics.describe(cell),- preparation_plan=_bounded(cell.preparation_plan),- readiness=review.readiness(dataset, cell),fits=_fit(cell, public_intent(dataset.intent)),+ fit=cell.fit(),seconds=float(cell.seconds or 0),used_at=cell.used_at,resource=_cell_link(dataset, cell),@@ -747,7 +727,7 @@ def next_actions(dataset, chain: list[Cell], active: Cell | None) -> list[NextAc)]ok, reason = active.fits(public_intent(dataset.intent))- if not ok or dataset.intent == Dataset.Intent.EXPLORE:+ if not ok:return [NextAction(tool="inspect_dataset_workbench",@@ -835,8 +815,7 @@ def serialize_dataset_detail("has_more": False,"next_cursor": None,},- "preparation_context": _bounded(workshop_context(dataset, measure_missing=False), 6000),- "preparation_plan": _bounded(dataset.preparation_plan, 3000),+ "preparation_context": _bounded(workshop_context(dataset), 6000),"capability_rank": _rank(dataset.capability_rank),"contamination_report": _bounded(dataset.source_spec.get("contamination_report", {})),"cells": cells,@@ -877,7 +856,6 @@ def serialize_dataset_detail(for name in ("operation","preparation_context",- "preparation_plan","contamination_report",):setattr(result, name, _bounded(getattr(result, name), 1000))@@ -894,9 +872,6 @@ def serialize_dataset_detail(for name in ("analytics","review",- "quality_report",- "preparation_plan",- "readiness","intent_report","capability_report",):@@ -905,7 +880,7 @@ def serialize_dataset_detail(name,_bounded(getattr(cell, name),- 6000 if name in {"analytics", "quality_report"} else 500,+ 6000 if name == "analytics" else 500,),)result.truncated_fields.append(f"cells.{cell.id}.{name}")diff --git a/overbae/services/mcp/contracts/workbench.py b/overbae/services/mcp/contracts/workbench.pyindex fec7e49a..b4981869 100644--- a/overbae/services/mcp/contracts/workbench.py+++ b/overbae/services/mcp/contracts/workbench.py@@ -3,7 +3,6 @@ from uuid import UUIDfrom pydantic import Field, model_validator-from overbae.services.datasets import reviewfrom overbae.services.mcp.contracts.common import (JobReceipt,MCPModel,@@ -16,8 +15,6 @@ from overbae.services.mcp.contracts.datasets import NextActiondef compact_run(record: dict, evidence_resource: dict) -> dict:def measured(scope):result = {key: value for key, value in scope.items() if key != "sample"}- if "impact" in result:- result["impact"] = review.summary(result["impact"])if "sample" in scope:result["sample_count"] = len(scope["sample"])return result@@ -125,7 +122,10 @@ class UpdateInput(DatasetInput):description="Future-import Tesseract codes (e.g. [eng, fra]); [] English. Set before upload. Published cells unchanged.",)name: str | None = Field(default=None, min_length=1, max_length=255)- intent: Literal["train", "eval", "explore"] | None = None+ intent: Literal["train", "eval"] | None = None+ train_format: Literal["sft", "decision", ""] | None = Field(+ default=None, description="For a train dataset: sft or decision training."+ )active: UUID | None = Nonecapability: UUID | None = Nonediff --git a/overbae/services/mcp/prompts.py b/overbae/services/mcp/prompts.pyindex d38210b0..e7553746 100644--- a/overbae/services/mcp/prompts.py+++ b/overbae/services/mcp/prompts.py@@ -273,9 +273,8 @@ PROMPTS = ("Fine-tune capability {capability} from dataset {dataset}. Use list_datasets, ""inspect_dataset, and query_dataset to choose and verify a train cell. ""For a new task or an unsuccessful-run retry, follow develop-model-from-data for either generative or decision training: save_training_plan, source audit, frozen roles, simple baseline and fitting sanity check. A full run does not require a pilot; do not add one unless the user requests it. Plan-bound training uses create_training_experiment with explicit pilot/full stages; start_finetune is the separate direct exploratory path. "- "Inspect preparation_context for source/active task families and downstream contracts; "+ "Inspect preparation_context for source/active columns and downstream contracts; ""do not assume the first sample or the bound capability describes every row. "- "Inspect the saved preparation plan, its assumptions and applicable checks. ""Report technical compatibility, source preservation, coverage and semantic findings ""separately on train and held-out eval versions, retaining unknowns and sample coverage. ""Worker examples are not end-to-end capability examples. Resolve scope and missing "diff --git a/overbae/services/mcp/resources.py b/overbae/services/mcp/resources.pyindex 40118a66..caab04f3 100644--- a/overbae/services/mcp/resources.py+++ b/overbae/services/mcp/resources.py@@ -134,7 +134,6 @@ _TOKEN_MEASUREMENTS = frozenset("total_tokens","num_tokens","max_token_length",- "p95_token_length",})_FINETUNE_PROGRESS_BLOCKED_PARTS = frozenset(@@ -222,15 +221,16 @@ def pipeline_package_guide() -> dict:],},"column_types": sorted(pipeline_packages.TYPES),- "analytics": "Published cells carry fingerprint-bound server analytics from a full-row scan. inspect_dataset and REST expose the same counts, baselines, warnings and not_checked risks; completed pipeline get_job includes final-output analytics. Read the exact selected consumer/partition cell before training handoff. Historical or stale reports are unmeasured: use explore_dataset to refresh without changing rows. Class imbalance and rare-class thresholds are advisory; soft targets are not converted to labels and a majority baseline is not model performance.",+ "analytics": "Published cells carry fingerprint-bound server analytics from a full-row scan. inspect_dataset and REST expose the same counts, baselines, warnings and not_checked risks. Read the exact selected consumer/partition cell before training handoff. Historical or stale reports are unmeasured: use explore_dataset to refresh without changing rows. Class imbalance and rare-class thresholds are advisory; soft targets are not converted to labels and a majority baseline is not model performance.","consumer": {"values": ["decision_train", "decision_eval", "chat_train", "model_eval"],"scope": "Declare on the final step. Validates the complete output, including nested decision targets, in both preview and publish. Technical compatibility does not establish target meaning.",},- "batch_rows": "Optional per-step integer 1–100000. The script runs as a separate bounded sandbox run for each consecutive row batch; outputs concatenate in source order and all steps publish atomically. Declare only for independent row transformations, never global sorting, grouping, splitting or deduplication. Choose a batch whose expanded JSONL input and output each fit half the declared scratch_mb. Each batch gets the package time limit; progress reports completed batches and rows. Global row checks run after concatenation.",+ "batch_rows": "Optional per-step integer 1–100000. The script runs once per consecutive row batch, each in a fresh process, one after another within the step's single sandbox run; outputs concatenate in source order and all steps publish atomically. Declare only for independent row transformations, never global sorting, grouping, splitting or deduplication. Memory admission estimates one batch from the frame's average row width, plus the whole input and output held between batches; at most 10,000 batches; each batch gets the package time limit; progress reports completed batches. Global row checks run after concatenation.","corrections": "Edit the same recipe family and run the corrected package from its original source cell. Successful publication replaces the displayed process; no repair-history view or disconnected prepared-v2 sources. Pinned training and evaluation inputs remain reproducible internally. Recipe ownership is project-scoped, not tied to the dataset or capability; reuse only when source and task semantics are compatible.","source_boundary": "Upload original source bytes once with pinned upstream revision metadata. Register retained transformation code before full-data processing. Locally prepared derivatives must use lineage-bound external import, never masquerade as an independent source upload.","script_arguments": ["input.jsonl", "output.jsonl", "parameters.json"],+ "io": "Optional per-step jsonl (default) or parquet. With parquet the script reads input.parquet and writes output.parquet instead (for pandas, pyarrow or DuckDB scripts); nested values are JSON text in the input; output columns may be any Arrow type except binary, which is stored as UTF-8 text. Output values must be finite.","inspectability": "Keep each step's meaningful logic in its entrypoint; reserve helpers for reusable functions. Cell transformation metadata binds exact run/revision/package/entrypoint and distinguishes platform execution from external imports. Inspect every retained file via the package resource (file, offset, limit in characters; next_offset until exhausted). Source reads verify the package and file checksums without executing code.","starter_script": "import json, sys\n\nwith open(sys.argv[1], encoding='utf-8') as source, open(sys.argv[2], 'w', encoding='utf-8') as output:\n for line in source:\n row = json.loads(line)\n # Author the requested transformation here; retain source_row.\n output.write(json.dumps(row, ensure_ascii=False) + '\\n')\n","checks": "preserve_rows and lineage apply in preview and publish. min_rows/max_rows are full-population assertions: preview records them as deferred, publication enforces them. Do not hardcode the first source's size in a reusable recipe unless that size is a real requirement.",@@ -284,7 +284,7 @@ def _dataset_upload_resource(uri: str) -> dict:"documents": "PDF, DOCX, Markdown, UTF-8 text and PNG/JPEG/WebP images are extracted by the batch worker (100 MiB per document, 2000 pages per PDF). Upload reservations return the file-type byte limit. Original bytes and element/page evidence are retained. PDF extraction preserves native text and automatically runs local English Tesseract OCR on scanned pages and embedded images. Direct images are capped at 64 megapixels; animated images are rejected. OCR engine/version, page regions, upright image coordinates and recognition confidence are retained. Reading order and visual table structure are not reconstructed. A document with no text lands with rows=0 and extraction.status=no_text; only a source with no text at all fails. Upload inspection returns rows=null until extraction. get_job(kind=dataset_run) exposes file/stage and measured OCR-page progress under progress.landing.","pdf_text_recovery": {"trigger": "Pages where the primary native parser returned no text are checked with PDFium before OCR, including selectable Type 3 font layers.",- "evidence": "Source extraction.native_text_recovery records engine/version, recovered pages, rows, characters, control_characters and reason. Row extraction methods distinguish pdfium-native-text from tesseract-ocr; page regions remain retained.",+ "evidence": "Source extraction.native_text_recovery records engine/version, recovered pages, rows, characters, control_characters and reason. Each row's _overmind_evidence keeps its page regions and extraction method, pdfium-native-text or tesseract-ocr.","limits": "Encoded text is source evidence, not visual verification. Font-encoding artifacts, reading order and diagram relationships require native-agent inspection; the platform does not normalize their meaning. This recovery does not certify partial omissions on pages where the primary parser returned some text.",},"publication_status": "Without --wait, CLI state/state_scope=at_publication describe the saved publication snapshot, not current extraction. Read get_job(kind=dataset_run) for current progress. --wait returns state_scope=observed_after_landing.",diff --git a/overbae/services/mcp/tools_workbench.py b/overbae/services/mcp/tools_workbench.pyindex 3371e7a2..9afb0818 100644--- a/overbae/services/mcp/tools_workbench.py+++ b/overbae/services/mcp/tools_workbench.py@@ -220,7 +220,7 @@ def register_workbench_tools(catalog):"update_dataset",UpdateInput,False,- "Set name, user intent, capability, active cell or future Tesseract OCR codes ([] English). Intent/capability freeze after use; null clears capability/default. Existing cells/consumers unchanged.",+ "Set name, intent (train with train_format sft or decision, or eval), capability, active cell or future Tesseract OCR codes ([] English). Intent/capability freeze after use; null clears capability/default. Existing cells/consumers unchanged.",),]for name, model, read_only, description in definitions:diff --git a/overbae/tasks/finetuning.py b/overbae/tasks/finetuning.pyindex 2f972f69..5ff91a5d 100644--- a/overbae/tasks/finetuning.py+++ b/overbae/tasks/finetuning.py@@ -108,6 +108,7 @@ def _build_training_jsonl(version) -> tuple[str, int]:def _resolve_train_val_paths(job, supports_validation: bool) -> tuple[str, str | None, int, dict]:"""Returns ``(training_path, validation_path | None, num_train_rows, event_metadata)``."""+ from overbae.services.datasets import lineagefrom overbae.services.datasets import rows as row_storefrom overbae.services.finetuning_split import split_datapoint_ids@@ -145,6 +146,7 @@ def _resolve_train_val_paths(job, supports_validation: bool) -> tuple[str, str |method=job.split_method,group_by=version.dataset.source_spec.get("split", {}).get("group_by", []),stratify_by=version.dataset.source_spec.get("split", {}).get("stratify_by"),+ lineage=(keys for _, keys in lineage.read(version)),)train_ids, val_ids = set(train_ids), set(val_ids)training_path, num_train = _write_rows(diff --git a/overmind/.claude-plugin/plugin.json b/overmind/.claude-plugin/plugin.jsonindex e05eb90f..a7641cf6 100644--- a/overmind/.claude-plugin/plugin.json+++ b/overmind/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "overmind",- "version": "1.2.12",+ "version": "1.2.13","description": "Overmind skills — agent observability, tracing, and platform workflows for coding agents.","author": {"name": "Overmind",diff --git a/overmind/.codex-plugin/plugin.json b/overmind/.codex-plugin/plugin.jsonindex f73f6fa2..8951fa2f 100644--- a/overmind/.codex-plugin/plugin.json+++ b/overmind/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "overmind",- "version": "1.2.12",+ "version": "1.2.13","description": "Investigate agent failures, prepare datasets, evaluate models, and manage training and serving with Overmind.","author": {"name": "Overmind",diff --git a/overmind/.cursor-plugin/plugin.json b/overmind/.cursor-plugin/plugin.jsonindex 8a8ccab4..82241960 100644--- a/overmind/.cursor-plugin/plugin.json+++ b/overmind/.cursor-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "overmind","displayName": "Overmind",- "version": "1.2.12",+ "version": "1.2.13","description": "Overmind skills and MCP — agent observability, tracing, and platform tools for coding agents.","author": {"name": "Overmind",diff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.pyindex c2b435fd..e2ca0b0a 100644--- a/overmind/overmind/__init__.py+++ b/overmind/overmind/__init__.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any-__version__ = "0.1.122"+__version__ = "0.1.123"from .client import Client, ModelDeleted, OvermindInferenceErrordiff --git a/overmind/overmind/dataset_cmd.py b/overmind/overmind/dataset_cmd.pyindex fec3bc43..7a9c463a 100644--- a/overmind/overmind/dataset_cmd.py+++ b/overmind/overmind/dataset_cmd.py@@ -28,7 +28,7 @@ CHUNK_TIMEOUT = 120UPLOAD_TRANSPORT_RETRIES = 5MIN_UPLOAD_CHUNK_BYTES = 1024 * 1024EXPORT_CHUNK_SIZE = 8_192-ALLOWED_INTENTS = {"train", "eval", "explore"}+ALLOWED_INTENTS = {"train", "eval"}SPLIT_POSITIONS = ("head", "tail", "random")EXPORT_HEADERS = (("cell", "X-Overmind-Cell"),@@ -250,7 +250,7 @@ def _normalize_intent(intent: str | None) -> str | None:if not value:return Noneif value not in ALLOWED_INTENTS:- raise DatasetUploadError("intent must be train, eval or explore.")+ raise DatasetUploadError("intent must be train or eval.")return value@@ -631,7 +631,7 @@ def upload(path: Annotated[Path, typer.Option("--path", help="Path to overmind.toml")] = DEFAULT_PATH,intent: Annotated[str | None,- typer.Option("--intent", help="Dataset intent: train, eval or explore"),+ typer.Option("--intent", help="Dataset intent: train or eval"),] = None,capability: Annotated[str | None,diff --git a/overmind/overmind/skills_db.py b/overmind/overmind/skills_db.pyindex 6d7914f1..828b8b5d 100644--- a/overmind/overmind/skills_db.py+++ b/overmind/overmind/skills_db.py@@ -1,7 +1,7 @@from dataclasses import dataclass# Every plugin manifest (.claude-plugin, .codex-plugin, .cursor-plugin) carries this version.-SKILLS_VERSION = "1.2.12"+SKILLS_VERSION = "1.2.13"@dataclassdiff --git a/overmind/pyproject.toml b/overmind/pyproject.tomlindex 2a45b3a1..8d403901 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.122"+version = "0.1.123"[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 fce3ed1e..4338df91 100644--- a/overmind/skills/overmind-datasets/SKILL.md+++ b/overmind/skills/overmind-datasets/SKILL.md@@ -35,10 +35,10 @@ contracts (`list_datasets` shows the active version's):probability/ordinal targets.- **`eval`**: an `input` on every row plus an `expected_output` column with at leastone reference.-- **`explore`**: data exploration, without automatic train/eval preparation.-- **`pending`**: no user purpose yet. Obtain their choice of Training, Eval or Data- exploration and set it with `update_dataset`; never infer intent from rows. A- leftover stored `ft` is **train**; there is no `ft` or `surface` intent.+- **`pending`**: no user purpose yet. Obtain their choice of training or evaluation+ and set it with `update_dataset`; never infer intent from rows. For exploration+ only, leave the intent pending and use `explore_dataset`. Publishing a final step+ with a declared `consumer` sets a pending intent (and `train_format`).Set intent at upload (`overmind dataset upload FILE --json --intent train|eval`), atcreate (`create_dataset_from_traces` / `_failures`), or later with@@ -56,10 +56,12 @@ decision comparisons use their frozen calibration/final plan in place of the evaA use freezes the version and everything before it, and starts a new major (2.0). Aused cell freezes intent: derive a separate dataset or create role-specific partitionsinstead of retagging a used chain. A contract is measured, never declared.-Capability prompt/schema mismatches, incomplete quality reviews and train/eval overlap-are advisory warnings, not technical-format errors; inspect cell `warnings` and-`readiness.quality_reason`. A passing format contract is not a claim that the answers-are supported by the inputs.+Capability prompt/schema mismatches and train/eval overlap are advisory warnings,+not technical-format errors. Each cell's `fit` says, for SFT training, decision+training and evaluation, whether its rows fit and why not. A train dataset's+`train_format` (`sft` or `decision`) is set by `update_dataset`, or by publication+when the final step declares `chat_train` or `decision_train` and no intent is set.+A passing format contract is not a claim that the answers are supported by the inputs.## Sources and inspection@@ -251,7 +253,7 @@ version and never partially publish output.Follow the run's `poll_after_seconds`; a queue wait alone is not a reason toresubmit or inspect infrastructure. A terminal receipt includes `completed_at`and stops suggesting polling. Format compatibility and task suitability are-different: readiness reports task suitability as unmeasured, not implicitly ready.+different: task suitability stays unmeasured, not implicitly ready.Reuse does not require copying the recipe into another dataset. Source anddestination must be in the same project. Save a paused source-to-revision binding@@ -308,7 +310,7 @@ an external coding agent or a remote provider request.## Consumer handoff-Inspect the actual output, technical format, impact and semantic limitations+Inspect the actual output, technical format, row counts and semantic limitationsseparately. Preserve exact dataset/cell IDs for training and evaluation.`update_dataset(active=...)` selects the default without changing prior consumers.Quality findings remain advisory; unreadable or incompatible data blocks use.@@ -345,9 +347,12 @@ evidenced semantics and structured provenance; never remove them to pass checks.Preview samples a bounded prefix and does not establish coverage of every family.For row-independent transformations, declare step `batch_rows` (1–100000).-Consecutive batches execute in separate restricted containers and concatenate in-source order. Each expanded JSONL input/output must fit half the package's-`scratch_mb`; each batch has the declared time limit. Global sorting, grouping,+Consecutive batches run one after another in fresh processes inside the step's one+sandbox run and concatenate in source order. Memory admission estimates one batch+from the frame's average row width, plus the whole input and an output the size of the+expanded input, held between batches; set `limits.memory_mb` for steps whose output+is much larger than their input; each batch has the declared time limit. A step may declare `"io": "parquet"` to+read `input.parquet` and write `output.parquet` instead of JSONL. Global sorting, grouping,splitting and deduplication must not use batching. Row checks apply to the combinedoutput, publication remains atomic, and progress records completed batches androws. A failed or cancelled batch publishes no partial cells. CLI directorydiff --git a/overmind/skills/overmind-training/SKILL.md b/overmind/skills/overmind-training/SKILL.mdindex ca4a7280..81375f69 100644--- a/overmind/skills/overmind-training/SKILL.md+++ b/overmind/skills/overmind-training/SKILL.md@@ -48,8 +48,8 @@ A fine-tuning job needs both of these before any paid preparation, estimate orPrefer the native `finetune-capability` prompt with the selected dataset andoptional capability. Resolve datasets with `list_datasets`; inspect and query-the exact train and held-out eval cells. Inspect whole-frame task families and-workshop findings rather than assuming a sample describes the whole corpus.+the exact train cell, and the held-out eval cell when the evaluation uses one. Inspect each cell's measured columns, `fit` and+analytics rather than assuming a sample describes the whole corpus.Use `get_model_catalog` for initial model discovery (it is dataset-independent andreports the active backend, tier, context limits, batch bounds, training methods,diff --git a/overmind/tests/test_dataset_cmd.py b/overmind/tests/test_dataset_cmd.pyindex 4166dd83..d40aab42 100644--- a/overmind/tests/test_dataset_cmd.py+++ b/overmind/tests/test_dataset_cmd.py@@ -110,7 +110,7 @@ def test_upload_file_rejects_ft_intent_before_network(tmp_path: Path):path.write_bytes(b"{}\n")session = ExportSession(FakeResponse({}))- with pytest.raises(DatasetUploadError, match="train, eval or explore"):+ with pytest.raises(DatasetUploadError, match="train or eval"):upload_file(path,project_id="project-1",diff --git a/overmind/uv.lock b/overmind/uv.lockindex d1cc7bfb..f135f1a0 100644--- a/overmind/uv.lock+++ b/overmind/uv.lock@@ -1,9 +1,9 @@version = 1-revision = 5+revision = 3requires-python = ">=3.10, <4"resolution-markers = ["python_full_version >= '3.12' and sys_platform == 'emscripten'",- "python_full_version == '3.11.*' or (python_full_version >= '3.12' and sys_platform != 'emscripten')",+ "(python_full_version >= '3.11' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')","python_full_version < '3.11'",]@@ -923,7 +923,7 @@ wheels = [[[package]]name = "overmind"-version = "0.1.122"+version = "0.1.123"source = { editable = "." }dependencies = [{ name = "packaging" },diff --git a/pyproject.toml b/pyproject.tomlindex 00c7ead0..eb223400 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -76,6 +76,7 @@ dependencies = ["pypdfium2>=5.0,<6","daytona==0.231.1","matplotlib>=3.11.2",+ "orjson>=3.13.0",]description = "Overbae — unified Django API for the Overclaw / Overmind platform"license = { text = "AGPL-3.0" }diff --git a/sandbox/documents/extract.py b/sandbox/documents/extract.pyindex e1db18f2..e3814853 100644--- a/sandbox/documents/extract.py+++ b/sandbox/documents/extract.py@@ -195,7 +195,7 @@ def extract("regions": row.pop("regions", []),}row.update(_overmind_document_id=identity, source_name=filename)- row["_overmind_provenance"] = {+ row["_overmind_evidence"] = {"evidence": [evidence],"extraction": row.pop("extraction", {"method": method, "version": parser_version}),}diff --git a/sandbox/execute.py b/sandbox/execute.pyindex 354f34ef..7880b2f0 100644--- a/sandbox/execute.py+++ b/sandbox/execute.py@@ -18,7 +18,10 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import BinaryIO-from sandbox import packages+import pyarrow as pa+import pyarrow.parquet as pq++from sandbox import packages, script_ioGIB = 1024**3EXTRACT_CPU_SECONDS = 1200@@ -57,6 +60,8 @@ class Outcome:extraction: dict | None = Noneexit_code: int | None = Noneruntime: dict | None = None+ # Bytes of each batch's output, in order, when the output holds several.+ segments: list[int] | None = Nonedef gib(value: float) -> str:@@ -91,11 +96,26 @@ def memory_budget() -> int:def need_for(header: dict) -> int:if header["mode"] == "package":- # Keep main's measured dataframe expansion allowance when admitting JSONL packages.- return max(GIB, int(header["input_bytes"] * 5.5) + 256 * 1024**2 + header["package_bytes"])+ expanded = max(header["input_bytes"], header.get("expanded_bytes", 0))+ # The whole input and the finished outputs wait on the tmpfs between batches.+ retained = header["input_bytes"] + expanded if _batched(header) else 0+ return max(GIB // 2, _child_need(header) + retained)return max(2 * GIB, 4 * int(header["input_bytes"])) + 3 * header.get("cache_bytes", 0)+def _batched(header: dict) -> bool:+ return bool(header.get("batch_rows") and header.get("rows"))+++def _child_need(header: dict) -> int:+ """One script process: the decoded rows it holds, about 5.5 times their uncompressed+ size (one batch with batch_rows), and its package."""+ expanded = max(header["input_bytes"], header.get("expanded_bytes", 0))+ if _batched(header):+ expanded = expanded * min(1.0, header["batch_rows"] / header["rows"])+ return int(expanded * 5.5) + 256 * 1024**2 + header["package_bytes"]++def refusal(header: dict, need: int, budget: int) -> str:if header["mode"] == "package":memory = header.get("limits", {}).get("memory_mb")@@ -552,6 +572,86 @@ def spawn(return Outcome(ok=True, stdout=stdout, seconds=seconds, exit_code=0, runtime=facts)+# What every batch of a run shares; anything else a batch leaves behind is removed.+_RUN_FILES = {"package", "parameters.json", "request.json"}+++def _reset(scratch: Path) -> None:+ for path in scratch.iterdir():+ if path.name in _RUN_FILES:+ continue+ if path.is_dir() and not path.is_symlink():+ shutil.rmtree(path, ignore_errors=True)+ else:+ path.unlink(missing_ok=True)+++def _run_batches(header, child, scratch, slot, stop, on_progress) -> Outcome:+ """Runs the script once per batch of ``batch_rows`` rows, one batch at a time, in fresh+ processes under one reservation. The whole input and the finished outputs wait where+ the script cannot read them."""+ name = f"output.{header.get('io', 'jsonl')}"+ held = Path(tempfile.mkdtemp(prefix="held_", dir=scratch.parent))+ try:+ rows = held / "rows.parquet"+ (scratch / "input.parquet").replace(rows)+ parquet = pq.ParquetFile(rows)+ size = header.get("batch_rows") or max(parquet.metadata.num_rows, 1)+ total = max(1, -(-parquet.metadata.num_rows // size))+ combined = (held / "output").open("w+b")+ segments, seconds, outcome = [], 0.0, Outcome(ok=True)+ metadata = parquet.schema_arrow.metadata or {}+ kinds = {+ column["name"]: column["type"]+ for column in json.loads(metadata.get(script_io.MANIFEST_KEY, b"[]"))+ }+ batches = parquet.iter_batches(batch_size=size)+ for number in range(total):+ if stop is not None and stop.is_set():+ outcome = Outcome(ok=False, error="The run was cancelled.")+ break+ batch = next(batches, None) or pa.RecordBatch.from_pylist([], parquet.schema_arrow)+ if header.get("io", "jsonl") == "jsonl":+ script_io.write_jsonl(batch, kinds, scratch / "input.jsonl")+ else:+ pq.write_table(pa.Table.from_batches([batch]), scratch / "input.parquet")+ outcome = spawn(child, scratch, slot, stop)+ seconds += outcome.seconds+ if not outcome.ok:+ break+ output = claim(scratch / name, packages.MAX_OUTPUT_BYTES)+ if output is None:+ outcome.ok = False+ outcome.error = f"The package did not produce a readable regular {name}."+ break+ # The 2 GiB output limit holds before a batch is copied, separator included.+ if combined.tell() + os.fstat(output.fileno()).st_size + 1 > packages.MAX_OUTPUT_BYTES:+ output.close()+ outcome.ok, outcome.error = False, "The package output exceeds 2 GiB."+ break+ with output:+ start = combined.tell()+ shutil.copyfileobj(output, combined)+ # A JSONL batch without a final newline must not join the next batch's line.+ if name == "output.jsonl" and combined.tell() > start:+ combined.seek(-1, os.SEEK_END)+ if combined.read(1) != b"\n":+ combined.write(b"\n")+ segments.append(combined.tell() - start)+ _reset(scratch)+ if on_progress is not None:+ on_progress({"batches": {"completed": number + 1, "total": total}})+ outcome.seconds = round(seconds, 3)+ if outcome.ok:+ combined.seek(0)+ outcome.output, outcome.segments = combined, segments+ else:+ combined.close()+ return outcome+ finally:+ shutil.rmtree(held, ignore_errors=True)++def run(header: dict,scratch: Path,@@ -571,13 +671,7 @@ def run(wall_seconds=limits.get("seconds", 300),scratch_bytes=limits.get("scratch_mb", 2048) * 1024**2,)- outcome = spawn(child, scratch, slot, stop)- if outcome.ok:- outcome.output = claim(scratch / "output.jsonl", packages.MAX_OUTPUT_BYTES)- if outcome.output is None:- outcome.ok = False- outcome.error = "The package did not produce a readable regular output.jsonl."- return outcome+ return _run_batches(header, child, scratch, slot, stop, on_progress)child = Child(argv=[str(Path(__file__).with_name("documents") / "child.py"),diff --git a/sandbox/package_child.py b/sandbox/package_child.pyindex c6f292b5..d88b3781 100644--- a/sandbox/package_child.py+++ b/sandbox/package_child.py@@ -21,6 +21,7 @@ def main():os.sched_setaffinity(0, sorted(os.sched_getaffinity(0))[: request["cpus"]])root = Path.cwd()entrypoint = root / "package" / request["entrypoint"]+ suffix = request["io"]# Python's isolated mode leaves this file's folder off the import path.sys.path.insert(0, str(Path(__file__).parent))from kernel import confine@@ -31,8 +32,8 @@ def main():sys.path.insert(0, str(root / "package"))sys.argv = [str(entrypoint),- str(root / "input.jsonl"),- str(root / "output.jsonl"),+ str(root / f"input.{suffix}"),+ str(root / f"output.{suffix}"),str(root / "parameters.json"),]runpy.run_path(str(entrypoint), run_name="__main__")diff --git a/sandbox/packages.py b/sandbox/packages.pyindex 0fd3e790..21018793 100644--- a/sandbox/packages.py+++ b/sandbox/packages.py@@ -1,19 +1,33 @@-"""Retained JSONL packages run inside the existing sandbox isolation boundary."""+"""Retained packages run inside the existing sandbox isolation boundary."""import hashlibimport json+import platformfrom functools import cachefrom pathlib import Path, PurePosixPathMAX_PACKAGE_BYTES = 20 * 1024**2MAX_OUTPUT_BYTES = 2 * 1024**3+MAX_BATCHES = 10_000+++IO = ("jsonl", "parquet")@cachedef runtime_id():+ """What a script can observe: its I/O contract, the interpreter, the libraries it can+ import and the runner that confines it. A change to the server leaves it unchanged."""root = Path(__file__).resolve().parent- digest = hashlib.sha256(b"overmind-sandbox-package-v1\0")- for path in [root.parent / "uv.lock", *sorted(root.rglob("*.py"))]:+ # The interpreter's version, not its build string: one runtime on every host OS.+ interpreter = f"{platform.python_implementation()} {platform.python_version()}"+ digest = hashlib.sha256(b"overmind-sandbox-package-v3\0" + interpreter.encode() + b"\0")+ for path in (+ root.parent / "uv.lock",+ root / "package_child.py",+ root / "kernel.py",+ root / "script_io.py",+ ):digest.update(path.relative_to(root.parent).as_posix().encode() + b"\0")digest.update(path.read_bytes())return "sha256:" + digest.hexdigest()@@ -31,6 +45,18 @@ def validate(header):raise ValueError("A package entrypoint is required.")if not isinstance(header.get("parameters"), dict):raise ValueError("Package parameters must be an object.")+ if header.get("io", "jsonl") not in IO:+ raise ValueError("Package io is jsonl or parquet.")+ for name in ("expanded_bytes", "rows"):+ if type(header.get(name, 0)) is not int or header.get(name, 0) < 0:+ raise ValueError(f"{name} must be a whole number.")+ batch_rows = header.get("batch_rows")+ if batch_rows is not None and (type(batch_rows) is not int or not 1 <= batch_rows <= 100000):+ raise ValueError("batch_rows must be between 1 and 100000.")+ # Each batch adds one output segment length to the reply header.+ rows = header.get("rows", 0)+ if batch_rows and rows and -(-rows // batch_rows) > MAX_BATCHES:+ raise ValueError(f"batch_rows must leave at most {MAX_BATCHES:,} batches.")bounds = {"seconds": (1, 1200),"memory_mb": (64, 4096),@@ -78,6 +104,10 @@ def unpack(header, scratch):(scratch / "parameters.json").write_text(json.dumps(header["parameters"], allow_nan=False))(scratch / "request.json").write_text(json.dumps(- {"entrypoint": header["entrypoint"], "cpus": header.get("limits", {}).get("cpus", 2)}+ {+ "entrypoint": header["entrypoint"],+ "cpus": header.get("limits", {}).get("cpus", 2),+ "io": header.get("io", "jsonl"),+ }))diff --git a/sandbox/script_io.py b/sandbox/script_io.pynew file mode 100644index 00000000..8999a277--- /dev/null+++ b/sandbox/script_io.py@@ -0,0 +1,39 @@+"""What a package script reads: the frame rows the platform hands it, as JSONL. A change+here changes the sandbox runtime identity."""++import json+import math+from pathlib import Path++# The column kinds the platform stores with every frame.+MANIFEST_KEY = b"overmind.columns"+++def _decode(value, kind):+ # JSON has no NaN or infinity: a missing number reaches the script as null.+ if value is None or (isinstance(value, float) and not math.isfinite(value)):+ return None+ if kind == "json":+ try:+ return json.loads(value, parse_constant=lambda _: None)+ except ValueError:+ return value+ if kind == "datetime":+ return value.isoformat()+ return value+++def write_jsonl(batch, kinds: dict, destination: Path) -> None:+ """A batch of frame rows as one JSON object per line, nested values decoded."""+ names = batch.schema.names+ columns = [+ [_decode(v, kinds.get(name)) for v in batch.column(name).to_pylist()] for name in names+ ]+ with destination.open("w", encoding="utf-8") as output:+ for values in zip(*columns, strict=True):+ output.write(+ json.dumps(+ dict(zip(names, values, strict=True)), ensure_ascii=False, allow_nan=False+ )+ + "\n"+ )diff --git a/sandbox/server.py b/sandbox/server.pyindex de6410db..94f49999 100644--- a/sandbox/server.py+++ b/sandbox/server.py@@ -133,6 +133,8 @@ def _reply(outcome: execute.Outcome) -> dict[str, Any]:}if outcome.extraction is not None:reply["extraction"] = outcome.extraction+ if outcome.segments is not None:+ reply["segments"] = outcome.segmentsreturn reply@@ -169,7 +171,7 @@ async def run(request: Request) -> Response:shutil.rmtree(scratch, ignore_errors=True)execute.release(slot)- source = scratch / ("input.jsonl" if header["mode"] == "package" else "document")+ source = scratch / ("input.parquet" if header["mode"] == "package" else "document")try:parts = [(source, header["input_bytes"])]if header["mode"] == "extract" and header.get("cache_bytes"):diff --git a/tests/conftest.py b/tests/conftest.pyindex fa8fd444..0881a395 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -333,66 +333,9 @@ def frozen_dataset(project, rows=None, *, capability=None, name="ds", contract=N)land.land_rows(dataset, [_lift_messages(r) for r in rows], user=user)dataset.refresh_from_db()- review_fixture(dataset)return dataset-def plan_fixture(dataset, cell=None):- from overbae.models import Cell-- cell = cell or dataset.active_cell- plan = {- "id": str(cell.pk),- "specification": {- "checks": [- {- "name": name,- "category": category,- "method": "deterministic",- "question": "Controlled fixture",- }- for name, category in {- "task_alignment": "semantic",- "input_evidence": "preservation",- "answer_support": "semantic",- "output_schema": "technical",- }.items()- ]- },- }- cell.preparation_plan = plan- Cell.objects.filter(pk=cell.pk).update(preparation_plan=plan)- return plan---def review_fixture(dataset, cell=None, *, failed=None, unknown=None):- from overbae.models import Cell- from overbae.services.datasets.context import context_fingerprint-- cell = cell or dataset.active_cell- plan = plan_fixture(dataset, cell)- # Consumer tests load a recorded review; the platform no longer runs semantic judges.- report = {- "fingerprint": cell.fingerprint,- "context_fingerprint": context_fingerprint(dataset.capability),- "intent": dataset.intent,- "plan_id": plan["id"],- "audit": {"method": "row_results"},- "checks": [- {- "name": name,- "result": "fail" if name == failed else "unknown" if name == unknown else "pass",- "evidence": "Known test fixture.",- "rows_checked": cell.rows,- }- for name in ("task_alignment", "input_evidence", "answer_support", "output_schema")- ],- }- cell.quality_report = report- Cell.objects.filter(pk=cell.pk).update(quality_report=report)- return report--def import_version(dataset, records, *, name="Native transformation"):from unittest.mock import patchfrom uuid import uuid4@@ -405,9 +348,7 @@ def import_version(dataset, records, *, name="Native transformation"):from overbae.models import Datasetfrom overbae.services.datasets import land- artifact = Dataset.objects.create(- project=dataset.project, name="Native artifact", intent="explore"- )+ artifact = Dataset.objects.create(project=dataset.project, name="Native artifact")land.land_rows(artifact, records)imported = {"artifact_cell": artifact.source.pk,diff --git a/tests/coverage_map.py b/tests/coverage_map.pyindex 9d80c8ee..32f7d2fd 100644--- a/tests/coverage_map.py+++ b/tests/coverage_map.py@@ -240,7 +240,9 @@ COVERAGE_MAP: dict[str, Entry] = {"A turn runs from a message to the reply and saves every step: a turn that stopped ""moving is marked interrupted and writes nothing more, a stop ends it at the next ""step, a question ends it, and a dataset's deletion removes its copies from the "- "workspace.",+ "workspace. A publish runs its package on a sample first and publishes nothing when "+ "the sample fails; the first message carries each version's fit and profile; a "+ "dataset made with an intent or a brief queues one first pass, one for a split.",),"assistant-api": Entry(S1,diff --git a/tests/journeys/test_data.py b/tests/journeys/test_data.pyindex d757cd76..7a05c811 100644--- a/tests/journeys/test_data.py+++ b/tests/journeys/test_data.py@@ -124,7 +124,7 @@ def use_freezes_an_uploaded_eval_source(console, workshop, project, worker, tmp_console.fill("#dataset-name", "Console upload")console.upload('[role="dialog"] input[type="file"]', tickets(tmp_path))console.sees("3 rows")- console.choose("#dataset-purpose", "Evaluation")+ console.choose("#dataset-intent", "Eval")console.press("Create dataset")def landed():@@ -162,7 +162,7 @@ def show_upload_bytes_until_publication(console, workshop, rest, project, worker"start_dataset", {"name": "Live upload", "brief": "Inspect uploaded rows"})["dataset"]["id"]console.goto(f"/datasets?projectId={project}")- console.sees("Waiting for source")+ console.sees("Live upload")data = b'[{"value":1},{"value":2}]'receipt = rest.request("POST",@@ -194,7 +194,6 @@ def show_upload_bytes_until_publication(console, workshop, rest, project, worker)rest.request("POST", f"/api/dataset-transfers/{receipt['id']}/complete/", json={})drain(worker)- console.sees("Ready")console.wait_until("() => !document.body.textContent.includes('Uploading') && [...document.querySelectorAll('td')].some(cell => cell.textContent === '2')")@@ -259,11 +258,19 @@ def keep_the_brief_when_the_cli_attaches_data()console.goto(f"/datasets/{dataset}?projectId={project}")console.sees("Retry rows")- console._browser.call(- lambda: console._page.get_by_role("searchbox", name="Search rows", exact=True).fill(- "Refund order 0"- )- )++ # The searched page must fail while the routes are still blocked; if its request went+ # out after unroute it would succeed and leave no Retry rows button to press.+ def search_fails():+ with console._page.expect_event(+ "requestfailed", predicate=lambda request: "search=Refund" in request.url+ ):+ console._page.get_by_role("searchbox", name="Search rows", exact=True).fill(+ "Refund order 0"+ )++ console._browser.call(search_fails)+ console.sees("Retry rows")console.save_evidence("dataset-rows-retry")console._browser.call(lambda: console._page.unroute("**/api/datasets/*/rows/**"))console.press("Retry rows")@@ -379,7 +386,7 @@ def open_traces_selected_in_the_console(console, workshop, project, live_api, wof"() => location.pathname === '/datasets/{dataset['id']}' ""&& !!document.querySelector('article [data-cell-frame]')")- console.sees("Intent pending", exact=False)+ console.sees("Not set", exact=False)console._browser.call(lambda: console._page.get_by_role("group", name="Prepare with coding agent", exact=True@@ -433,7 +440,6 @@ def read_a_scanned_document_once_per_page(workshop, cli, sample_agent, worker):{"brief": "Keep document evidence for OCR verification.","name": f"OCR source {number}",- "intent": "explore",},)["dataset"]["id"]workshop.call("update_dataset", {"dataset": draft, "ocr_languages": ["eng"]})@@ -510,7 +516,6 @@ def publish_version_bound_analytics(workshop, cli, sample_agent, rest, worker, tnext(c for c in report["checks"] if c["id"] == "targets.class_balance")["status"]== "warning")- assert receipt["progress"]["analytics"]["fingerprint"] == report["fingerprint"]rest_cell = next(cfor c in rest.request("GET", f"/api/datasets/{dataset}/")["cells"]@@ -611,4 +616,7 @@ def a_failed_preparation_is_repaired_from_the_console()console.save_evidence("dataset-preparation-repaired")console.goto(f"/datasets?projectId={project}")- console.sees("Ready")+ # An idle row shows its name alone: the repaired dataset no longer reads Failed.+ console.wait_until(+ "() => document.querySelector('tbody tr') && !document.body.textContent.includes('Failed')"+ )diff --git a/tests/journeys/test_observe.py b/tests/journeys/test_observe.pyindex 5dfd0a04..7497198d 100644--- a/tests/journeys/test_observe.py+++ b/tests/journeys/test_observe.py@@ -386,7 +386,7 @@ def show_agent_changes_without_reload(console, mcp, project):console._browser.call(console._page.evaluate, "window.activityDocument = 'unchanged'")dataset = mcp.call("start_dataset",- {"name": "Live agent source", "brief": "Review live agent changes", "intent": "explore"},+ {"name": "Live agent source", "brief": "Review live agent changes"},)["dataset"]["id"]console.sees("Live agent source")mcp.call("update_dataset", {"dataset": dataset, "name": "Renamed live source"})diff --git a/tests/test_assistant_turn.py b/tests/test_assistant_turn.pyindex d4f0ad42..32acf898 100644--- a/tests/test_assistant_turn.py+++ b/tests/test_assistant_turn.py@@ -4,11 +4,12 @@ from datetime import timedeltaimport pytestfrom conftest import frozen_datasetfrom django.utils import timezone-from factories import make_project, make_user+from factories import auth_client, make_capability, make_project, make_userfrom fakes.llm import tool_callfrom overbae.core.llms import stream_llm_toolsfrom overbae.models import (+ AssistantInput,AssistantThread,BillingTelemetry,Dataset,@@ -16,8 +17,8 @@ from overbae.models import (ProjectMembership,)from overbae.services import workspaces-from overbae.services.assistant import log, threads, turn-from overbae.services.datasets import lifecycle, list_activity+from overbae.services.assistant import log, threads, tools, turn+from overbae.services.datasets import land, lifecycle, list_activityfrom overbae.tasks import assistant as assistant_taskspytestmark = [pytest.mark.django_db, pytest.mark.covers("assistant-turn")]@@ -205,6 +206,95 @@ def test_one_call_retains_a_pipeline_and_runs_it_and_a_correction_is_its_next_reassert not failed["ok"] and failed["content"]["error"]+def test_a_publish_runs_a_sample_first_and_a_failing_sample_publishes_nothing(+ fake_llm, user, eager+):+ project = make_project(member=user)+ rows = [{"input": f"q{i}", "expected_output": "a"} for i in range(tools.SAMPLE_ROWS + 1)]+ thread = threads.open_thread(frozen_dataset(project, rows, user=user))+ source = thread.dataset.source+ manifest = {"version": 1, "steps": [{"name": "Break", "entrypoint": "break.py"}]}+ files = {"manifest.json": json.dumps(manifest), "break.py": "raise SystemExit('broken')\n"}+ call = {"summary": "Publishing", "source_cell": str(source.pk), "mode": "publish"}+ fake_llm.stream_rounds(+ [([tool_call("run_pipeline", {**call, "name": "Break", "files": files})], ""), ([], "")]+ )+ say(thread, user, "Prepare it.")++ (failed,) = results(thread)+ assert not failed["ok"] and failed["content"]["sample"] and failed["content"]["error"]+ (run,) = DatasetPipeline.objects.get().datasetpipelinerun_set.all()+ assert (run.mode, run.state) == ("preview", "failed")+ thread.dataset.refresh_from_db()+ assert thread.dataset.active_cell == source+++def test_the_first_message_carries_each_versions_fit_profile_and_the_capability_contract(user):+ project = make_project(member=user)+ capability = make_capability(+ project,+ "Support",+ improvement_metadata={"capability_card": {"system_prompt": "Answer tickets."}},+ )+ reply = [{"role": "user", "content": "Hi"}, {"role": "assistant", "content": "Hello"}]+ rows = [{"messages": reply, "queue": "billing"}] * 2 + [+ {"messages": reply[:1] + [{"role": "assistant", "content": "Bye"}], "queue": "tech"}+ ]+ dataset = frozen_dataset(project, rows, user=user, capability=capability)+ brief = threads.brief(threads.open_thread(dataset))++ assert brief["capability"]["system_prompt"] == "Answer tickets."+ source = brief["source"]+ assert source["fit"]["sft"]["ok"] and not source["fit"]["decision"]["ok"]+ assert source["duplicate_rows"] == 1+ queue = next(column for column in source["columns"] if column["name"] == "queue")+ assert queue["distinct"] == 2 and queue["top"][0] == {"value": "billing", "count": 2}+++def test_a_dataset_made_with_an_intent_queues_one_first_pass_and_a_split_one_for_both(user):+ project = make_project(member=user)+ client = auth_client(user)+ body = {+ "project": str(project.pk),+ "name": "Tickets",+ "brief": "Keep the tone.",+ "prepare": True,+ "source": {"rows": [{"text": f"t{i}"} for i in range(4)]},+ }+ made = client.post("/api/datasets/", {**body, "intent": "train"}, format="json").data+ (message,) = AssistantInput.objects.filter(thread__dataset_id=made["id"])+ assert message.text == f"{threads.FIRST_PASS['train']}\n\nKeep the tone."+ assert message.state == AssistantInput.State.QUEUED++ plain = client.post("/api/datasets/", {**body, "prepare": False}, format="json").data+ assert not AssistantThread.objects.filter(dataset_id=plain["id"]).exists()++ split = {**body, "name": "Pair", "eval_percent": 50, "position": "tail"}+ pair = client.post("/api/datasets/split/", split, format="json").data+ (first,) = AssistantInput.objects.filter(thread__dataset_id=pair["train"]["id"])+ assert first.text.startswith(threads.SPLIT_PASS)+ assert not AssistantThread.objects.filter(dataset_id=pair["eval"]["id"]).exists()+++def test_a_first_pass_waits_through_a_failed_import_for_a_landed_source(+ user, woken, django_capture_on_commit_callbacks+):+ project = make_project(member=user)+ dataset = Dataset.objects.create(+ project=project, name="t", intent="train", state=Dataset.State.ERROR+ )+ message = threads.queue_first_pass(dataset, user)+ thread = message.thread+ turn.run(thread.pk)+ message.refresh_from_db()+ assert message.state == AssistantInput.State.QUEUED and not thread.events.exists()++ land.land_rows(dataset, [{"text": "a"}])+ with django_capture_on_commit_callbacks(execute=True):+ turn.wake_dataset(dataset.pk)+ assert woken == [str(thread.pk)]++def test_a_kernel_that_restarted_is_told_to_the_model(fake_llm, user, thread):provider = workspaces.provider()project, conversation = str(thread.project_id), thread.pk.hexdiff --git a/tests/test_data_first_workflow.py b/tests/test_data_first_workflow.pyindex c974634b..57968441 100644--- a/tests/test_data_first_workflow.py+++ b/tests/test_data_first_workflow.py@@ -322,7 +322,7 @@ def test_native_agent_imports_declared_mean_without_inventing_probabilities(settassert next(store.iter_rows(paths.cell_path(dataset.pk, source.pk))) == original-def test_changing_an_existing_mean_records_semantic_impact_and_preserves_source():+def test_changing_an_existing_mean_publishes_a_version_and_preserves_source():project = Project.objects.create(name="Mean review", slug="mean-review")dataset = Dataset.objects.create(project=project, name="Means", intent="train")@@ -343,7 +343,6 @@ def test_changing_an_existing_mean_records_semantic_impact_and_preserves_source(assert next(rows.iter_rows(dataset.source)).extra["decision"]["target_mean"] == 0.4assert next(rows.iter_rows(dataset.active_cell)).extra["decision"]["target_mean"] == 0.9assert dataset.active_cell.review["execution"] == "external_attributed"- assert dataset.active_cell.review["decision_changes"] == 1def test_demo_model_workflows_remain_terminal_and_reset_without_provider_work():diff --git a/tests/test_dataset_api.py b/tests/test_dataset_api.pyindex b575c0ff..6768b767 100644--- a/tests/test_dataset_api.py+++ b/tests/test_dataset_api.py@@ -7,7 +7,7 @@ import uuidfrom unittest.mock import patchimport pytest-from conftest import EVAL_ROWS, import_version, review_fixture+from conftest import EVAL_ROWS, import_versionfrom rest_framework.test import APIClientfrom rest_framework_simplejwt.tokens import RefreshToken@@ -211,7 +211,6 @@ def test_preparation_names_an_optimizer_experiment_by_its_capability():intent="eval",capability=str(capability.id),)- review_fixture(dataset)cell = use.use(dataset, "eval")experiment = OptimizerExperiment.objects.create(project=project, capability=capability, dataset=dataset, cell=cell, entrypoint="answer"@@ -233,7 +232,6 @@ def test_delete_refused_while_a_version_is_used():project = _project()client = _client(project)dataset = _create(client, project, rows=[dict(r) for r in EVAL_ROWS], intent="eval")- review_fixture(dataset)use.use(dataset, "eval")res = client.delete(f"/api/datasets/{dataset.id}/")assert res.status_code == 409 and res.data["code"] == "dataset_referenced"@@ -280,3 +278,13 @@ def test_another_project_reads_and_writes_nothing():res = outsider.get("/api/datasets/", {"project": str(project.id)})assert res.status_code == 200 and res.data["results"] == []assert Dataset.objects.filter(pk=dataset.pk, name="ds").exists()+++def test_an_intent_only_patch_keeps_the_training_format():+ project = _project()+ client = _client(project)+ dataset = _create(client, project)+ url = f"/api/datasets/{dataset.id}/"+ client.patch(url, {"intent": "train", "train_format": "decision"}, format="json")+ assert client.patch(url, {"intent": "train"}, format="json").data["train_format"] == "decision"+ assert client.patch(url, {"intent": "eval"}, format="json").data["train_format"] == ""diff --git a/tests/test_dataset_chain.py b/tests/test_dataset_chain.pyindex f6eba0c7..02810b2d 100644--- a/tests/test_dataset_chain.py+++ b/tests/test_dataset_chain.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport uuidimport pytest-from conftest import EVAL_ROWS, TRAIN_ROWS, frozen_dataset, import_version, review_fixture+from conftest import EVAL_ROWS, TRAIN_ROWS, frozen_dataset, import_versionfrom overbae.models import Capability, Cell, Dataset, EvalRun, Projectfrom overbae.services.datasets import diff, land, lifecycle, paths, store, use@@ -115,7 +115,6 @@ def test_use_marks_the_cell_and_starts_a_new_major(django_assert_num_queries):name="Shape",)shape.refresh_from_db()- review_fixture(dataset, shape)cell = use.use(dataset, "eval")assert cell == shape and cell.used_at is not Noneassert dataset.versions()[shape.id] == "2.0"@@ -153,7 +152,6 @@ def test_versions_see_a_use_made_after_the_cells_were_prefetched():def test_a_used_cell_is_protected_and_blocks_deletion():project = _project()dataset = _landed(project, [dict(r) for r in EVAL_ROWS], intent="eval")- review_fixture(dataset)cell = use.use(dataset, "eval")EvalRun.objects.create(project=project, name="r", dataset=dataset, cell=cell)assert "used by runs" in lifecycle.delete_blocked_reason(dataset)diff --git a/tests/test_dataset_consumer_contract.py b/tests/test_dataset_consumer_contract.pyindex f667d885..eedcf191 100644--- a/tests/test_dataset_consumer_contract.py+++ b/tests/test_dataset_consumer_contract.py@@ -8,10 +8,12 @@ from factories import make_matrix_rowfrom overbae.innermind import generation, runsfrom overbae.models import Capability, Dataset, EvalRun, Project-from overbae.services.datasets import alignment, contract, land, paths, review, rows, store, use+from overbae.services.datasets import alignment, contract, land, lineage, paths, rows, store, usefrom overbae.services.datasets.examples import prepare_examples-from overbae.services.datasets.partition import contamination_keys, split_rows+from overbae.services.datasets.partition import contamination_keys+from overbae.services.datasets.pipeline_execution import Parents, carryfrom overbae.services.datasets.sampling import select_rows+from overbae.services.finetuning_split import split_datapoint_idspytestmark = pytest.mark.covers("data-logic")@@ -143,27 +145,28 @@ def test_prepared_request_keeps_prior_assistant_context_on_repeat_preparation():def test_lineage_survives_projection_and_keeps_related_rows_in_one_split(tmp_path):- original = pd.DataFrame([{**example(i), "source_row": i} for i in range(6)])- shaped = pd.DataFrame(- [{"source_row": i, "input": f"rephrased {i}", "expected_output": "yes"} for i in range(6)]- )- original_rows = original.to_dict(orient="records")- before, after, destination = (- tmp_path / f"{name}.parquet" for name in ("before", "after", "output")- )+ original_rows = [{**example(i), "source_row": i} for i in range(6)]+ before, after = tmp_path / "before.parquet", tmp_path / "after.parquet"store.write_rows(before, original_rows)- store.write_rows(after, shaped.to_dict(orient="records"))- review.preserve_file_provenance(before, after, destination)- shaped_rows = list(store.iter_rows(destination))- assert all(- contamination_keys(a) & contamination_keys(b)- for a, b in zip(original_rows, shaped_rows, strict=True)- )- training, evaluation, _ = split_rows(- original_rows + shaped_rows, eval_percent=30, position="random"+ lineage.write(before, ((row["source_row"], lineage.own_keys(row)) for row in original_rows))+ shaped = [+ {"source_row": i, "input": f"rephrased {i}", "expected_output": "yes"} for i in range(6)+ ]+ inherited = []+ parents = Parents([(before, lineage.load(before))], ())+ store.write_rows(after, carry(shaped, parents, inherited))+ shaped_keys = [+ lineage.own_keys(row) | parent+ for row, parent in zip(store.iter_rows(after), inherited, strict=True)+ ]+ original_keys = [lineage.own_keys(row) for row in original_rows]+ assert all(a <= b for a, b in zip(original_keys, shaped_keys, strict=True))+ datapoints = [{"id": f"o{i}", "extra": row} for i, row in enumerate(original_rows)]+ datapoints += [{"id": f"s{i}", "extra": row} for i, row in enumerate(shaped)]+ training, evaluation, _ = split_datapoint_ids(+ datapoints, 0.3, lineage=original_keys + shaped_keys)- train_keys = set().union(*(contamination_keys(row) for row in training))- assert not any(train_keys & contamination_keys(row) for row in evaluation)+ assert {i[1:] for i in training}.isdisjoint({i[1:] for i in evaluation})def test_identifier_only_inputs_warn_without_failing_the_format_contract():@@ -174,14 +177,6 @@ def test_identifier_only_inputs_warn_without_failing_the_format_contract():assert "without evidence" in report["eval"]["warnings"][0]-def test_projecting_domain_evidence_to_an_identifier_is_a_reviewed_change():- before = pd.DataFrame(- [{"source_row": 0, "input": {"case_id": "one", "documents": ["evidence"]}}]- )- after = pd.DataFrame([{"source_row": 0, "input": {"case_id": "one"}}])- assert review.impact(before, after)["input_evidence_removed"] == 1--def test_model_transcript_is_not_validated_as_an_application_entry_point():capability = SimpleNamespace(improvement_metadata={@@ -218,8 +213,7 @@ def test_mechanical_preparation_and_context_loss_record_impact_and_keep_source()lost_rows = list(store.iter_rows(paths.cell_path(dataset.pk, active.pk)))for row in lost_rows:row["input"] = {"onboarding_packet_id": "case-1"}- lost = import_version(dataset, lost_rows, name="Identifier projection")- assert lost.review["input_evidence_removed"] == 1+ import_version(dataset, lost_rows, name="Identifier projection")assert use.use(dataset, "eval", cell=active).id == active.idassert store.head(paths.cell_path(dataset.id, active.id), 1)[0]["input"]["messages"]diff --git a/tests/test_dataset_context.py b/tests/test_dataset_context.pyindex 5986b5d9..6d320bd3 100644--- a/tests/test_dataset_context.py+++ b/tests/test_dataset_context.py@@ -6,7 +6,7 @@ import pytestfrom conftest import import_versionfrom overbae.models import Dataset, Project-from overbae.services.datasets import contract, land, review, rows, store+from overbae.services.datasets import contract, land, rows, storefrom overbae.services.datasets.context import workshop_contextfrom overbae.services.datasets.examples import prepare_examplesfrom overbae.services.datasets.profile import profile_records@@ -79,7 +79,7 @@ def test_encoded_wire_fields_are_normalised_without_modifying_text_or_source(source["messages"] = json.dumps(source["messages"])prepared = prepare_examples(pd.DataFrame([source]), intent)path = tmp_path / "frame.parquet"- store.write_frame(path, prepared)+ store.write_rows(path, prepared.to_dict(orient="records"))persisted = next(store.iter_rows(path))assert contract.measure(frame_of([persisted]))[intent]["ok"]product_row = rows.row_from_record(0, persisted)@@ -127,7 +127,7 @@ def test_invalid_tools_fail_even_when_no_assistant_calls_them(bad_tools, frame_o@pytest.mark.django_db@pytest.mark.parametrize("intent", ["train", "eval"])-def test_replacing_existing_instructions_records_semantic_impact_and_preserves_source(intent):+def test_replacing_existing_instructions_publishes_a_new_version_and_preserves_source(intent):project = Project.objects.create(name="Context", slug="context")dataset = Dataset.objects.create(project=project, name="Mixed tasks", intent=intent)records = prepare_examples(pd.DataFrame([example(), example("Apply rules")]), intent)@@ -139,18 +139,11 @@ def test_replacing_existing_instructions_records_semantic_impact_and_preserves_sfor row in prepared:transcript = row["messages"] if intent == "train" else row["input"]["messages"]transcript[0]["content"] = "Do everything"- output = import_version(dataset, prepared, name="Replace instructions")- assert output.review["instruction_changes"] == 2+ import_version(dataset, prepared, name="Replace instructions")dataset.refresh_from_db()assert dataset.active_cell.id != dataset.source.id- assert len(workshop_context(dataset)["profiles"]["source"]["families"]) == 2---def test_representation_changes_and_projection_do_not_look_like_scope_changes(frame_of):- before = pd.DataFrame([example(source_row=0, tools=json.dumps([tool()]))])- after = prepare_examples(before, "eval")- changes = review.impact(frame_of(before.to_dict("records")), frame_of(after.to_dict("records")))- assert changes["instruction_changes"] == 0+ source = workshop_context(dataset)["profiles"]["source"]+ assert source["cell"] == str(dataset.source.id) and source["columns"]def test_decision_profiles_count_raw_and_native_targets_and_source_families():@@ -180,18 +173,15 @@ def test_decision_profiles_count_raw_and_native_targets_and_source_families():@pytest.mark.django_db-def test_workshop_context_uses_profile_measured_for_the_frozen_frame(monkeypatch):+def test_workshop_context_reads_the_columns_measured_at_publication(monkeypatch):from overbae.services.datasets import contextproject = Project.objects.create(name="Cached profile", slug="cached-profile")dataset = Dataset.objects.create(project=project, name="Cached", intent="train")land.land_rows(dataset, [example(), example("Second task")])- monkeypatch.setattr(- context, "profile_records", lambda *a: pytest.fail("Re-scanned immutable frame")- )+ monkeypatch.setattr(store, "iter_rows", lambda *a, **k: pytest.fail("Re-scanned the frame"))profile = context.workshop_context(dataset)["profiles"]["source"]- assert profile["rows_scanned"] == 2 and len(profile["families"]) == 2- assert profile["fingerprint"] == dataset.source.fingerprint+ assert profile["rows"] == 2 and profile["columns"] == dataset.source.columns@pytest.mark.parametrize(diff --git a/tests/test_dataset_contract.py b/tests/test_dataset_contract.pyindex 99866671..500bf604 100644--- a/tests/test_dataset_contract.py+++ b/tests/test_dataset_contract.py@@ -100,3 +100,23 @@ def test_a_transcript_that_landing_cut_does_not_fit_train():report = contract.measure(pd.DataFrame([row, {"messages": TURNS}]))["train"]assert report["ok"] is Falseassert report["failures"] == [{"row": 0, "reason": "a value was cut at landing"}]+++def test_a_batched_eval_output_is_judged_by_every_frame():+ decision = {+ "decision": {"state": "s", "question": "q?", "kind": "choice", "options": ["a", "b"]}+ }+ reference = {"probabilities": [1.0, 0.0]}+ referenced = pd.DataFrame([{"input": decision, "expected_output": reference}])++ def frames(*parts):+ return contract.measure_frames(+ ((part, None) for part in parts), ["input", "expected_output"]+ )++ # A later frame's decision without a reference fails the output.+ unreferenced = pd.DataFrame([{"input": decision, "expected_output": None}])+ assert not frames(referenced, unreferenced)["eval"]["ok"]+ # A text frame without references still counts its input type.+ text = pd.DataFrame([{"input": "plain question", "expected_output": None}])+ assert set(frames(referenced, text)["eval"]["input_types"]) == {"decision", "text"}diff --git a/tests/test_dataset_fingerprints.py b/tests/test_dataset_fingerprints.pyindex 018bd556..7f1acd6b 100644--- a/tests/test_dataset_fingerprints.py+++ b/tests/test_dataset_fingerprints.py@@ -1,6 +1,8 @@import pytest-from overbae.services.datasets.partition import contamination_keys, content_key, preserve_lineage+from overbae.models import Dataset, Project+from overbae.services.datasets import land, lineage, paths, store+from overbae.services.datasets.partition import contamination_keys, content_keypytestmark = pytest.mark.covers("data-logic")@@ -47,7 +49,14 @@ def test_corrected_fingerprints_do_not_discard_retained_lineage_or_declared_grou}transformed = {"input": "different representation",- "_overmind_provenance": preserve_lineage(original),+ "_overmind_provenance": {+ "source_content_keys": sorted(+ v for k, v in contamination_keys(original) if k == "content"+ ),+ "source_group_keys": sorted(+ [k, v] for k, v in contamination_keys(original) if k != "content"+ ),+ },}assert contamination_keys(original) <= contamination_keys(transformed)@@ -75,3 +84,103 @@ def test_call_origin_and_trace_identity_detect_contamination():a = {"origin_trace_id": "shared", "input": "first turn"}b = {"trace_id": "shared", "input": "later turn"}assert contamination_keys(a) & contamination_keys(b)+++GOLDEN_ROWS = [+ {+ "messages": [+ {"role": "system", "content": "Be brief."},+ {"role": "user", "content": "Reset my password"},+ {"role": "assistant", "content": "Done."},+ ],+ "trace_id": "t-1",+ "conversation_id": "c-9",+ },+ {+ "decision": {+ "state": '{"x": 1}',+ "question": "Approve?",+ "kind": "choice",+ "options": ["yes", "no"],+ "target_probabilities": [1.0, 0.0],+ },+ "group_id": "g-2",+ },+ {+ "input": {"question": "What is 2 + 2?", "case_id": "k-7"},+ "expected_output": "4",+ "metadata": {"packet_id": 12},+ },+ {+ "ticket": "T-1",+ "total": 12.5,+ "items": [{"sku": "S1", "qty": 2}],+ "note": None,+ "source_row": 3,+ },+ {+ "text": "Ünïcode text",+ "customer": "acme",+ "_overmind_provenance": {+ "source_content_keys": ["abc"],+ "source_group_keys": [["trace_id", '"t-0"']],+ },+ },+]+# Computed by the platform before lineage moved to key files. Leakage checks compare keys+# across cells of every age, so these strings may never change.+GOLDEN_KEYS = [+ [+ ["content", "8e4e8524078f2f85c59d161eeeec92c44602f1222e438d3317f58fb00c431653"],+ ["conversation_id", '"c-9"'],+ ["trace_id", '"t-1"'],+ ],+ [+ ["content", "04632979516b3f1ea7eecfd7e3e88358f9a2315cfe02b836820ab6ce5e5d76fe"],+ ["group_id", '"g-2"'],+ ],+ [+ ["case_id", '"k-7"'],+ ["content", "1de78e966a1f4a9d625eb75f1c2b994e24262dee91d72a9afa3f9d62c712c837"],+ ["packet_id", "12"],+ ],+ [["content", "record:v1:e0bb62b9f80a5b617e7645c4dfc9404fc0eb8ceaad14bcce4e4b66cf0def9ef3"]],+ [+ ["content", "abc"],+ ["content", "record:v1:c258a22b88361fbc0924e0218f483df2ba4fd0297b80e70a62b51874a5bf1b06"],+ ["customer", '"acme"'],+ ["trace_id", '"t-0"'],+ ],+]+++def test_lineage_keys_keep_their_exact_strings():+ assert [+ sorted(map(list, contamination_keys(row, ("customer",)))) for row in GOLDEN_ROWS+ ] == GOLDEN_KEYS+++def test_a_landed_cell_keys_every_row_as_it_is_stored():+ project = Project.objects.create(name="Keys", slug="keys")+ dataset = Dataset.objects.create(project=project, name="Keys")+ land.land_rows(+ dataset, [{k: v for k, v in row.items() if k != "source_row"} for row in GOLDEN_ROWS[:4]]+ )+ frame = paths.cell_path(dataset.pk, dataset.source.pk)+ assert [keys for _, keys in lineage.read(dataset.source)] == [+ lineage.own_keys(row) for row in store.iter_rows(frame)+ ]+++def test_a_frame_written_before_key_files_takes_its_keys_from_stored_provenance():+ project = Project.objects.create(name="Old keys", slug="old-keys")+ dataset = Dataset.objects.create(project=project, name="Old keys")+ land.land_rows(dataset, [{"text": "x"}])+ frame = paths.cell_path(dataset.pk, dataset.source.pk)+ store.write_rows(frame, [{**GOLDEN_ROWS[4], "source_row": 0}])+ lineage.keys_path(frame).unlink()+ assert lineage.read(dataset.source) == [+ (0, frozenset(map(tuple, GOLDEN_KEYS[4])) - {("customer", '"acme"')})+ ]diff --git a/tests/test_dataset_import_receipts.py b/tests/test_dataset_import_receipts.pyindex 29eaddf6..247abbf5 100644--- a/tests/test_dataset_import_receipts.py+++ b/tests/test_dataset_import_receipts.py@@ -201,13 +201,13 @@ def test_stale_import_cannot_write_or_publish_landing_progress(imported_source,DatasetImport.objects.filter(pk=run.pk).update(owner=uuid.uuid4())published = []monkeypatch.setattr(imports.events, "publish", lambda *args: published.append(args))- imports._read_parts(stale, [dataset])+ imports._read_parts(stale, [dataset], imports._landing_progress(stale, [dataset]))dataset.refresh_from_db()assert dataset.source_spec == original_specassert published == []run.refresh_from_db()- imports._read_parts(run, [dataset])+ imports._read_parts(run, [dataset], imports._landing_progress(run, [dataset]))dataset.refresh_from_db()assert dataset.source_spec["landing_progress"]["completed"] == 1assert publisheddiff --git a/tests/test_dataset_land_traces.py b/tests/test_dataset_land_traces.pyindex 671bbac5..8bfe358b 100644--- a/tests/test_dataset_land_traces.py+++ b/tests/test_dataset_land_traces.py@@ -86,8 +86,7 @@ def test_one_row_per_trace_in_selection_order_with_the_fixed_columns():first, _ = _chat_trace(project, text="one", capability=capability)second, _ = _chat_trace(project, text="two", capability=capability)dataset, df = _land(project, {"trace_ids": [second, first, second]})- assert [column for column in df.columns if column != "_overmind_provenance"] == COLUMNS- assert df["_overmind_provenance"].map(bool).all()+ assert list(df.columns) == COLUMNSassert df["trace_id"].tolist() == [second, first]row = df.iloc[0]assert (row["capability"], row["capability_id"]) == ("Concierge", str(capability.id))diff --git a/tests/test_dataset_query_capacity.py b/tests/test_dataset_query_capacity.pyindex a45e5d02..8aea6df6 100644--- a/tests/test_dataset_query_capacity.py+++ b/tests/test_dataset_query_capacity.py@@ -17,7 +17,7 @@ pytestmark = [pytest.mark.django_db, pytest.mark.covers("capacity")]def test_missing_query_admission_backend_is_retryable_and_does_not_change_the_source(settings):user = make_user()project = make_project(member=user)- dataset = Dataset.objects.create(project=project, name="retained", intent="explore")+ dataset = Dataset.objects.create(project=project, name="retained")land.land_rows(dataset, [{"value": 1}], user=user)dataset.refresh_from_db()_, token = APIToken.create_for_user(user, project=project)diff --git a/tests/test_dataset_scale.py b/tests/test_dataset_scale.pyindex ffc6d90a..7d776916 100644--- a/tests/test_dataset_scale.py+++ b/tests/test_dataset_scale.py@@ -1,15 +1,27 @@-"""A 20,000-row table moves through landing, a cell, paging and the diff inside+"""Tables move through landing, a cell, paging, the diff and a sandboxed pipeline insidebudgets a per-row Python loop or a quadratic join would miss by a wide margin."""from __future__ import annotations+import io+import jsonimport timeimport uuid+import zipfile+from unittest import mockimport pytestfrom overbae.models import Dataset, Project-from overbae.services.datasets import diff, land, paths, store+from overbae.services.datasets import (+ diff,+ land,+ paths,+ pipeline_packages,+ pipeline_runner,+ store,+ workbench,+)pytestmark = [pytest.mark.django_db, pytest.mark.load, pytest.mark.covers("capacity")]ROWS = 20_000@@ -55,3 +67,72 @@ def test_twenty_thousand_transcripts_land_run_page_and_diff_within_budget():assert len(page["rows"]) == 50summary = _timed(2, lambda: diff.summary(before, after))assert summary["rows_removed"] == ROWS - cell.rows+++DECIDE = """import json, sys+with open(sys.argv[1]) as source, open(sys.argv[2], "w") as output:+ for line in source:+ row = json.loads(line)+ row["decision"] = {"state": json.dumps(row["items"]), "question": "Status?",+ "kind": "choice", "options": ["shipped", "refunded"],+ "target_probabilities": [float(row["status"] == "shipped"), float(row["status"] == "refunded")]}+ output.write(json.dumps(row) + "\\n")+"""+++def test_three_hundred_thousand_orders_land_and_publish_a_batched_script_within_budget(tmp_path):+ rows = 300_000+ source = tmp_path / "orders.jsonl"+ with source.open("w") as stream:+ for i in range(rows):+ order = {+ "order_id": f"O{i:08d}",+ "customer": {"id": i % 9000, "tier": "gold" if i % 5 else None},+ "items": [{"sku": f"S{i % 400}", "qty": 1 + i % 3}] * (1 + i % 4),+ "status": "shipped" if i % 3 else "refunded",+ }+ stream.write(json.dumps(order) + "\n")+ project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")+ dataset = Dataset.objects.create(project=project, name="orders")+ _timed(60, lambda: land.commit(dataset, land.read_file(source, filename="orders.jsonl")))+ dataset.refresh_from_db()+ original = dataset.source+ manifest = {+ "version": 1,+ "runtime": pipeline_packages.runtime_id(),+ "steps": [+ {+ "consumer": "decision_train",+ "entrypoint": "decide.py",+ "id": "decide",+ "input": "source",+ "name": "Decide",+ "batch_rows": 2000,+ "checks": {"preserve_rows": True},+ }+ ],+ }+ bundle = io.BytesIO()+ with zipfile.ZipFile(bundle, "w") as archive:+ archive.writestr("manifest.json", json.dumps(manifest))+ archive.writestr("decide.py", DECIDE)+ bundle.seek(0)+ package = pipeline_packages.save(project, None, bundle)+ pipeline = workbench.save_pipeline(+ project, None, name="Decide", request_key="decide", package=package.pk, dataset=dataset+ )+ with mock.patch("overbae.tasks.datasets.execute_pipeline.delay"):+ run = workbench.submit(+ dataset,+ None,+ source_cell=original.pk,+ source_fingerprint=original.fingerprint,+ request_key="decide",+ pipeline=pipeline.pk,+ )+ _timed(180, lambda: workbench.execute(run.pk, script_executor=pipeline_runner.execute_script))+ run.refresh_from_db()+ dataset.refresh_from_db()+ assert run.state == "completed", run.error+ assert dataset.active_cell.rows == rows+ assert (dataset.intent, dataset.train_format) == ("train", "decision")diff --git a/tests/test_dataset_store.py b/tests/test_dataset_store.pyindex 34e8fd08..40d7bc2f 100644--- a/tests/test_dataset_store.py+++ b/tests/test_dataset_store.py@@ -147,17 +147,6 @@ def test_query_is_sandboxed(table):store.query("set enable_external_access = true", limit=None, t=table)-def test_write_frame_round_trips_and_hashes(table, tmp_path):- df = store.read_frame(table).assign(n=[1, 2, 3])- out = tmp_path / "p.parquet"- manifest = store.write_frame(out, df)- assert {c["name"]: c["type"] for c in manifest}["n"] == "integer"- assert store.row_count(out) == 3- first = store.file_sha256(out)- store.write_frame(out, df)- assert store.file_sha256(out) == first--def test_csv_numbers_become_numeric(tmp_path):path = tmp_path / "rows.csv"path.write_text("name,count,score,note\nA,1,1.5,x\nB,2,2.5,\n", encoding="utf-8")diff --git a/tests/test_dataset_streaming.py b/tests/test_dataset_streaming.pyindex 274d3700..75b07718 100644--- a/tests/test_dataset_streaming.py+++ b/tests/test_dataset_streaming.py@@ -4,7 +4,7 @@ import weakrefimport pytestfrom overbae.models import Dataset, Project-from overbae.services.datasets import files, land, paths, store+from overbae.services.datasets import files, land, lineage, paths, storepytestmark = pytest.mark.covers("data-logic")@@ -84,7 +84,7 @@ def test_landing_measures_every_row_without_full_frame_reads(tmp_path, settings,rows = store.iter_rows(paths.cell_path(dataset.id, source.id))first = next(rows)assert first["source_row"] == 0- assert first["_overmind_provenance"]["source_content_keys"]+ assert lineage.read(source)[0][1]last = Nonefor last in rows: # noqa: B007 — inspect the final streamed rowpass@@ -93,7 +93,7 @@ def test_landing_measures_every_row_without_full_frame_reads(tmp_path, settings,@pytest.mark.django_db-def test_batch_cell_impact_and_export_are_file_backed(tmp_path, settings, monkeypatch):+def test_batch_cell_and_export_are_file_backed(tmp_path, settings, monkeypatch):from conftest import import_versionfrom overbae.services.datasets import use@@ -104,7 +104,6 @@ def test_batch_cell_impact_and_export_are_file_backed(tmp_path, settings, monkeyrecords = [{"text": f"case {i}", "target": [0.25, 0.75]} for i in range(20_003)]land.land_rows(dataset, records)source = dataset.source- original = store.head(paths.cell_path(dataset.id, source.id), 1)[0]def forbid(*args, **kwargs):raise AssertionError("Whole-frame read in the batch lifecycle")@@ -125,15 +124,10 @@ def test_batch_cell_impact_and_export_are_file_backed(tmp_path, settings, monkeyif r["source_row"] % 3 != 1]cell = import_version(dataset, selected, name="Native")- assert cell.review["rows_removed"] == 6668- assert cell.review["identity_preserved"]assert dataset.state == "idle", dataset.errorassert cell.rows == 13_335 and cell.intent_report["train"]["ok"]first = store.head(paths.cell_path(dataset.id, cell.id), 1)[0]- assert all(- first["_overmind_provenance"][k] == v for k, v in original["_overmind_provenance"].items()- )- assert first["_overmind_provenance"]["parents"][0]["row"] == original["source_row"]+ assert lineage.read(source)[0][1] <= lineage.read(cell)[0][1]assert first["decision"]["target_probabilities"] == [0.25, 0.75]assert use.check(dataset, "train", cell=cell).id == cell.id@@ -227,7 +221,7 @@ def test_attached_files_and_replay_never_materialize_existing_frame(settings.MEDIA_ROOT = tmp_pathproject = Project.objects.create(name="Attachment streaming", slug="attachment-streaming")- dataset = Dataset.objects.create(project=project, name="Source", intent="explore")+ dataset = Dataset.objects.create(project=project, name="Source")land.land_rows(dataset, [{"text": f"evidence {i}", "group_id": str(i)} for i in range(3000)])dataset.refresh_from_db()source = dataset.sourcediff --git a/tests/test_dataset_work.py b/tests/test_dataset_work.pynew file mode 100644index 00000000..fa9aa7bb--- /dev/null+++ b/tests/test_dataset_work.py@@ -0,0 +1,73 @@+"""The work a dataset shows is the stage and counter the run or landing measured."""++import pytest+from conftest import frozen_dataset+from factories import make_project++from overbae.models import Dataset, DatasetPipelineRun+from overbae.services.datasets import land, list_activity++pytestmark = [pytest.mark.django_db, pytest.mark.covers("measured-facts")]+++def test_a_run_shows_its_stage_and_only_the_batches_the_sandbox_counted():+ dataset = frozen_dataset(make_project())+ run = DatasetPipelineRun.objects.create(+ dataset=dataset, source=dataset.source, request_key="k", state="running"+ )++ def work(stage, steps):+ DatasetPipelineRun.objects.filter(pk=run.pk).update(result={"stage": stage, "steps": steps})+ return list_activity.current_work([dataset])[str(dataset.pk)]++ batched = work("step_1_executing", [{"batches": {"completed": 3, "total": 10}}])+ assert (batched["label"], batched["completed"], batched["total"], batched["unit"]) == (+ "Transforming",+ 3,+ 10,+ "batches",+ )+ unbatched = work("step_1_executing", [{}])+ assert (unbatched["completed"], unbatched["total"]) == (None, None)+ waiting = work("step_1_executing", [{"runtime": {"stage": "waiting_for_sandbox"}}])+ assert waiting["label"] == "Waiting for sandbox"+ assert work("step_1_measuring", [{}])["label"] == "Measuring"+ DatasetPipelineRun.objects.filter(pk=run.pk).update(+ result={"stage": "step_1_measuring", "steps": [{"output_rows": 50}], "rows_done": 20}+ )+ measuring = list_activity.current_work([dataset])[str(dataset.pk)]+ assert (measuring["completed"], measuring["total"], measuring["unit"]) == (20, 50, "rows")+ assert work("publishing", [{}])["label"] == "Publishing"+++def test_a_landing_shows_the_rows_it_wrote():+ dataset = Dataset.objects.create(+ project=make_project(),+ name="big",+ state=Dataset.State.LANDING,+ source_spec={+ "landing_progress": {"stage": "writing", "rows_done": 4000, "rows_total": 10000}+ },+ )+ work = list_activity.current_work([dataset])[str(dataset.pk)]+ assert (work["label"], work["completed"], work["total"], work["unit"]) == (+ "Writing",+ 4000,+ 10000,+ "rows",+ )+++def test_landing_reports_rows_written_then_measuring(tmp_path):+ source = tmp_path / "rows.jsonl"+ source.write_text("".join(f'{{"text": "t{i}"}}\n' for i in range(2500)))+ dataset = Dataset.objects.create(project=make_project(), name="rows")+ reported = []+ land.prepare(+ dataset,+ land.read_file(source, filename="rows.jsonl"),+ path=tmp_path / "out.parquet",+ on_progress=reported.append,+ )+ assert [r.get("rows_done") for r in reported if r["stage"] == "writing"] == [0, 1000, 2000]+ assert reported[-1] == {"stage": "measuring", "rows_done": 0, "rows_total": 2500}diff --git a/tests/test_decision_workshop.py b/tests/test_decision_workshop.pyindex 8cb2a74a..dd6a9164 100644--- a/tests/test_decision_workshop.py+++ b/tests/test_decision_workshop.py@@ -5,10 +5,9 @@ import pytestfrom conftest import import_versionfrom overbae.models import Dataset, Project-from overbae.services.datasets import land, paths, store, use+from overbae.services.datasets import land, lineage, paths, store, usefrom overbae.services.datasets.examples import prepare_examplesfrom overbae.services.datasets.profile import profile_records-from overbae.services.datasets.review import decision_changedpytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]@@ -35,20 +34,6 @@ def flat(index=0, **changes):)-def test_flat_supervision_changes_are_visible_to_workshop_review():- original = flat(weight=2.5, target_semantics="posterior", target_provenance={"field": "p"})- for field, value in {- "weight": 1.0,- "target_semantics": "teacher_distribution",- "target_provenance": {"field": "teacher_p"},- }.items():- assert decision_changed(original, {**original, field: value})- prepared = prepare_examples(pd.DataFrame([original]), "train").iloc[0]["decision"]- assert prepared["weight"] == 2.5- assert prepared["target_semantics"] == "posterior"- assert prepared["target_provenance"] == {"field": "p"}--def test_flat_semantics_cannot_hide_invalid_gold_supervision():result = profile_records([flat(target_semantics="categorical_gold")])assert result["counts"].get("invalid_decision_rows", 0) == 1@@ -127,16 +112,10 @@ def test_native_preparation_keeps_empty_evidence_soft_targets_and_multiplicity(assert prepared[0]["decision"]["target_probabilities"] == [1 - 0.7, 0.7]assert prepared[0]["decision"] == prepared[1]["decision"]assert prepared[2]["decision"] == rows[2]["decision"]- original = list(store.iter_rows(paths.cell_path(ds.id, ds.source.id)))- for result_row, source_row in zip(prepared, original, strict=True):- assert all(- result_row["_overmind_provenance"][k] == v- for k, v in source_row["_overmind_provenance"].items()- )- if "parents" in result_row["_overmind_provenance"]:- assert (- result_row["_overmind_provenance"]["parents"][0]["row"] == source_row["source_row"]- )+ for (_, result_keys), (_, source_keys) in zip(+ lineage.read(cell), lineage.read(ds.source), strict=True+ ):+ assert source_keys <= result_keysassert cell.intent_report[intent]["ok"]if intent == "eval":for row in prepared:diff --git a/tests/test_document_service.py b/tests/test_document_service.pyindex e693ec9f..afdfb9db 100644--- a/tests/test_document_service.py+++ b/tests/test_document_service.py@@ -34,7 +34,7 @@ def test_parser_reports_ocr_progress_and_retained_identity():assert metadata["ocr"]["pages"] == [1]assert any(event.get("stage") == "ocr" for event in progress)assert rows[0]["_overmind_document_id"]- assert rows[0]["_overmind_provenance"]["evidence"][0]["filename"] == "scanned.pdf"+ assert rows[0]["_overmind_evidence"]["evidence"][0]["filename"] == "scanned.pdf"def test_parser_configuration_has_no_in_process_fallback(settings, tmp_path):@@ -121,7 +121,7 @@ def test_default_english_and_explicit_french_ocr(tmp_path):rows, metadata = documents.extract(path, filename=path.name, ocr_languages=["fra"])assert metadata["ocr"]["languages"] == ["fra"]assert "facture" in " ".join(row["text"] for row in rows)- assert all(row["_overmind_provenance"]["extraction"]["languages"] == ["fra"] for row in rows)+ assert all(row["_overmind_evidence"]["extraction"]["languages"] == ["fra"] for row in rows)def test_ocr_worker_budget_stays_bounded(monkeypatch):diff --git a/tests/test_mcp_workflow_friction.py b/tests/test_mcp_workflow_friction.pyindex 6fe3d6a3..baa23611 100644--- a/tests/test_mcp_workflow_friction.py+++ b/tests/test_mcp_workflow_friction.py@@ -1,5 +1,5 @@import json-from unittest.mock import Mock, patch+from unittest.mock import patchimport pytestfrom mcp_fixtures import asgi_db@@ -18,18 +18,14 @@ pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]@asgi_db-def test_mcp_inspection_is_bounded_paged_and_does_not_profile_on_read(monkeypatch):+def test_mcp_inspection_is_bounded_and_paged():project, _, dataset = workspace()cell = dataset.active_celldataset.active = celldataset.save(update_fields=["active"])cell.note = "long note " * 51cell.stats = {}- cell.quality_report = {- "checks": [],- "audit": {"script": "x" * 100000},- "audits": {str(i): {"script": "x" * 100000} for i in range(20)},- }+ cell.review = {str(i): {"script": "x" * 100000} for i in range(20)}cell.save()for i in range(1, 13):Cell.objects.create(@@ -45,10 +41,6 @@ def test_mcp_inspection_is_bounded_paged_and_does_not_profile_on_read(monkeypatckey, _ = APIToken.create_for_user(project.memberships.first().user, project=project, permission=["read", "write"])- monkeypatch.setattr(- "overbae.services.datasets.context.profile_records",- Mock(side_effect=AssertionError("Inspection scanned whole source")),- )with TestClient(create_mcp_application()) as client:found = []offset = 0@@ -107,7 +99,6 @@ def test_native_partition_members_are_ready_for_comparison_without_workshop_repafor row in store.iter_rows(paths.cell_path(cell.dataset_id, cell.id)):assert row["expected_output"] == {"probabilities": [0.35, 0.65]}assert set(row["input"]["decision"]) == {"state", "question", "kind", "options"}- assert row["_overmind_provenance"]["partition"]["role"] == rolewith patch.object(native_evaluation, "runtime", return_value={"app": "offline", "environment": "test"}):@@ -149,10 +140,7 @@ def test_inspection_remains_valid_json_for_one_wide_unicode_cell():cell.script = "界" * 8000cell.note = "界" * 512cell.columns = [{"name": "column" + str(i), "metadata": "界" * 8000} for i in range(100)]- cell.quality_report = {- "checks": [],- "audit": {("界" * 1000 + str(i)): "界" * 8000 for i in range(100)},- }+ cell.review = {("界" * 1000 + str(i)): "界" * 8000 for i in range(100)}cell.save()dataset.brief = "界" * 8000dataset.save()diff --git a/tests/test_reusable_workshop_journey.py b/tests/test_reusable_workshop_journey.pyindex a895ff98..dbfc1303 100644--- a/tests/test_reusable_workshop_journey.py+++ b/tests/test_reusable_workshop_journey.py@@ -14,6 +14,7 @@ from rest_framework.test import APIClientfrom overbae.models import APIToken, Dataset, Project, ProjectMembership, Span, Userfrom overbae.services.datasets import (+ lineage,paths,pipeline_bindings,pipeline_packages,@@ -70,11 +71,10 @@ def test_branch_fan_in_retains_every_observation_and_exact_parents(eligible):output = list(store.iter_rows(paths.cell_path(dataset.pk, cells[-1].pk)))assert sorted(row["source_row"] for row in output) == list(range(len(eligible)))assert sorted(row["eligible"] for row in output) == sorted(eligible)- for row in output:- parent = cells[0 if row["eligible"] else 1]- assert row["_overmind_provenance"]["parents"] == [- {"cell": str(parent.pk), "fingerprint": parent.fingerprint, "row": row["source_row"]}- ]+ merged = dict(lineage.read(cells[-1]))+ for parent in cells[:2]:+ for source_row, keys in lineage.read(parent):+ assert keys <= merged[source_row]assert [item["rows"] for item in cells[-1].review["inputs"]] == [eligible.count(True),eligible.count(False),@@ -318,7 +318,6 @@ def source(client, project, name, records):{"project": str(project.pk),"name": name,- "intent": "explore","source": {"rows": records},},format="json",@@ -1082,7 +1081,7 @@ with open(sys.argv[1]) as source, open(sys.argv[2], 'w') as output:assert runtime["stage_seconds"]["input_transfer"] > 0assert runtime["stage_seconds"]["output_reading"] > 0assert runtime["backend"] == "sandbox"- assert runtime["memory_limit_bytes"] >= 1024**3+ assert runtime["memory_limit_bytes"] > 0assert [step["output_rows"] for step in job["details"]["result"]["steps"]] == ([50, 50] if mode == "preview" else [5000, 5000])diff --git a/tests/test_sandbox_packages.py b/tests/test_sandbox_packages.pyindex b1fc5611..9edee55f 100644--- a/tests/test_sandbox_packages.py+++ b/tests/test_sandbox_packages.py@@ -1,11 +1,14 @@import jsonimport osimport sys+import tempfilefrom concurrent.futures import ThreadPoolExecutor+from pathlib import Pathimport httpximport pytest+from overbae.services.datasets import storefrom overbae.services.workspaces.conformance import LIBRARY_USEfrom sandbox import execute, packagesfrom sandbox.protocol import HeaderReader, header_bytes@@ -13,10 +16,16 @@ from sandbox.protocol import HeaderReader, header_bytespytestmark = pytest.mark.covers("sandbox")-def run_package(sandbox_server, code, *, limits=None, runtime=None, files=None):+def run_package(+ sandbox_server, code, *, limits=None, runtime=None, files=None, rows=None, batch_rows=None+):url, token = sandbox_serverpackage = json.dumps(files or {"step.py": code}).encode()- source = b'{"source_row": 0, "value": 9007199254740993}\n'+ rows = rows or [{"source_row": 0, "value": 9007199254740993}]+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "input.parquet"+ store.write_rows(path, rows)+ source = path.read_bytes()header = {"mode": "package","runtime": runtime or packages.runtime_id(),@@ -24,7 +33,9 @@ def run_package(sandbox_server, code, *, limits=None, runtime=None, files=None):"parameters": {},"package_bytes": len(package),"input_bytes": len(source),+ "rows": len(rows),"limits": limits or {"seconds": 20},+ **({"batch_rows": batch_rows} if batch_rows else {}),}response = httpx.post(url + "/v1/run",@@ -62,6 +73,32 @@ def test_package_runs_on_isolated_service_with_exact_rows_and_nested_modules(sanassert json.loads(payload)["value"] == 9007199254740993[email protected]("fail_last", [False, True])+def test_batches_run_one_after_another_in_fresh_processes_and_keep_order(sandbox_server, fail_last):+ code = """import json, pathlib, sys+rows = [json.loads(line) for line in open(sys.argv[1])]+if FAIL and rows[0]["source_row"] == 8:+ raise SystemExit(1)+seen = pathlib.Path("seen").exists()+pathlib.Path("seen").write_text("x")+# No final newline: each batch's last row must not join the next batch's first.+with open(sys.argv[2], "w") as output:+ output.write("\\n".join(json.dumps({**r, "batch": len(rows), "seen": seen}) for r in rows))+""".replace("FAIL", str(fail_last))+ status, result, payload = run_package(+ sandbox_server, code, rows=[{"source_row": i} for i in range(11)], batch_rows=4+ )+ assert status == 200+ if fail_last:+ assert not result["ok"] and payload == b""+ return+ assert result["ok"], result+ rows = [json.loads(line) for line in payload.splitlines()]+ assert [row["source_row"] for row in rows] == list(range(11))+ assert [row["batch"] for row in rows] == [4] * 8 + [3] * 3+ assert not any(row["seen"] for row in rows)++def test_a_package_sees_no_other_process_and_opens_no_network_socket(sandbox_server):code = """import os, socketfor attempt in (lambda: os.listdir('/proc'), lambda: open('/proc/1/cmdline'), socket.socket):diff --git a/tests/test_training_plan_workflow.py b/tests/test_training_plan_workflow.pyindex 34f3b5c5..4cea3176 100644--- a/tests/test_training_plan_workflow.py+++ b/tests/test_training_plan_workflow.py@@ -49,7 +49,7 @@ def test_mcp_training_plan_keeps_task_data_and_selection_bound(mode, settings):user = User.objects.create_user(email=f"{mode}@example.com")ProjectMembership.objects.create(project=project, user=user)key, _ = APIToken.create_for_user(user, project=project, permission=["read", "write"])- dataset = Dataset.objects.create(project=project, name="Cases", intent="explore")+ dataset = Dataset.objects.create(project=project, name="Cases")records = []for index in range(40):row = {"case_id": str(index), "language": "en"}diff --git a/tests/test_workshop_documents.py b/tests/test_workshop_documents.pyindex 155ee997..238265db 100644--- a/tests/test_workshop_documents.py+++ b/tests/test_workshop_documents.py@@ -94,7 +94,7 @@ def test_intent_first_then_source_keeps_the_original_request(source = store.read_frame(paths.cell_path(dataset.id, dataset.source.id))assert any("three days" in value for value in source["text"])assert all(source["_overmind_document_id"])- assert all(source["_overmind_provenance"].map(lambda value: bool(value["evidence"])))+ assert all(source["_overmind_evidence"].map(lambda value: bool(value["evidence"])))again = client.post(f"/api/datasets/{dataset.id}/source/", {"rows": [{"text": "replacement"}]}, format="json")@@ -203,12 +203,12 @@ def test_type3_native_text_survives_landing_without_ocr_replacement(workshop):native = [rowfor row in rows- if row["_overmind_provenance"]["extraction"]["method"] == "pdfium-native-text"+ if row["_overmind_evidence"]["extraction"]["method"] == "pdfium-native-text"]assert nativewidth, height = (612, 792) if page in (1, 3) else (792, 612)for row in native:- box = row["_overmind_provenance"]["evidence"][0]["regions"][0]["bbox"]+ box = row["_overmind_evidence"]["evidence"][0]["regions"][0]["bbox"]assert box["coord_origin"] == "TOPLEFT"assert 0 <= box["l"] < box["r"] <= widthassert 0 <= box["t"] < box["b"] <= height@@ -235,7 +235,7 @@ def test_scanned_pdf_upload_lands_with_page_evidence_and_original_bytes(workshoprows = frame[frame["page"] == page]assert "Returns are accepted for thirty days." in " ".join(rows["text"])for _, row in rows.iterrows():- evidence = row["_overmind_provenance"]["evidence"][0]+ evidence = row["_overmind_evidence"]["evidence"][0]assert evidence["document_id"] == artifact["sha256"]assert evidence["page"] == pageassert evidence["regions"][0]["page"] == page@@ -246,11 +246,11 @@ def test_scanned_pdf_upload_lands_with_page_evidence_and_original_bytes(workshopocr_rows = [rowfor row in rows.to_dict("records")- if row["_overmind_provenance"]["extraction"]["method"] == "tesseract-ocr"+ if row["_overmind_evidence"]["extraction"]["method"] == "tesseract-ocr"]assert ocr_rowsassert all(- 0 <= row["_overmind_provenance"]["extraction"]["confidence"] <= 100 for row in ocr_rows+ 0 <= row["_overmind_evidence"]["extraction"]["confidence"] <= 100 for row in ocr_rows)if name == "mixed":assert list(frame["page"]) == sorted(frame["page"])@@ -335,7 +335,7 @@ def test_image_upload_extracts_text_with_upright_evidence_and_original_download(assert extraction["ocr"]["image"]["coordinate_space"] == "exif-oriented-pixels"if format == "WEBP":assert extraction["ocr"]["image"]["ocr_width"] < 1224- for provenance in frame["_overmind_provenance"]:+ for provenance in frame["_overmind_evidence"]:evidence = provenance["evidence"][0]assert evidence["document_id"] == artifact["sha256"]assert evidence["filename"] == f"policy.{extension}"@@ -414,7 +414,7 @@ def test_image_without_text_lands_as_an_empty_recorded_part_of_a_batch(workshop)assert dataset.source is not None, dataset.errorframe = store.read_frame(paths.cell_path(dataset.id, dataset.source.id))assert "Returns are accepted for thirty days." in " ".join(frame["text"])- assert {p["evidence"][0]["filename"] for p in frame["_overmind_provenance"]} == {"policy.png"}+ assert {p["evidence"][0]["filename"] for p in frame["_overmind_evidence"]} == {"policy.png"}by_name = {source["filename"]: source for source in dataset.source_spec["sources"]}assert by_name["blank.png"]["rows"] == 0assert by_name["blank.png"]["extraction"]["status"] == "no_text"@@ -444,7 +444,7 @@ def test_photographed_page_falls_back_to_single_block_ocr(workshop, monkeypatch,assert dataset.source is not None, dataset.errorframe = store.read_frame(paths.cell_path(dataset.id, dataset.source.id))assert "Returns are accepted for thirty days." in " ".join(frame["text"])- assert {p["extraction"]["psm"] for p in frame["_overmind_provenance"]} == {6}+ assert {p["extraction"]["psm"] for p in frame["_overmind_evidence"]} == {6}def test_image_can_be_added_to_an_existing_workshop(workshop, django_capture_on_commit_callbacks):@@ -555,7 +555,6 @@ def test_source_upload_merges_after_existing_cells_and_preserves_frozen_versionsassert frame["text"].tolist() == ["cleaned", "new"]assert frame["source_row"].is_uniqueassert frame.iloc[1]["category"] == "example"- assert frame.iloc[1]["_overmind_provenance"]["file"]["filename"] == "more.csv"assert paths.cell_path(dataset.id, dataset.source.id).read_bytes() == original_bytesassert paths.cell_path(dataset.id, transformed.id).read_bytes() == frozen_bytesartifact = dataset.source_spec["sources"][0]@@ -603,7 +602,7 @@ def test_source_attachment_batch_is_atomic_and_can_be_retried(dataset.refresh_from_db()assert dataset.active_cell.rows == 2frame = store.read_frame(paths.cell_path(dataset.id, dataset.active_cell.id))- assert frame.iloc[1]["_overmind_provenance"]["evidence"]+ assert frame.iloc[1]["_overmind_evidence"]["evidence"]def test_source_attachment_busy_scope_and_duplicate_delivery(diff --git a/tests/test_workshop_mcp_acceptance.py b/tests/test_workshop_mcp_acceptance.pyindex 8bc16f08..94aa75d5 100644--- a/tests/test_workshop_mcp_acceptance.py+++ b/tests/test_workshop_mcp_acceptance.py@@ -68,7 +68,6 @@ def test_pipeline_poll_and_replay_keep_examples_in_drilldown_not_status(mode):assert len(json.dumps(response).encode()) < 48000assert job["progress"]["steps"][0]["output_rows"] == 5assert job["progress"]["seconds"] > 0- assert "input_examples" not in job["progress"]["steps"][0]["impact"]assert job["details"]["evidence_resource"]["uri"] == job["resource"]["uri"]async def evidence():@@ -276,7 +275,7 @@ def test_pipeline_job_exposes_measured_stage_and_completion_counts():"request_key": "progress",},)- impact = workbench.review.impact_files+ impact = workbench.measure.describe_frameobservations = []def inspect_impact(*args, **kwargs):@@ -285,9 +284,9 @@ def test_pipeline_job_exposes_measured_stage_and_completion_counts():)return impact(*args, **kwargs)- with patch.object(workbench.review, "impact_files", side_effect=inspect_impact):+ with patch.object(workbench.measure, "describe_frame", side_effect=inspect_impact):workbench.execute(run["run"]["id"], script_executor=execute_fixture)- assert observations[0]["progress"]["stage"] == "measuring_impact"+ assert observations[0]["progress"]["stage"] == "step_1_measuring"assert observations[0]["progress"]["source_rows"] == 2assert observations[0]["progress"]["output_rows"] == 1completed = call(context, "get_job", {"kind": "dataset_pipeline", "id": run["run"]["id"]})@@ -406,7 +405,7 @@ def test_interrupted_worker_cannot_publish_over_a_newer_queued_run(interruption)"request_key": "interrupted",}replacement = []- impact = workbench.review.impact_files+ impact = workbench.measure.describe_framedef interrupt(*positional, **keyword):if interruption == "cancel":@@ -426,7 +425,7 @@ def test_interrupted_worker_cannot_publish_over_a_newer_queued_run(interruption)with patch("overbae.tasks.datasets.execute_pipeline.delay"):first = call(context, "run_dataset_pipeline", args)- with patch.object(workbench.review, "impact_files", side_effect=interrupt):+ with patch.object(workbench.measure, "describe_frame", side_effect=interrupt):workbench.execute(first["run"]["id"], script_executor=execute_fixture)dataset.refresh_from_db()assert dataset.active_cell.pk == source.pk and dataset.state == "running"@@ -587,7 +586,7 @@ def test_landing_and_pipeline_preserve_scalar_values_without_lossy_coercion(valuassert json.dumps(actual) == json.dumps(values)frame_values = store.read_frame(paths.cell_path(dataset.pk, cell.pk))["value"].tolist()assert json.dumps(frame_values) == json.dumps(values)- batches = store.iter_frames(paths.cell_path(dataset.pk, cell.pk), batch_size=10000)+ batches = store.iter_frames(paths.cell_path(dataset.pk, cell.pk))assert json.dumps([value for frame in batches for value in frame["value"].tolist()]) == json.dumps(values)diff --git a/tests/test_workshop_preparation_journey.py b/tests/test_workshop_preparation_journey.pyindex 579d44ff..fd50cd51 100644--- a/tests/test_workshop_preparation_journey.py+++ b/tests/test_workshop_preparation_journey.py@@ -1,17 +1,14 @@import pytestfrom mcp_fixtures import call_tool-from overbae.models import Activity, DatasetPipelineRun+from overbae.models import DatasetPipelineRunfrom overbae.services import operational_progressfrom overbae.services.datasets import (attachments,exploration,land,partition_plans,- paths,pipeline_runner,- review,- store,workbench,)from overbae.services.mcp.catalog import CATALOG@@ -99,81 +96,6 @@ def test_partition_canvas_replaces_corrected_process_and_preserves_pinned_inputsassert final["details"]["output_cell"] == str(selected.pk)[email protected]("fail_last", [False, True])-def test_explicit_row_batches_publish_atomically_and_preserve_order(fail_last):- project, client, context = workspace()- dataset = source(client, project, "Batched input", [{"value": i} for i in range(11)])- original = dataset.active_cell- recipe = call(- context,- "save_dataset_pipeline",- name="Batched decisions",- request_key="batch-recipe",- package=retained_package(- project,- context.user,- [- decision_step(- batch_rows=4,- consumer="decision_train",- checks={"preserve_rows": True, "min_rows": 11},- )- ],- ),- )["pipeline"]- receipt = call(- context,- "run_dataset_pipeline",- dataset=str(dataset.pk),- pipeline=recipe["id"],- source_cell=str(original.pk),- source_fingerprint=original.fingerprint,- request_key="batch-run",- )- task_activity = Activity.objects.get(task_id=receipt["run"]["id"])- inventory = client.get("/api/datasets/", {"project": str(project.pk)}).data["results"]- active_work = next(item["work"] for item in inventory if item["id"] == str(dataset.pk))- assert active_work["label"] == "Transforming"- assert active_work["status"] == "queued"- assert active_work["actor_kind"] == task_activity.actor_kind- seen = []-- def executor(run, index, path, directory, step, files, progress):- task_activity.refresh_from_db()- assert task_activity.status == "running"- receipt = run.result["steps"][index]- assert "exit_code" not in receipt- assert "provider_execution" not in receipt- receipt["exit_code"] = 0- receipt["provider_execution"] = f"batch-{len(seen) + 1}"- records = list(store.iter_rows(path))- seen.append([row["value"] for row in records])- if fail_last and len(seen) == 3:- raise ValueError("Last batch failed")- return execute_fixture(run, index, path, directory, step, files, progress)-- workbench.execute(receipt["run"]["id"], script_executor=executor)- run = DatasetPipelineRun.objects.get(pk=receipt["run"]["id"])- dataset.refresh_from_db()- task_activity.refresh_from_db()- assert task_activity.status == ("failed" if fail_last else "completed")- assert Activity.objects.filter(task_id=str(run.pk)).count() == 1- inventory = client.get("/api/datasets/", {"project": str(project.pk)}).data["results"]- assert next(item["work"] for item in inventory if item["id"] == str(dataset.pk)) is None- assert seen == [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10]]- if fail_last:- assert run.state == "failed"- assert dataset.active_cell.pk == original.pk- assert dataset.cells.count() == 1- else:- assert run.state == "completed", run.error- assert [- row["decision"]["state"]- for row in store.iter_rows(paths.cell_path(dataset.pk, dataset.active_cell.pk))- ] == [str(i) for i in range(11)]- assert run.result["steps"][0]["batches"]["completed"] == 3--def test_worker_redelivery_never_replays_claimed_work_and_expiry_preserves_source():project, client, context = workspace()dataset = source(client, project, "Interrupted source", [{"value": 1}])@@ -227,7 +149,7 @@ def test_worker_redelivery_never_replays_claimed_work_and_expiry_preserves_sourcassert repeated["run"]["state"] == "failed"-def test_runner_heartbeat_survives_long_impact_measurement_without_claiming_progress(monkeypatch):+def test_runner_heartbeat_survives_long_measurement_without_claiming_progress(monkeypatch):project, client, context = workspace()dataset = source(client, project, "Long measurement", [{"value": 1}])recipe = call(@@ -247,10 +169,10 @@ def test_runner_heartbeat_survives_long_impact_measurement_without_claiming_progrequest_key="measurement-run",)run_id = submitted["run"]["id"]- measure = review.impact_files+ measure = workbench.measure.describe_frameobserved = []- def slow_measurement(before, after, **kwargs):+ def slow_measurement(*args, **kwargs):previous = workbench.runner_status()["last_heartbeat_at"]progress = operational_progress.latest(project.pk, "dataset_pipeline", run_id)pipeline_runner.heartbeat()@@ -262,11 +184,11 @@ def test_runner_heartbeat_survives_long_impact_measurement_without_claiming_progoperational_progress.latest(project.pk, "dataset_pipeline", run_id)["last_progress_at"]== progress["last_progress_at"])- return measure(before, after, **kwargs)+ return measure(*args, **kwargs)pipeline_runner.heartbeat()monkeypatch.setattr(pipeline_runner, "execute_script", execute_fixture)- monkeypatch.setattr(review, "impact_files", slow_measurement)+ monkeypatch.setattr(workbench.measure, "describe_frame", slow_measurement)from overbae.tasks.datasets import execute_pipelineexecute_pipeline(str(run_id))diff --git a/tests/test_workshop_readiness.py b/tests/test_workshop_readiness.pyindex 472b5ba7..bd6ab5bd 100644--- a/tests/test_workshop_readiness.py+++ b/tests/test_workshop_readiness.py@@ -16,9 +16,6 @@ from overbae.models import (User,)from overbae.services.datasets import alignment, land, review, use-from overbae.services.datasets.context import context_fingerprint-from overbae.services.mcp.contracts.datasets import serialize_dataset_detail-from overbae.services.mcp.errors import mcp_cell_contractfrom overbae.services.training_preparation import request_preparationpytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]@@ -54,12 +51,6 @@ def capability():)-def complete_review(dataset, *, failed=None, unknown=None):- from conftest import review_fixture-- return review_fixture(dataset, failed=failed, unknown=unknown)--def make_dataset(capability, *, intent="eval", evidence=True, case_id="case1"):ds = Dataset.objects.create(project=capability.project, capability=capability, name="Cases", intent=intent@@ -118,46 +109,6 @@ def test_worker_prompt_reports_capability_mismatch(capability, frame_of):assert not report["ok"] and "system turn differs" in report["reason"][email protected]("failure", [None, "input_evidence", "answer_support"])-def test_missing_or_failed_review_warns_without_blocking_use(capability, failure):- ds = make_dataset(capability)- if failure:- complete_review(ds, failed=failure)- assert review.warnings(ds, ds.active_cell)- assert use.use(ds, "eval").used_at is not None- detail = serialize_dataset_detail(ds)- assert detail.next_actions[0].tool == "check_evaluation_readiness"- assert any(action.tool == "check_evaluation_readiness" for action in detail.next_actions)- assert not detail.cells[0].readiness["quality_passed"]- contract = mcp_cell_contract(ds, ds.active_cell, "eval")- assert contract.fits and contract.warnings---def test_sampled_or_unknown_answer_support_cannot_pass(capability):- ds = make_dataset(capability)- complete_review(ds, unknown="answer_support")- assert "Answer support: unknown" in "; ".join(review.warnings(ds, ds.active_cell))- assert use.use(ds, "eval").used_at is not None---def test_context_changes_make_review_stale_without_blocking_use(capability):- ds = make_dataset(capability)- complete_review(ds)- assert review.readiness(ds, ds.active_cell)["quality_passed"]- assert use.check(ds, "eval").used_at is None- assert use.use(ds, "eval").used_at is not None- before = context_fingerprint(capability)- capability.improvement_metadata["capability_card"]["output_schema"]["required_keys"].append(- "evidence"- )- capability.save(update_fields=["improvement_metadata"])- ds.refresh_from_db()- assert context_fingerprint(capability) != before- assert not review.readiness(ds, ds.active_cell)["quality_passed"]- assert review.warnings(ds, ds.active_cell)- assert use.use(ds, "eval").used_at is not None--def test_unreviewed_data_can_start_model_preprocessing(capability, settings):settings.FINETUNING_BACKEND = "modal"ds = make_dataset(capability, intent="train")@@ -178,7 +129,6 @@ def test_unbound_data_still_uses_dataset_quality_contract(capability):def test_training_create_allows_warnings_and_freezes_pair_atomically(capability):train = make_dataset(capability, intent="train")evaluation = make_dataset(capability)- complete_review(train)user = User.objects.create_user(email="[email protected]", password="test")ProjectMembership.objects.create(user=user, project=capability.project)eval_set = EvalSet.objects.create(project=capability.project, name="Screening")@@ -217,9 +167,7 @@ def test_training_create_allows_warnings_and_freezes_pair_atomically(capability)job = serializer.save(triggered_by=user)assert job.eval_cell_id == evaluation.active_cell.idassert job.cell.used_at and job.eval_cell.used_at- assert review.warnings(evaluation, job.eval_cell)replacement = make_dataset(capability, case_id="new-eval")- complete_review(replacement)update = FinetuningJobSerializer(job, data={"eval_dataset": str(replacement.id)}, partial=True)assert not update.is_valid() and "eval_dataset" in update.errorsassert replacement.active_cell.used_at is Nonediff --git a/tests/test_workshop_redesign.py b/tests/test_workshop_redesign.pyindex 303cf3dc..5d7fd657 100644--- a/tests/test_workshop_redesign.py+++ b/tests/test_workshop_redesign.py@@ -51,7 +51,6 @@ def test_pipeline_conflicts_and_project_isolation_preserve_the_source():{"project": str(project.pk),"name": "Source",- "intent": "explore","source": {"rows": [{"text": "evidence"}]},},format="json",@@ -101,7 +100,6 @@ def test_failed_external_lineage_and_cancelled_runs_never_publish():{"project": str(project.pk),"name": "Bound source",- "intent": "explore","source": {"rows": [{"text": "Source evidence"}]},},format="json",@@ -195,7 +193,6 @@ def test_external_output_records_attribution_and_preserves_frozen_inputs():dataset.refresh_from_db()output = dataset.active_cellassert output.review["execution"] == "external_attributed"- assert output.quality_report == {}assert not next(store.iter_rows(paths.cell_path(dataset.pk, output.pk))).get("human_reviewed")assert repeated["run"]["provenance"] == "Local script revision abc123"assert (@@ -221,7 +218,6 @@ def test_large_external_artifact_is_project_scoped_and_retained():{"project": str(project.pk),"name": "Evidence",- "intent": "explore","source": {"rows": [{"text": "Original evidence"}]},},format="json",@@ -234,7 +230,6 @@ def test_large_external_artifact_is_project_scoped_and_retained():{"project": str(project.pk),"name": "External artifact",- "intent": "explore","source": {"rows": [{"text": f"Derived {i}", "_overmind_parent_rows": [identity]}@@ -312,7 +307,6 @@ def test_queued_source_cancellation_releases_the_dataset_without_publishing():{"project": str(project.pk),"name": "Queued source",- "intent": "explore","source": {"rows": [{"text": "Evidence"}]},},format="json",diff --git a/uv.lock b/uv.lockindex 4a0f532f..cfddbb21 100644--- a/uv.lock+++ b/uv.lock@@ -1,5 +1,5 @@version = 1-revision = 5+revision = 3requires-python = ">=3.13"resolution-markers = ["python_full_version >= '3.14' and sys_platform == 'win32'",@@ -291,6 +291,7 @@ dependencies = [{ name = "numpy" },{ name = "openai" },{ name = "opentelemetry-proto" },+ { name = "orjson" },{ name = "overmind" },{ name = "pandas" },{ name = "pgvector" },@@ -390,6 +391,7 @@ requires-dist = [{ name = "numpy", specifier = ">=2.0" },{ name = "openai", specifier = ">=1.0.0" },{ name = "opentelemetry-proto" },+ { name = "orjson", specifier = ">=3.13.0" },{ name = "overmind", specifier = ">=0.1.97" },{ name = "pandas", specifier = ">=2.2.0" },{ name = "pgvector", specifier = ">=0.4.2" },@@ -3234,6 +3236,44 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/18/8d/39885564eefa43f6181acfa3d698af2f6b5fe3e64c86dce3f1b955f6397f/opentelemetry_util_http-0.66b2-py3-none-any.whl", hash = "sha256:c4bb5d6744e60353bcaa3e325bc529a1515346b51cb4d9c8e5b730579337e06d", size = 8383, upload-time = "2026-10-29T17:38:07.462Z" },]+[[package]]+name = "orjson"+version = "3.13.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/f2/72/380b97dc45bd162d23afe5194721ef678d9eac7cfaa549fe2873f7f0a518/orjson-3.13.0.tar.gz", hash = "sha256:d1de5eb04485110c5da4c657e49168995d55e076b1ce60f1a042e254f4186c4f", size = 2732604, upload-time = "2026-10-07T14:09:25.719Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/a9/56/f8ad2546150168858c16915c452b00eecb79597597524d1ad6ae14ad4eab/orjson-3.13.0-cp313-cp313-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:64e8f345048d988c8b68d3882e5d41028fca1219a9939b32e4a77be34c8ae8e3", size = 222892, upload-time = "2026-10-07T14:08:37.495Z" },+ { url = "https://files.pythonhosted.org/packages/1f/19/725d23160b2471a3f27026c55bb79af34687652d8be8f5f583cee5dcd42f/orjson-3.13.0-cp313-cp313-macosx_15_0_arm64.whl", hash = "sha256:ded33b972cffdaf4ca0ac917338ab61d2bb10d68987dbcae641c313fbfdbf499", size = 123319, upload-time = "2026-10-07T14:08:38.989Z" },+ { url = "https://files.pythonhosted.org/packages/ac/08/e5d81a00b22c73dfcb60d80da3bd92d5a7684346593536565f184dbae3c9/orjson-3.13.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:45e34deb3437509f4ec9888dd9ee5dc426cfe21be10f1eb4ea3a9e4d33034f9e", size = 113196, upload-time = "2026-10-07T14:08:40.383Z" },+ { url = "https://files.pythonhosted.org/packages/67/78/fda6117c69a43e470b1e9dff38dd8c5f0bc6fd8a47e4d4561ab023039335/orjson-3.13.0-cp313-cp313-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:9825b954155b345c4759f24e5f8d652b9aec2261bb5d4e1abe06bba0a1200535", size = 130245, upload-time = "2026-10-07T14:08:41.878Z" },+ { url = "https://files.pythonhosted.org/packages/6d/31/d0cfebd456defb234414795ae7599696bf124843dfe077d0c9ece0c93554/orjson-3.13.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b081f0e7b600ff24513dec4ca75507fa05e904607847e386e8310d5b7b96b6c7", size = 128981, upload-time = "2026-10-07T14:08:43.716Z" },+ { url = "https://files.pythonhosted.org/packages/45/46/f8d83189ff5b7b2ff225a58c5908618cc4e86afe09e65d17a30ac68c9da4/orjson-3.13.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cbed5f4c4b88d94bcc36115f4c3bb3aa25da1563a5c3328aa3acebce2b083040", size = 130370, upload-time = "2026-10-07T14:08:45.132Z" },+ { url = "https://files.pythonhosted.org/packages/e6/6a/d6344c305003ea826b3fa0482645a897a3cd6d477ed74e1fe15d3322cb23/orjson-3.13.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e9b61676116f755126b90e740a9cff36b91562f47ec330056cc88cc3b9f02f4b", size = 134595, upload-time = "2026-10-07T14:08:46.63Z" },+ { url = "https://files.pythonhosted.org/packages/9f/52/d73fa44f88d53e02d10de1cf77c16ed13204ff5bca47e1692da6b406619c/orjson-3.13.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3ef75ed7e81dae34a3649f82df52cd85f9ac839a7d6ec78ab355b33b3b27ef7f", size = 126513, upload-time = "2026-10-07T14:08:48.111Z" },+ { url = "https://files.pythonhosted.org/packages/fb/f8/bcfc50b4ab851c4f9c0ee62f52bf3b28f0bcd0d9fe08e0ad98d4585148db/orjson-3.13.0-cp313-cp313-win_amd64.whl", hash = "sha256:4ee06e53b998c71ce3eb93b86222912fdd9dcced685ac64d4525d36fac338ea4", size = 121371, upload-time = "2026-10-07T14:08:49.549Z" },+ { url = "https://files.pythonhosted.org/packages/7b/7a/d6927845712ec2b1e89263cd12d7203531db185dbad67f914226f2fca156/orjson-3.13.0-cp313-cp313-win_arm64.whl", hash = "sha256:89efecad02515df7f318d0613b5dfd6d2a1acd323a2b8294712789a715945525", size = 126134, upload-time = "2026-10-07T14:08:51.118Z" },+ { url = "https://files.pythonhosted.org/packages/f0/10/98b5a3cdc086abf78d8cd20bb0cba124485d4b6a745722197bd209d967a5/orjson-3.13.0-cp314-cp314-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:a7bfc7db961c7d96cb75889dc6a1e4ae1e91d87ee61da564f582bd742b8dfeef", size = 222889, upload-time = "2026-10-07T14:08:52.673Z" },+ { url = "https://files.pythonhosted.org/packages/22/7c/7728c5280ab5202f4891ff4b0b96e2e1dbd5520dfee53edf083c54409a64/orjson-3.13.0-cp314-cp314-macosx_15_0_arm64.whl", hash = "sha256:91d933e668ff0ffe164d7c2daec36beba6d1ce7fadb71538fbe142a71f8a1e6e", size = 123312, upload-time = "2026-10-07T14:08:54.25Z" },+ { url = "https://files.pythonhosted.org/packages/a9/a5/d9a44321e6f66c0f64b45be587395f87ad94cb447bce7d92286f6b97d46a/orjson-3.13.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:6c8bfe728b81b0fd58a3c7f3f9c5a113f87f2992c9948e0f28707aafd737c0bc", size = 113146, upload-time = "2026-10-07T14:08:55.803Z" },+ { url = "https://files.pythonhosted.org/packages/80/da/d95c80d413f288feb471e16d82e5c1512d2439728e3bac917d058c31f098/orjson-3.13.0-cp314-cp314-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:e8e05549f3b30f9d8a8e28c5aba11cc2a4b90b90961ec685ca58444b0815fc09", size = 130348, upload-time = "2026-10-07T14:08:57.31Z" },+ { url = "https://files.pythonhosted.org/packages/04/0f/36fdfb32ad1852997bac00e3ce52c7888d8a1094ba9dcdcbb22fcc6b953a/orjson-3.13.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c749ab3ac30b5ab1ffb7677f8b92eacfdfdc5260210baa398f845bc3714c05d8", size = 128971, upload-time = "2026-10-07T14:08:58.843Z" },+ { url = "https://files.pythonhosted.org/packages/25/de/a82acf93bdcca0c79ccff25ef0c6868d24ccbc2e72f21fae39c8cabce4f1/orjson-3.13.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:58a9619d88f8818d9ab6b39d70d203789457ba13c1ed5d274f33ce9ae7e81a36", size = 130359, upload-time = "2026-10-07T14:09:00.412Z" },+ { url = "https://files.pythonhosted.org/packages/71/ca/2bc4f7697cb9f6897bf61aca11803df096a5d971bf69ef5538b243bb1fa8/orjson-3.13.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:2715c4808d1571029ed18fd07a82140bf3ba7def0dc89f8d015c416e3649bf87", size = 134583, upload-time = "2026-10-07T14:09:02.047Z" },+ { url = "https://files.pythonhosted.org/packages/23/b3/12b1af9b87ff9fa0aaf4e5724c87672b30bb5de76f275f7fac64e8219c1b/orjson-3.13.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:08bf722f923d2100bc5e5a5dcf72c656db557049c1bea26582fdd5dd9d5395a1", size = 126500, upload-time = "2026-10-07T14:09:03.863Z" },+ { url = "https://files.pythonhosted.org/packages/ad/ea/cf257fc8a7f4b18f5677c22b3a9673a1b51d4b7161f25177ed389b76560e/orjson-3.13.0-cp314-cp314-win_amd64.whl", hash = "sha256:6adcaa85d79977659a448b4123a88eb33511a11ed2db243535ad7ea88a6668e0", size = 121378, upload-time = "2026-10-07T14:09:05.375Z" },+ { url = "https://files.pythonhosted.org/packages/05/0a/9f4643f849e9918eab11983b83928af3aac14bedb04002e28e885ee1936f/orjson-3.13.0-cp314-cp314-win_arm64.whl", hash = "sha256:83705c12b4afde10c62a5dd3fe6fdb21b7900bd0dcd5af1c85612ae94d0ee590", size = 126123, upload-time = "2026-10-07T14:09:07.085Z" },+ { url = "https://files.pythonhosted.org/packages/8c/15/d265f2b556c0c7c0b30ea830316d6e5af5b85dde08f234a1ebed60fab386/orjson-3.13.0-cp315-cp315-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:5ef4d4157392a0439b74f7e49e5636b4ea43d9616bd0884effc0195fffcaa2d5", size = 223305, upload-time = "2026-10-07T14:09:08.84Z" },+ { url = "https://files.pythonhosted.org/packages/0c/97/781be8b80a33b8171b3f5acea941af47182c8b4b5827c2b7c3fea706f21c/orjson-3.13.0-cp315-cp315-macosx_15_0_arm64.whl", hash = "sha256:84d87e322e1674408f85adea63f11aa19201eba082755aec20ebc217f493bbd2", size = 123515, upload-time = "2026-10-07T14:09:10.792Z" },+ { url = "https://files.pythonhosted.org/packages/20/68/011bb98fa7da7b430b363db1bb7ef9160c438fc5c43e7468fb593c220037/orjson-3.13.0-cp315-cp315-manylinux_2_39_aarch64.whl", hash = "sha256:8c2ac5c09b017c484df1b4c68b2cf250b4e8ba08204cb58e7cd6cbbc71a9c902", size = 129222, upload-time = "2026-10-07T14:09:12.542Z" },+ { url = "https://files.pythonhosted.org/packages/86/7f/d96fa2aedaaec14c095ea9cd48d2158fdf33c0f4fd6e7a598d899d536b03/orjson-3.13.0-cp315-cp315-manylinux_2_39_armv7l.whl", hash = "sha256:51d11525bc3ca736fa97ce4e4c7da9999cc00bf261522bede43b4e7531bd7965", size = 113152, upload-time = "2026-10-07T14:09:14.059Z" },+ { url = "https://files.pythonhosted.org/packages/e9/2d/ee77aa685c54bd920a1f0e2936986b46269adb0d72bf5098c2c694dbeb36/orjson-3.13.0-cp315-cp315-manylinux_2_39_i686.whl", hash = "sha256:ac81530647c3423107cf61c3481e91f57134e9ddfb6ef83f5150ccbdcbc3a3ee", size = 130749, upload-time = "2026-10-07T14:09:15.835Z" },+ { url = "https://files.pythonhosted.org/packages/48/eb/3411fbfdad61b3f3af22343b5af7ed5c8a1679e35f442e8f1b229b33040e/orjson-3.13.0-cp315-cp315-manylinux_2_39_x86_64.whl", hash = "sha256:0526a3456db67b264c6d661b5f090077f326b6cd074d0ef53a72763595dec5d7", size = 130471, upload-time = "2026-10-07T14:09:17.463Z" },+ { url = "https://files.pythonhosted.org/packages/87/71/abdc2b8c70b8d85a6cb22f404da0f52d7d712f9d49cda039a0cb1adcb973/orjson-3.13.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:dd61e64802d51d1e4f16531c64536354fc3bc67932dc0cff254044f72bf0f187", size = 134793, upload-time = "2026-10-07T14:09:19.084Z" },+ { url = "https://files.pythonhosted.org/packages/0a/2e/1c13552d8b0241083116de02b2f284ee38501ef06ebfb79893f741538168/orjson-3.13.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:c5e3ccaac3106e8fa6e2f2f6962449d7c757d7b067e41b395a19d6f0d6cec892", size = 126711, upload-time = "2026-10-07T14:09:20.645Z" },+ { url = "https://files.pythonhosted.org/packages/85/f8/d4ece953a519d064cf690adaa68cd389d5b64fd261726334841b32978d6a/orjson-3.13.0-cp315-cp315-win_amd64.whl", hash = "sha256:7804dd1d6161da0e53b284c2aebf20f23e78eaac617300803e1467d1828d987f", size = 121496, upload-time = "2026-10-07T14:09:22.359Z" },+ { url = "https://files.pythonhosted.org/packages/70/cf/f691388c4a9bc4af7dcc1648c4b40845869908b517d7c0009d005c7d1fa1/orjson-3.13.0-cp315-cp315-win_arm64.whl", hash = "sha256:f5c05a8fee59309f537590a1ff12d3c1009c485e96a50a9ac60dd085c09d0fc0", size = 126260, upload-time = "2026-10-07T14:09:23.928Z" },+]+[[package]]name = "overmind"version = "0.1.97"