Skip to content

The platform for continuously improving AI agents.

Act on #369's review and fix decision training on foundations (#370)

Freyam Mehtacb19780d7791
diff --git a/.agents/skills/data-workshop/SKILL.md b/.agents/skills/data-workshop/SKILL.md
index 1a127056..f9938c96 100644
--- a/.agents/skills/data-workshop/SKILL.md
+++ b/.agents/skills/data-workshop/SKILL.md
@@ -26,7 +26,7 @@ A customer's coding agent over MCP and the Console assistant own interpretation,
- 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.
+- 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 transfer has one receipt, each dataset it lands gets one source cell, and an added batch becomes one version.
- A new dataset from several files lands one dataset per set of column names (`land._group`: ignoring case and order; value types do not split a set), the first set in the named dataset and the others in datasets saved at publication (`imports._column_groups`). Every landed dataset's `source_spec.column_groups` lists them; Home adds each as its own Data stage. A split or an added batch needs one set of columns.
- XLSX (`spreadsheets.py`, openpyxl read-only) lands one dataset per sheet. The first nonempty row is the header; formulas stay source text, dates become ISO text, durations seconds; `_overmind_evidence` names the sheet, row and typed cells. 100 MiB per workbook and 512 MiB expanded; `.xlsx.gz` is refused. 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.
diff --git a/frontend/src/components/assistant/assistant-result.tsx b/frontend/src/components/assistant/assistant-result.tsx
index 7b448c17..0877f234 100644
--- a/frontend/src/components/assistant/assistant-result.tsx
+++ b/frontend/src/components/assistant/assistant-result.tsx
@@ -337,8 +337,11 @@ function Draft({ node }: { node: EvalSetDraftNode }) {
<EvalSetDraftReview
answered={actions.answered.has(answerKey(call, node.id))}
node={node}
- onAnswer={(text, values) => actions.onAnswer(text, { call, id: node.id, values })}
+ onAnswer={(text, values, onSent) =>
+ actions.onAnswer(text, { call, id: node.id, values }, onSent)
+ }
sending={actions.sending}
+ storageKey={`assistant-eval-set:${answerKey(call, node.id)}`}
/>
);
}
diff --git a/frontend/src/components/assistant/eval-set-draft.test.tsx b/frontend/src/components/assistant/eval-set-draft.test.tsx
index a40ea2ad..7fd6a974 100644
--- a/frontend/src/components/assistant/eval-set-draft.test.tsx
+++ b/frontend/src/components/assistant/eval-set-draft.test.tsx
@@ -8,19 +8,18 @@ import { NEW_CRITERION } from "@/components/evaluations/criteria-card";
import { draftChanges, EvalSetDraftReview } from "./eval-set-draft";
import type { EvalSetDraftNode } from "./types";
-const created = vi.fn();
+const created = vi.fn((_request: unknown) =>
+ Promise.resolve({ id: "new-set", name: "Replies v2" })
+);
vi.mock("@/client", () => ({
- default: {
- evalSets: {
- evalSetsCreate: (request: unknown) => {
- created(request);
- return Promise.resolve({ id: "new-set", name: "Replies v2" });
- },
- },
- },
+ default: { evalSets: { evalSetsCreate: (request: unknown) => created(request) } },
}));
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ created.mockClear();
+ window.sessionStorage.clear();
+});
const tone = { ...NEW_CRITERION.llm, name: "Tone", source: "Is it polite?" };
const brief = { ...NEW_CRITERION.llm, name: "Brief", source: "Is it short?" };
@@ -43,23 +42,38 @@ it("names what a draft adds, changes and removes by criterion", () => {
});
});
-it("saves the reviewed draft as a new set and answers with its id", async () => {
- const onAnswer = vi.fn();
+const review = (onAnswer: () => void) =>
render(
<QueryClientProvider client={new QueryClient()}>
- <EvalSetDraftReview answered={false} node={node} onAnswer={onAnswer} sending={false} />
+ <EvalSetDraftReview
+ answered={false}
+ node={node}
+ onAnswer={onAnswer}
+ sending={false}
+ storageKey="draft-call"
+ />
</QueryClientProvider>
);
+
+it("compares a stored criterion by value, whatever its key order", () => {
+ const stored = Object.fromEntries(Object.entries(tone).reverse()) as typeof tone;
+ expect(draftChanges([stored], [tone]).changed).toEqual([]);
+});
+
+it("saves the reviewed draft as a new set and answers with its id", async () => {
+ const onAnswer = vi.fn();
+ review(onAnswer);
expect(screen.getByText("Added: Brief")).toBeTruthy();
expect(screen.getByText("Changed: Tone")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Save eval set" }));
await waitFor(() =>
- expect(onAnswer).toHaveBeenCalledWith("Saved eval set Replies v2.", {
- name: "Replies v2",
- saved: "new-set",
- })
+ expect(onAnswer).toHaveBeenCalledWith(
+ "Saved eval set Replies v2.",
+ { name: "Replies v2", saved: "new-set" },
+ expect.any(Function)
+ )
);
expect(created).toHaveBeenCalledWith({
evalSetRequest: expect.objectContaining({
@@ -69,3 +83,35 @@ it("saves the reviewed draft as a new set and answers with its id", async () =>
}),
});
});
+
+it("answers with the saved set after a lost reply instead of saving it again", async () => {
+ // The reply never reaches the queue, so the card is still unanswered when it remounts.
+ const lost = vi.fn();
+ review(lost);
+ fireEvent.click(screen.getByRole("button", { name: "Save eval set" }));
+ await waitFor(() => expect(lost).toHaveBeenCalled());
+ cleanup();
+
+ const onAnswer = vi.fn();
+ review(onAnswer);
+ fireEvent.click(screen.getByRole("button", { name: "Save eval set" }));
+
+ expect(onAnswer).toHaveBeenCalledWith(
+ "Saved eval set Replies v2.",
+ { name: "Replies v2", saved: "new-set" },
+ expect.any(Function)
+ );
+ expect(created).toHaveBeenCalledTimes(1);
+});
+
+it("locks the draft while its save is pending", async () => {
+ let finish: (set: { id: string; name: string }) => void = () => undefined;
+ created.mockImplementationOnce(() => new Promise((resolve) => (finish = resolve)));
+ review(vi.fn());
+ expect(screen.getByLabelText("Benchmark name")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "Save eval set" }));
+
+ await waitFor(() => expect(screen.queryByLabelText("Benchmark name")).toBeNull());
+ finish({ id: "new-set", name: "Replies v2" });
+});
diff --git a/frontend/src/components/assistant/eval-set-draft.tsx b/frontend/src/components/assistant/eval-set-draft.tsx
index 97c253e0..efe266c3 100644
--- a/frontend/src/components/assistant/eval-set-draft.tsx
+++ b/frontend/src/components/assistant/eval-set-draft.tsx
@@ -6,20 +6,34 @@ import apiClient from "@/client";
import { CriteriaCard, type Criterion, saveBlocker } from "@/components/evaluations/criteria-card";
import { Button } from "@/components/ui/button";
import { errorMessage } from "@/lib/notify";
+import { sessionStore } from "@/lib/storage";
import type { EvalSet } from "@/openapi";
import type { EvalSetDraftNode } from "./types";
const LABELS = { added: "Added", changed: "Changed", removed: "Removed" };
+// A stored criterion comes back from jsonb with its keys reordered.
+function same(a: unknown, b: unknown): boolean {
+ if (a === b) return true;
+ if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
+ const left = a as Record<string, unknown>;
+ const right = b as Record<string, unknown>;
+ const keys = (value: Record<string, unknown>) =>
+ Object.keys(value).filter((key) => value[key] !== undefined);
+ return (
+ keys(left).length === keys(right).length &&
+ keys(left).every((key) => same(left[key], right[key]))
+ );
+}
+
/** What a draft changes in the set it amends, by criterion name. */
export function draftChanges(before: Criterion[], after: Criterion[]) {
const old = new Map(before.map((criterion) => [criterion.name, criterion]));
const names = new Set(after.map((criterion) => criterion.name));
return {
added: after.filter((c) => !old.has(c.name)).map((c) => c.name),
- changed: after
- .filter((c) => old.has(c.name) && JSON.stringify(old.get(c.name)) !== JSON.stringify(c))
- .map((c) => c.name),
+ changed: after.filter((c) => old.has(c.name) && !same(old.get(c.name), c)).map((c) => c.name),
removed: before.filter((c) => !names.has(c.name)).map((c) => c.name),
};
}
@@ -51,6 +65,17 @@ function Changes({
);
}
+type Saved = Pick<EvalSet, "id" | "name">;
+
+function savedOf(key: string): Saved | null {
+ try {
+ const value = JSON.parse(sessionStore.get(key) ?? "null");
+ return typeof value?.id === "string" && typeof value?.name === "string" ? value : null;
+ } catch {
+ return null;
+ }
+}
+
/** The agent's drafted eval set: the person edits it, then saves it as a new set or rejects
* it. Either answer reaches the agent as the person's reply. */
export function EvalSetDraftReview({
@@ -58,19 +83,25 @@ export function EvalSetDraftReview({
node,
onAnswer,
sending,
+ storageKey,
}: {
answered: boolean;
node: EvalSetDraftNode;
- onAnswer: (text: string, values: Record<string, unknown>) => void;
+ /** ``onSent`` runs once the answer is queued. */
+ onAnswer: (text: string, values: Record<string, unknown>, onSent?: () => void) => void;
sending: boolean;
+ storageKey: string;
}) {
const queryClient = useQueryClient();
const [name, setName] = useState(node.name);
const [criteria, setCriteria] = useState<Criterion[]>(node.criteria);
- // A saved set whose reply did not send is sent again, never saved twice.
- const [saved, setSaved] = useState<EvalSet | null>(null);
- const reply = (set: EvalSet) =>
- onAnswer(`Saved eval set ${set.name}.`, { name: set.name, saved: set.id });
+ // A saved set whose reply did not send is sent again, never saved twice, even after the
+ // card remounts in this browser session.
+ const [saved, setSaved] = useState<Saved | null>(() => savedOf(storageKey));
+ const reply = (set: Saved) =>
+ onAnswer(`Saved eval set ${set.name}.`, { name: set.name, saved: set.id }, () =>
+ sessionStore.remove(storageKey)
+ );
const save = useMutation({
mutationFn: () =>
apiClient.evalSets.evalSetsCreate({
@@ -83,12 +114,13 @@ export function EvalSetDraftReview({
},
}),
onSuccess: async (set) => {
+ sessionStore.set(storageKey, JSON.stringify({ id: set.id, name: set.name }));
setSaved(set);
reply(set);
await queryClient.invalidateQueries({ queryKey: ["eval-sets"] });
},
});
- const editable = !answered && !saved;
+ const editable = !answered && !saved && !save.isPending;
const blocker = saveBlocker(name, criteria);
const busy = answered || sending || save.isPending;
return (
diff --git a/frontend/src/components/datasets/attachment.test.tsx b/frontend/src/components/datasets/attachment.test.tsx
index 5036b09e..04aa1896 100644
--- a/frontend/src/components/datasets/attachment.test.tsx
+++ b/frontend/src/components/datasets/attachment.test.tsx
@@ -56,3 +56,16 @@ it("stops drawing a PDF preview when the tile goes away", async () => {
unmount();
expect(pdf.destroy).toHaveBeenCalled();
});
+
+it("never starts a PDF preview for a tile that went away while its bytes were read", async () => {
+ pdf.started.mockClear();
+ let read: (bytes: ArrayBuffer) => void = () => undefined;
+ const entry = upload("late.pdf", "ready");
+ entry.file.arrayBuffer = vi.fn(() => new Promise<ArrayBuffer>((resolve) => (read = resolve)));
+ const { unmount } = tile(entry);
+ await vi.waitFor(() => expect(entry.file.arrayBuffer).toHaveBeenCalled());
+ unmount();
+ read(new ArrayBuffer(4));
+ await new Promise((resolve) => setTimeout(resolve));
+ expect(pdf.started).not.toHaveBeenCalled();
+});
diff --git a/frontend/src/components/workspace/home-composer.test.tsx b/frontend/src/components/workspace/home-composer.test.tsx
new file mode 100644
index 00000000..abf04a5e
--- /dev/null
+++ b/frontend/src/components/workspace/home-composer.test.tsx
@@ -0,0 +1,64 @@
+// @vitest-environment jsdom
+// covers: console-logic
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { HomeComposer } from "./home-composer";
+
+const GROUPS = 21;
+const landed = (id: string) => ({
+ active: `${id}-cell`,
+ cells: [{ fingerprint: "f", id: `${id}-cell`, state: "ok" }],
+ id,
+ name: id,
+ rows: 1,
+ sourceSpec: {
+ column_groups: Array.from({ length: GROUPS }, (_, i) => ({ dataset: `group-${i}` })),
+ },
+ state: "idle",
+});
+const api = vi.hoisted(() => ({
+ datasets: {
+ datasetsCreate: vi.fn(() => Promise.resolve({ id: "group-0" })),
+ datasetsList: vi.fn(() => Promise.resolve({ next: null, results: [] })),
+ datasetsRetrieve: vi.fn(({ id }: { id: string }) => Promise.resolve(landed(id))),
+ },
+ experiments: { experimentsCreate: vi.fn() },
+ uploads: {
+ uploadsChunkUpdate: vi.fn(({ body, offset }: { body: Blob; offset: number }) =>
+ Promise.resolve({ received: offset + body.size })
+ ),
+ uploadsCreate: vi.fn(() =>
+ Promise.resolve({ chunkBytes: 1024, maxBytes: 2048, uploadId: "upload" })
+ ),
+ uploadsInspectCreate: vi.fn(() => Promise.resolve({ rows: 1 })),
+ uploadsRetrieve: vi.fn(() => Promise.resolve({ received: 0 })),
+ },
+}));
+vi.mock("@/client", () => ({ default: api }));
+
+afterEach(cleanup);
+
+it("refuses data that lands as more datasets than a message takes", async () => {
+ render(
+ <QueryClientProvider client={new QueryClient()}>
+ <TooltipProvider>
+ <HomeComposer onStarted={vi.fn()} projectId="project" />
+ </TooltipProvider>
+ </QueryClientProvider>
+ );
+ fireEvent.change(screen.getByLabelText("Attach dataset files"), {
+ target: { files: [new File(["a,b\n1,2\n"], "rows.csv")] },
+ });
+ const send = screen.getByRole("button", { name: "Send" });
+ await waitFor(() => expect(send.hasAttribute("disabled")).toBe(false));
+
+ fireEvent.click(send);
+
+ expect(
+ await screen.findByText("The attached data is 21 datasets. A message takes at most 20.")
+ ).toBeTruthy();
+ expect(api.experiments.experimentsCreate).not.toHaveBeenCalled();
+});
diff --git a/frontend/src/components/workspace/home-composer.tsx b/frontend/src/components/workspace/home-composer.tsx
index 1fb29f55..02520b8b 100644
--- a/frontend/src/components/workspace/home-composer.tsx
+++ b/frontend/src/components/workspace/home-composer.tsx
@@ -278,6 +278,11 @@ export function HomeComposer({
})
).then((found) => found.flat());
setLanding("");
+ // The upload's sets of columns are known only once it lands.
+ if (cells.length > MAX_DATASETS)
+ throw new Error(
+ `The attached data is ${cells.length} datasets. A message takes at most ${MAX_DATASETS}.`
+ );
const experiment = await apiClient.experiments.experimentsCreate({
experimentCreateRequest: { cells, message, name, project: projectId, requestKey: step.key },
});
diff --git a/frontend/src/lib/pdf-thumbnail.ts b/frontend/src/lib/pdf-thumbnail.ts
index d2b993f3..8dc63e50 100644
--- a/frontend/src/lib/pdf-thumbnail.ts
+++ b/frontend/src/lib/pdf-thumbnail.ts
@@ -8,7 +8,10 @@ export async function pdfThumbnail(file: File, signal?: AbortSignal): Promise<st
const pdfjs = await import("pdfjs-dist");
signal?.throwIfAborted();
pdfjs.GlobalWorkerOptions.workerSrc = workerUrl;
- const task = pdfjs.getDocument({ data: await file.arrayBuffer() });
+ const data = await file.arrayBuffer();
+ // An abort during the read fired before the listener below exists.
+ signal?.throwIfAborted();
+ const task = pdfjs.getDocument({ data });
const stop = () => void task.destroy();
signal?.addEventListener("abort", stop, { once: true });
try {
diff --git a/overbae/services/activity.py b/overbae/services/activity.py
index 8ebef516..54ab8fd7 100644
--- a/overbae/services/activity.py
+++ b/overbae/services/activity.py
@@ -292,6 +292,8 @@ def mcp_succeeded(name, definition, output, context):
)
return
if name in {"save_dataset_pipeline", "run_dataset_pipeline"}:
+ if (output.get("run") or {}).get("mode") == "preview":
+ return
datasets = [item for item in output_assets(output) if item["kind"] == "dataset"]
if len(datasets) == 1:
assets = datasets
@@ -516,7 +518,7 @@ def _preparation_key(project_id, dataset_id):
def preparing(project_id, dataset_id, assets, **attribution):
"""One row for a dataset's preparation, from its first saved script or run to its
- publication: later scripts, previews and runs move the same row."""
+ publication: later scripts and runs move the same row; a preview adds none."""
record(
key=_preparation_key(project_id, dataset_id),
project_id=project_id,
diff --git a/overbae/services/datasets/analytics.py b/overbae/services/datasets/analytics.py
index 845ce46b..c416305e 100644
--- a/overbae/services/datasets/analytics.py
+++ b/overbae/services/datasets/analytics.py
@@ -121,7 +121,7 @@ class Analytics:
"judged_labels": set(),
"named": Counter(),
"values": {},
- "overflow": set(),
+ "unassessed": set(),
}
values = state if isinstance(state, dict) else {"state": state}
own, others = leak["own"][label], leak["others"][label]
@@ -129,7 +129,7 @@ class Analytics:
leak["judged"] += 1
leak["judged_labels"].add(label)
for name, value in values.items():
- if isinstance(value, str):
+ if isinstance(value, str) and str(name) in self.fields:
found = set(WORD.findall(value.lower()))
if found & own and not found & others:
leak["named"][str(name)] += 1
@@ -137,25 +137,25 @@ class Analytics:
return
for name, value in state.items():
name = str(name)
- if missing(value) or name in leak["overflow"] or name not in self.fields:
+ if missing(value) or name in leak["unassessed"] or name not in self.fields:
continue
counted = leak["values"].setdefault(name, {})
text = json.dumps(value, sort_keys=True, default=str)
identity = text if len(text) <= 64 else hashlib.sha256(text.encode()).hexdigest()
if identity not in counted and len(counted) >= VALUE_LIMIT:
- leak["overflow"].add(name)
+ leak["unassessed"].add(name)
del leak["values"][name]
continue
counted.setdefault(identity, Counter())[label] += 1
def _leak_findings(self):
- determined, named, overflow = [], [], set()
+ determined, named, unassessed = [], [], set()
assessed = judged = False
for key, leak in self.leaks.items():
family = self.families[key]
if sum(1 for count in family["counts"] if count) < 2:
continue
- overflow |= leak["overflow"]
+ unassessed |= leak["unassessed"]
for name, counted in leak["values"].items():
assessed = True
shared = [labels for labels in counted.values() if labels.total() >= SHARED_ROWS]
@@ -176,7 +176,7 @@ class Analytics:
named.append(
{"family": key, "field": name[:120], "rows": leak["judged"], "named": count}
)
- return determined, named, sorted(overflow), assessed, judged
+ return determined, named, sorted(unassessed), assessed, judged
def report(self):
families = [dict(family) for family in self.families.values()]
@@ -209,12 +209,12 @@ class Analytics:
if "first" in field and not field["varies"]:
constants.append(name[:120])
- determined, named, overflow, assessed, judged = self._leak_findings()
+ determined, named, unassessed, assessed, judged = self._leak_findings()
labelled = any(sum(1 for count in f["counts"] if count) > 1 for f in gold)
- unassessed = (
- f" {len(overflow):,} inputs with more than {VALUE_LIMIT:,} distinct values were not "
- "assessed."
- if overflow
+ unassessed_note = (
+ f" {len(unassessed):,} inputs with more than {VALUE_LIMIT:,} distinct values were "
+ "not assessed."
+ if unassessed
else ""
)
@@ -386,10 +386,10 @@ class Analytics:
for item in determined[:3]
)
+ (f" And {len(determined) - 3} more inputs." if len(determined) > 3 else "")
- + unassessed
+ + unassessed_note
if determined
else "No single input gives the label on 99% of the rows that share its value "
- f"with at least {SHARED_ROWS - 1} others.{unassessed}"
+ f"with at least {SHARED_ROWS - 1} others.{unassessed_note}"
if assessed
else "No JSON input fields were available to compare with the labels."
if labelled
@@ -399,7 +399,7 @@ class Analytics:
"determined_share": DETERMINED_SHARE,
"covered_share": COVERED_SHARE,
"findings": determined[:20],
- "unassessed_fields": overflow[:20],
+ "unassessed_fields": unassessed[:20],
},
),
check(
diff --git a/overbae/services/datasets/land.py b/overbae/services/datasets/land.py
index 2bcc9b65..f73b2e54 100644
--- a/overbae/services/datasets/land.py
+++ b/overbae/services/datasets/land.py
@@ -394,6 +394,13 @@ def _group(parts: list[Landing]) -> list[Landing]:
first.extend(empty)
landings = []
for members in groups.values():
+ # The store matches names ignoring case: a later file writes the first file's spelling.
+ spelling = {}
+ for part in members:
+ names = part.rows.source.names
+ for name in names.values():
+ spelling.setdefault(name.lower(), name)
+ part.rows.source.names = {raw: spelling[name.lower()] for raw, name in names.items()}
sources = [source for part in members for source in part.spec["sources"]]
landings.append(
Landing(
diff --git a/overbae/services/mcp/resources.py b/overbae/services/mcp/resources.py
index dfa1cf9b..fdde39df 100644
--- a/overbae/services/mcp/resources.py
+++ b/overbae/services/mcp/resources.py
@@ -304,10 +304,12 @@ def _dataset_upload_resource(uri: str) -> dict:
"Read the receipt or repeat reservation with the identical key to resume. Publication is separate from landing."
),
"multiple_files": (
- "Use overmind dataset upload FILE1 FILE2 ... --project-id PROJECT --json to publish "
- "one combined source version. Up to 100 ordered files and 2 GiB combined bytes "
- "share one durable transfer receipt; per-file type limits still apply. With --dataset, "
- "one attachment cell combines the whole batch with the preceding version. Original "
+ "Use overmind dataset upload FILE1 FILE2 ... --project-id PROJECT --json. Up to 100 "
+ "ordered files and 2 GiB combined bytes share one durable transfer receipt; per-file "
+ "type limits still apply. A new dataset lands one dataset per set of column names "
+ "(case and order ignored) and per workbook sheet, each with one source cell, listed in "
+ "source_spec.column_groups. With --dataset, the batch needs one set of columns and one "
+ "attachment cell combines it with the preceding version. Original "
"bytes and file-row evidence remain retained. Repeat the identical command after "
"interruption; changed file order, content or recipe conflicts under the same request key. "
"No dataset is published until every file is verified. --json-rows-field requires a single file. "
diff --git a/overbae/services/native_evaluation.py b/overbae/services/native_evaluation.py
index 1d7a2c61..1fba4d67 100644
--- a/overbae/services/native_evaluation.py
+++ b/overbae/services/native_evaluation.py
@@ -268,7 +268,8 @@ def create_plan(
config["authorization"] = existing.config["authorization"]
if existing.config.get("reuse"):
config["reuse"] = existing.config["reuse"]
- if existing.config != config or existing.name != name:
+ # A plan saved before purpose was recorded is a final measurement.
+ if {"purpose": "final", **existing.config} != config or existing.name != name:
raise InputValidationError(
"This request key already identifies a different frozen comparison"
)
@@ -688,10 +689,13 @@ def collect(plan, stage, receipt):
if digest_file(partial) != checksum:
raise InputValidationError("Native prediction artifact checksum differs.")
if preparing:
+ groups = preparation_groups(plan)
+ reused = plan.config.get("reuse", {})
for arm in participants(plan):
if (
arm["kind"] != "external"
- and preparation_groups(plan)[preparation_identity(arm)][0] == group
+ and arm["key"] not in reused
+ and groups[preparation_identity(arm)][0] == group
):
with replacing(directory(plan, role) / f"{arm['key']}.failures.jsonl") as copy:
shutil.copyfile(target, copy)
diff --git a/overbae/services/training_preparation.py b/overbae/services/training_preparation.py
index 3b62b8a0..faa4630e 100644
--- a/overbae/services/training_preparation.py
+++ b/overbae/services/training_preparation.py
@@ -21,7 +21,7 @@ from modal_shared.decisions import DECISION_OBJECTIVES
from modal_shared.modelfam import resolve
from modal_shared.preparation import processor_fingerprint as asset_fingerprint
from modal_shared.preparation import validate_preparation_report
-from modal_shared.stacks import train_function_name
+from modal_shared.stacks import TRAIN_DECISION, TRAIN_KEV, train_function_name
from modal_shared.training_data import file_digest
from overbae.core.errors import InputValidationError
from overbae.modal.decision_catalog import get as decision_catalog_model
@@ -49,6 +49,16 @@ def processor_fingerprint():
return asset_fingerprint(Path(__file__).parent / "sft_assets")
+def training_stack(model: str, objective: str) -> str:
+ """The image a job prepares and trains on. A decision objective needs the qualified
+ decision encoder, so it runs on the decision runtime unless its family brings its own
+ (Kev); a foundation's chat image does not carry that encoder."""
+ if objective not in DECISION_OBJECTIVES:
+ return get_unsloth_image(model)
+ family = resolve(get_hf_base(model) or model).train_image
+ return family if family in {TRAIN_DECISION, TRAIN_KEV} else TRAIN_DECISION
+
+
def request_preparation(
cell,
model: str,
@@ -105,11 +115,7 @@ def request_preparation(
"validation_fingerprint": validation_cell.fingerprint if validation_cell else None,
"processor": runtime["processor"] if runtime else processor_fingerprint(),
"data_format": runtime["data_format"],
- "stack": (
- resolve(get_hf_base(model) or model).train_image
- if objective in DECISION_OBJECTIVES
- else get_unsloth_image(model)
- ),
+ "stack": training_stack(model, objective),
}
signature = hashlib.sha256(json.dumps(config, sort_keys=True).encode()).hexdigest()
preparation, _ = TrainingPreparation.objects.get_or_create(
diff --git a/tests/test_dataset_column_groups.py b/tests/test_dataset_column_groups.py
index 8acf447b..e2b472ce 100644
--- a/tests/test_dataset_column_groups.py
+++ b/tests/test_dataset_column_groups.py
@@ -8,7 +8,7 @@ from openpyxl import Workbook
from rest_framework.test import APIClient
from overbae.models import Dataset, Project, ProjectMembership, User
-from overbae.services.datasets import files
+from overbae.services.datasets import files, paths, store
pytestmark = pytest.mark.covers("data-logic")
@@ -77,6 +77,10 @@ def test_each_set_of_columns_and_each_sheet_lands_as_its_own_dataset(client_proj
["book.xlsx"],
]
assert listed[3]["files"][0]["sheet"] == "refunds"
+ # One column per name, spelled as the first file spells it.
+ rows = list(store.iter_rows(paths.cell_path(primary.pk, primary.source.pk)))
+ assert [(row["input"], row["output"]) for row in rows] == [("q1", "a1"), ("q2", 2)]
+ assert "Output" not in rows[1]
assert all(d.source_spec["column_groups"] == listed for d in landed)
assert {d.project_id for d in landed} == {project.id}
assert all(not files.upload_data_path(upload_id).exists() for upload_id in ids)
diff --git a/tests/test_dataset_label_leakage.py b/tests/test_dataset_label_leakage.py
index c3694dee..121af9eb 100644
--- a/tests/test_dataset_label_leakage.py
+++ b/tests/test_dataset_label_leakage.py
@@ -4,6 +4,7 @@ import json
import pytest
+from overbae.services.datasets import analytics
from overbae.services.datasets.profile import profile_records
pytestmark = pytest.mark.covers("data-logic")
@@ -85,3 +86,23 @@ def test_labels_without_distinct_words_are_not_searched():
single = checks([row("refund", {"a": 1}) for _ in range(60)])
assert single["leakage.label_in_input"]["status"] == "not_applicable"
assert single["leakage.input_determines_label"]["status"] == "not_applicable"
+
+
+def test_an_input_past_the_tracked_fields_is_not_searched_for_its_label():
+ filler = {f"field_{i}": "x" for i in range(analytics.FIELD_LIMIT)}
+ records = [
+ row(label, {**filler, "queue": f"{label}-desk"}) for label in ["refund", "replacement"] * 60
+ ]
+ found = checks(records)
+ assert found["leakage.label_in_input"]["metrics"]["findings"] == []
+
+
+def test_inputs_with_too_many_values_leave_the_weights_check_alone():
+ records = [
+ row(label, {"order": index})
+ for index, label in enumerate(["refund", "replacement"] * (analytics.VALUE_LIMIT // 2 + 1))
+ ]
+ found = checks(records)
+ assert found["leakage.input_determines_label"]["metrics"]["unassessed_fields"] == ["order"]
+ weights = found["targets.weights"]
+ assert (weights["status"], weights["metrics"]["aggregate_overflow"]) == ("pass", False)
diff --git a/tests/test_dataset_preparation_activity.py b/tests/test_dataset_preparation_activity.py
index 822870dd..82c5621c 100644
--- a/tests/test_dataset_preparation_activity.py
+++ b/tests/test_dataset_preparation_activity.py
@@ -78,6 +78,14 @@ def test_a_preparation_is_one_row_from_its_first_script_to_its_publication():
]
+def test_a_preview_opens_no_preparation():
+ context = mcp_context(["read", "write"], client_name="codex")
+ dataset = frozen_dataset(context.project, ROWS, name="tickets")
+ job = {"kind": "dataset_pipeline", "id": "run", "status": "queued"}
+ _succeeded(context, "run_dataset_pipeline", dataset, run={"mode": "preview"}, job=job)
+ assert not Activity.objects.filter(project=context.project, kind="task_requested").exists()
+
+
def test_an_experiment_run_is_one_row_that_ends_with_the_run(eager, monkeypatch):
from overbae.tasks.assistant import run_turn
diff --git a/tests/test_decision_training.py b/tests/test_decision_training.py
index f439e4ee..47dadcc6 100644
--- a/tests/test_decision_training.py
+++ b/tests/test_decision_training.py
@@ -112,3 +112,20 @@ def test_native_full_weight_training_is_rejected_before_gpu_allocation(settings)
dataset = frozen_dataset(project, [example()], contract="train")
with pytest.raises(ValueError, match="decision training currently supports LoRA"):
request_preparation(dataset.active_cell, "Qwen/Qwen3.5-9B", 4096, training_type="full")
+
+
+def test_a_foundation_trains_decisions_on_the_qualified_decision_runtime():
+ from modal_shared.decisions import DECISION_OBJECTIVES
+ from modal_shared.stacks import NATIVE_FOUNDATION_STACKS, TRAIN_DECISION, TRAIN_KEV
+ from overbae.modal.model_registry import get_unsloth_image
+ from overbae.services.training_preparation import training_stack
+
+ decision = next(iter(DECISION_OBJECTIVES))
+ # A foundation offered for decision training has a chat image without the encoder.
+ assert get_unsloth_image("ornith-ai/Ornith-1.5-9B") in NATIVE_FOUNDATION_STACKS
+ assert training_stack("ornith-ai/Ornith-1.5-9B", decision) == TRAIN_DECISION
+ # Kev's trainer brings its own runtime; chat training keeps the family's image.
+ assert training_stack("jaredpalmer/kev-4b", decision) == TRAIN_KEV
+ assert training_stack("ornith-ai/Ornith-1.5-9B", "sft") == get_unsloth_image(
+ "ornith-ai/Ornith-1.5-9B"
+ )
diff --git a/tests/test_native_evaluation_variants.py b/tests/test_native_evaluation_variants.py
index b054aba5..61dd34cc 100644
--- a/tests/test_native_evaluation_variants.py
+++ b/tests/test_native_evaluation_variants.py
@@ -1,12 +1,13 @@
"""A native evaluation compares prompt variants of one model, and a development measurement
also reads decision training rows; a final one reads only an evaluation dataset."""
+import hashlib
import json
import pytest
from overbae.core.errors import InputValidationError
-from overbae.models import Dataset, FinetuningJob, Project
+from overbae.models import Dataset, FinetuningJob, NativeEvaluationPlan, Project
from overbae.services import native_evaluation
from overbae.services.datasets import land
from overbae.services.decision_providers import question
@@ -47,11 +48,13 @@ def job():
)
-def plan(job, final_cell, *, purpose="final", instructions="Answer as a cautious reviewer."):
+def plan(
+ job, final_cell, *, purpose="final", instructions="Answer as a cautious reviewer.", key=""
+):
return native_evaluation.create_plan(
job.project,
name="Prompts",
- request_key=f"{purpose}-{len(instructions)}",
+ request_key=key or f"{purpose}-{len(instructions)}",
final_cell=final_cell,
participants=[
{"key": "plain", "name": "Plain", "kind": "trained", "job": str(job.pk)},
@@ -103,3 +106,42 @@ def test_development_reads_training_decisions_and_final_refuses_them(job, tmp_pa
"state": "Evidence 0",
}
assert [row["reference"] for row in references] == [{"probabilities": [1, 0]}] * 3
+
+
+def test_a_plan_saved_before_purpose_was_recorded_retries_as_itself(job):
+ cell = suite(job.project, "eval", evaluation_row)
+ saved = plan(job, cell)
+ older = {k: v for k, v in saved.config.items() if k != "purpose"}
+ NativeEvaluationPlan.objects.filter(pk=saved.pk).update(config=older)
+
+ assert plan(job, cell).pk == saved.pk
+
+
+def test_a_shared_preparation_skips_a_variant_that_reuses_its_predictions(
+ job, tmp_path, settings, fake_modal
+):
+ settings.MEDIA_ROOT = tmp_path
+ cell = suite(job.project, "eval", evaluation_row)
+ source = plan(job, cell, key="source")
+ source.calls = {"final_careful": {"state": "completed", "receipt": {}}}
+ source.save()
+ predictions = native_evaluation.directory(source, "final") / "careful.jsonl"
+ predictions.parent.mkdir(parents=True)
+ predictions.write_text("")
+ variants = native_evaluation.reuse_predictions(
+ plan(job, cell, key="variants"),
+ source=source,
+ participant="careful",
+ source_participant="careful",
+ )
+ native_evaluation.seal_suite(variants, "final")
+ failures = b'{"key": "0"}\n'
+ fake_modal.files[f"/decision-evaluations/{variants.id}-final/failures.jsonl"] = failures
+
+ native_evaluation.collect(
+ variants, "final_prepare", {"failures_sha256": hashlib.sha256(failures).hexdigest()}
+ )
+
+ stage = native_evaluation.directory(variants, "final")
+ assert (stage / "plain.failures.jsonl").read_bytes() == failures
+ assert not (stage / "careful.failures.jsonl").exists()