The platform for continuously improving AI agents.
Rebuild the test suite around a product coverage map (#279)
Freyam Mehtafe6ddf78c71e
diff --git a/.agents/skills/mcp/SKILL.md b/.agents/skills/mcp/SKILL.mdindex 01293584..2564b63b 100644--- a/.agents/skills/mcp/SKILL.md+++ b/.agents/skills/mcp/SKILL.md@@ -117,12 +117,12 @@ Organize the catalog by intent: discovery and read, mutation, background work, C## Tests-Follow the testing policy in AGENTS.md: prove the change through existing E2E coverage first. These files hold focused coverage:+Follow the testing policy in AGENTS.md and the run-tests skill. A tool's happy path belongs to its vertical's journey; these files hold the edge cases. Call tools through `mcp_fixtures.call_tool`; only auth and transport tests go through the ASGI app (`mcp_fixtures.asgi_db`).| Change | Coverage || ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- || Contract or catalog metadata | `tests/test_mcp_catalog.py`, `tests/test_mcp_manifest.py` |-| Feature tool | `tests/test_mcp_<domain>.py`: happy path, project isolation, expected errors, structured output, returned IDs |+| Feature tool | `tests/test_mcp_<domain>.py`: project isolation, expected errors, structured output, returned IDs || Result format | `tests/test_mcp_result_compat.py` || Resource or job kind | `tests/test_mcp_resources.py` || Auth or transport | `tests/test_mcp_authorization.py`, `test_mcp_oauth.py`, `test_mcp_api_keys.py`, `test_mcp_account_access.py`, `test_mcp_transport.py` |diff --git a/.agents/skills/pr-etiquette/SKILL.md b/.agents/skills/pr-etiquette/SKILL.mdindex 547788c4..68b08cf9 100644--- a/.agents/skills/pr-etiquette/SKILL.md+++ b/.agents/skills/pr-etiquette/SKILL.md@@ -9,13 +9,13 @@ description: How to open a complete pull request on overmind-core/overmind — t`.github/workflows/ci.yml` runs five jobs on every non-draft PR; pushes to `main` run all but `migrations`. Run the equivalents locally rather than discovering them in CI:-| CI job | What it runs | Local equivalent |-| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |-| `lint` | `uv run ruff check .` and `uv run ruff format --check .` | the same two commands (`make lint-backend` fixes in place) |-| `frontend` | `bun run check`, `bun run typecheck`, `bun run check:all`, `bun run test` — in parallel, all must pass | same four, from `frontend/` |-| `test` | `uv run pytest tests/ -n auto --dist worksteal -q` | `make test` |-| `journeys` | `make test-journeys` with Postgres, Redis and Tesseract | `make test-journeys` |-| `migrations` | `makemigrations --check` on the merge commit plus `scripts/check_migrations.py`; only when `overbae/models/` or `overbae/migrations/` changed | `make check-migrations` |+| CI job | What it runs | Local equivalent |+| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |+| `lint` | ruff check and format, then the `coverage-map`, `agent-docs-size` and `test-seams` checks | `make lint-backend`, then `pre-commit run --from-ref origin/main --to-ref HEAD` |+| `frontend` | `bun run check`, `bun run typecheck`, `bun run check:all`, `bun run test` — in parallel, all must pass | same four, from `frontend/` |+| `test` | `uv run pytest tests/ -m 'not load' -n auto --dist worksteal -q` | `make test` |+| `journeys` | `make test-journeys` with Postgres, Redis and Tesseract, then the journeys budget | `make test-journeys` |+| `migrations` | `makemigrations --check` on the merge commit plus `scripts/check_migrations.py`; only when `overbae/models/` or `overbae/migrations/` changed | `make check-migrations` |`pre-commit run --files <changed files>` before committing substantial work. Note that `mdformat` reflows markdown, so commit its output rather than fighting it.@@ -86,14 +86,14 @@ you open the PR, search them for every name, limit, route, state and command youchanged, and update each match in the same PR:```bash-rg -n '<changed name>' AGENTS.md CONTRIBUTING.md DESIGN.md PRODUCT.md .agents/ overmind/skills/+rg -n '<changed name>' AGENTS.md CONTRIBUTING.md DESIGN.md .agents/ overmind/skills/```- `AGENTS.md` — the rules and traps every task needs.- `.agents/skills/*/SKILL.md` and their `references/*.md` — subsystem maps and procedures.- `.agents/hooks/` — a guard whose rule or message names what you changed. Hook wiring in `.claude/settings.json` and `.codex/hooks.json` changes together.- `overmind/skills/` — the user-facing skills that `overmind init` installs; a change there needs the SDK version bump above.-- `CONTRIBUTING.md`, `DESIGN.md` and `PRODUCT.md` when they describe the change.+- `CONTRIBUTING.md` and `DESIGN.md` when they describe the change.Update or delete the stale line; don't append a description of the new behaviourbeside it. There is one copy of each rule: put a fact in the skill that owns thediff --git a/.agents/skills/run-tests/SKILL.md b/.agents/skills/run-tests/SKILL.mdindex 7fc21192..e4f5c549 100644--- a/.agents/skills/run-tests/SKILL.md+++ b/.agents/skills/run-tests/SKILL.md@@ -5,7 +5,7 @@ description: How to run the platform test suites without wasting minutes — log# Running tests on this repo-Test runs here are expensive (`make test` about 75 s, frontend about 40 s, journeys about 6 min). Two rules:+Test runs here are expensive (`make test` about a minute, frontend about 40 s, journeys a few minutes). Two rules:## 1. Decide whether to run at all@@ -36,27 +36,60 @@ changing code, scoped to the failing files/tests:uv run pytest tests/test_foo.py::test_bar 2>&1 | tee "$SCRATCHPAD/pytest-rerun.log"```-## Journeys+## Coverage map++`tests/coverage_map.py` lists every entry a test may cover, ordered by severity.+Each test file sets `pytestmark = pytest.mark.covers("<entry>")`; a test inside it+that owns another entry takes its own `@pytest.mark.covers(...)`. Collection fails+on a test with no entry, an unknown entry, a promise outside `tests/journeys/` or+a second journey for a promise; the `coverage-map` hook fails when an entry has no+owner.++The SDK suite (`overmind/tests`, `make -C overmind test`) uses the same markers,+and its conftest loads the same collection guard; an SDK test never covers a+promise.-`make test-journeys` runs `tests/journeys/` against the live stack. It needs-the compose `postgres` and `redis` services, and uses Redis DB 15. Each journey-writes a run record to `tests/journeys/.runs/<timestamp>/`; read it for the-LLM requests, background task failures and the error. `make test` never-collects journeys: a parallel run without `OVERMIND_JOURNEY_XDIST` skips them, and so does any run without `TEST_REDIS_URL`. `make test-journeys` sets both and runs them with xdist (`-v`, `--dist loadfile`); each worker gets its own Redis DB, and DB 12 stays with the load subprocess. The journeys take several minutes, and CI runs them as their own job beside `test`;-`make test-journeys test_args="-k <name>"` runs one. `test_kit_*.py` files run one-journey per vendor (`tests/journeys/test_kit_connectors.py`, `test_kit_gpu_training.py`): a new-vendor joins its kit's parametrize list.+A Console test file (`frontend/src/**/*.test.ts(x)`) names its entry on one+`// covers: <entry>` line; the vitest setup fails a file without one, with an+unknown entry or with a promise. It may mock third-party modules and the network+edge (`@/client`, `@/openapi`); a `vi.mock` of our other modules is a seam that+`test-seams` counts.++| Severity | A failure means | Gate |+| -------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |+| S1 | A security breach, a wrong charge, or lost or changed data | One owning test at the lowest tier that reproduces; never quarantined; a fix ships with a test that fails before it |+| S2 | A vertical or the platform stops for every customer | One journey per promise; one owning test per platform invariant |+| S3 | One path, integration, model family or displayed fact is wrong | Contract tables (one row per dialect, vendor, provider) and logic tests |+| S4 | A heuristic or a presentation detail is wrong | A logic test only for a real edge case or a fixed bug |++A new behaviour joins an existing entry. A new entry or a new journey variant is a+change to the map, and so is a new promise.## Where a test belongs-- **Journey** (`tests/journeys/`): a customer promise across CLI, MCP, REST, SDK, worker and Console on the live stack. `tests/journeys/console/` builds the self-hosted Console (`bun run build`, ~4 s) and drives it with Playwright on its own thread; `uv run playwright install chromium-headless-shell` once per machine.-- **Contract kit** (`tests/test_*_contract.py`, `test_otlp_dialects.py`): one table over every vendor or dialect, the real client talking to a network fake.-- **Unit test**: pure logic with many edge cases, through a public entry point.+- **Journey** (`tests/journeys/test_<promise>.py`): the one end-to-end run of a product vertical across CLI, MCP, REST, SDK, worker and Console on the live stack. An edge case never gets its own journey; fold the assertion into the journey or test it at a lower tier.+- **Stack owner** (`tests/journeys/test_<entry>.py`): an invariant that needs the live worker, beat or API to reproduce, such as tenancy over every route or a cancelled GPU call.+- **Contract table** (`tests/test_*_contract.py`, `test_otlp_dialects.py`): one table over every vendor, dialect or provider, the real client talking to a network fake.+- **Unit test**: pure logic with real edge cases, through a public entry point.+- **Load check** (`pytest.mark.load`): capacity with wall-clock bounds. `make test` and `make test-journeys` skip them; `make test-load` runs them.+- **Migration replay**: a data migration that rewrites rows ships a replay test on `tests/migration_replay.scratch_database`. Delete the test once a published release has applied the migration.-The unit suite runs behind the same outbound guard as the journeys: sockets reach loopback only, and every HTTP call must be answered by `tests/fakes` (`fake_llm` is autouse; `fake_modal`, `sft`, `serving`, `clerk`, `stripe_api`, `scripted(host)`, `slept` on request). FakeLLM serves chat, streaming (`stream_rounds`), the OpenRouter catalog (`catalog_payload`, `limits`, `prices`), and Jev decisions (`decide`; the Jev path needs Redis, so point `CACHES` at `TEST_REDIS_URL`).+The unit suite runs behind the same outbound guard as the journeys: sockets reach loopback only, and every HTTP call must be answered by `tests/fakes` (`fake_llm` is autouse; `fake_modal`, `sft`, `serving`, `decisions`, `clerk`, `stripe_api`, `scripted(host)`, `slept` on request). FakeLLM serves chat, streaming (`stream_rounds`), the OpenRouter catalog (`catalog_payload`, `limits`, `prices`), and Jev decisions (`decide`; the Jev path needs Redis, so point `CACHES` at `TEST_REDIS_URL`).A known product defect gets a `pytest.mark.xfail(strict=True, reason=...)` control that asserts the correct behaviour; it turns red when the fix lands, and the marker goes.+## Journeys++`make test-journeys` runs `tests/journeys/` against the live stack with xdist (`--dist loadfile`, one Redis DB pair per worker; DB 12 stays with the load subprocess). It needs the compose `postgres` and `redis` services. The Console builds once per run into a shared folder and each worker serves it against its own API; `uv run playwright install chromium-headless-shell` once per machine. Each journey writes a run record to `tests/journeys/.runs/<timestamp>/`; read it for the LLM requests, background task failures and the error. `make test` never collects journeys. `make test-journeys test_args="-k <name>"` runs one.++A journey waits on observable state (`drain`, `drain_scoring` before it reads scores, `settle`, `until`, `console.sees`), never on wall time, animations or fonts; the `test-seams` hook refuses new ones.++CI fails when the journeys run takes longer than `JOURNEY_BUDGET_SECONDS` (`tests/coverage_map.py`) or one test takes more than a third of it. Make a slow journey cheaper by moving its edge cases to a lower tier.++## Database transactions++Tests run inside a rolled-back transaction by default. Call MCP tools with `mcp_fixtures.call_tool`: it runs thread-sensitive handlers on the test thread and runs on-commit work. Use `django_db(transaction=True)` only when another thread or process must see the rows (the ASGI MCP app takes `mcp_fixtures.asgi_db`, sandboxes, admission races). After such a test, only the tables it wrote are emptied.+## Gotchas- Backend tests need the compose `postgres` service on `localhost:5432`diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdindex 2ac29adc..eb166917 100644--- a/.github/PULL_REQUEST_TEMPLATE.md+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -26,7 +26,7 @@- [ ] **MCP** — classify (MCP-ready / CLI-guided / frontend-only / out of scope); catalog, contracts, tools, prompts, resources, `tests/test_mcp_*.py`- [ ] **Blast radius** — celery routing, `seed_demo`, generated OpenAPI client- [ ] **Docs** — `overmind-core/docs` PR opened and linked, if user-visible behaviour changed-- [ ] **Agent instructions** — searched `rg -n '<changed name>' AGENTS.md CONTRIBUTING.md DESIGN.md PRODUCT.md .agents/ overmind/skills/`; each stale line updated or deleted in this PR, not appended to+- [ ] **Agent instructions** — searched `rg -n '<changed name>' AGENTS.md CONTRIBUTING.md DESIGN.md .agents/ overmind/skills/`; each stale line updated or deleted in this PR, not appended to## Checklistdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 36174983..247f7edd 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -40,6 +40,9 @@ jobs:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v4+ with:+ # HEAD^1 is the base this change merges into; test-seams counts against it.+ fetch-depth: 2- uses: astral-sh/setup-uv@v6with:@@ -53,6 +56,12 @@ jobs:- name: Run ruffrun: uv run ruff check . && uv run ruff format --check .+ - name: Check the coverage map, test seams and agent docs+ run: |+ uv run python scripts/check_coverage_map.py+ uv run python scripts/check_agent_docs.py+ PRE_COMMIT_FROM_REF=HEAD^1 uv run python scripts/check_test_seams.py+# Frontend install once, then biome / tsc / vitest in parallel.# Add this job as a required status check if branch protection still only lists `lint`.frontend:@@ -190,7 +199,7 @@ jobs:- name: Run tests# Match local `make test`: xdist is already in the test dep group.- run: uv run pytest tests/ -n auto --dist worksteal -q+ run: uv run pytest tests/ -m 'not load' -n auto --dist worksteal -qjourneys:if: github.event_name == 'push' || github.event.pull_request.draft == false@@ -259,4 +268,7 @@ jobs:run: sudo apt-get update && sudo apt-get install -y tesseract-ocr tesseract-ocr-eng tesseract-ocr-osd tesseract-ocr-fra tesseract-ocr-spa- name: Run journeys- run: make test-journeys+ run: make test-journeys test_args="--junitxml=journeys.xml -o junit_duration_report=call"++ - name: Check the journeys budget+ run: uv run python scripts/check_journey_budget.py journeys.xmldiff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 69d04845..2bf0d127 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -34,7 +34,14 @@ repos:name: no new patches of our own code or private imports in testsentry: uv run python scripts/check_test_seams.pylanguage: system- files: "^tests/.*\\.py$"+ files: "^(tests/.*\\.py|overmind/tests/.*\\.py|frontend/src/.*\\.test\\.tsx?)$"+ pass_filenames: false+ - id: coverage-map+ name: every coverage-map entry has an owning test+ entry: uv run python scripts/check_coverage_map.py+ language: system+ files: "^(tests/.*\\.py|overmind/tests/.*\\.py|frontend/src/.*\\.test\\.tsx?)$"+ pass_filenames: false- id: agent-docs-sizename: AGENTS.md and skills stay within agent load limitsentry: uv run python scripts/check_agent_docs.pydiff --git a/AGENTS.md b/AGENTS.mdindex 599dca2d..12e22640 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -35,7 +35,7 @@ This file is the playbook every task needs; Claude Code, Codex and Cursor read i- Code under `overbae/modal/`, `modal_shared/` and `overbae/services/sft_assets/` reaches Modal only after `modal deploy`; training and serving pin immutable releases.- Naming: UI "Optimiser" is backend `optimizer`; UI "Training" is backend `finetuning`; UI "Capability" is the `Capability` model, and the sidebar's "Agent" is the project graph.- Overwatch (`/api/internal/overwatch/*`, app in `sales-dashboard/`) only reads product records and runs no user authentication. Its tokens, caches and Slack boundary are in backend-architecture `references/auth-and-billing.md`.-- `DESIGN.md` and `PRODUCT.md` carry a fixed YAML frontmatter schema that tooling reads. Extend the values; don't restructure the documents.+- `DESIGN.md` carries a fixed YAML frontmatter schema that tooling reads. Extend the values; don't restructure the document.Subsystem detail lives in the skills: backend-architecture (Celery, tracing and scoring, evaluation, capabilities, auth and billing, training, serving, data-first), data-workshop, mcp, frontend-design.@@ -67,16 +67,16 @@ Instrument voice: state the fact and stop ("9 rows", not "9 rows — small enoug### Naming-Name by behavior. Plan-phase labels (P0/P1, "Phase N") stay out of code, comments and test names. Backend tests live flat in `tests/test_<feature>.py`; journeys in `tests/journeys/test_<promise>.py`.+Name by behavior. Plan-phase labels (P0/P1, "Phase N") stay out of code, comments and test names. Backend tests live flat in `tests/test_<feature>.py`; journeys in `tests/journeys/test_<promise>.py`, and stack-tier owners beside them as `test_<entry>.py`.## Workflow-- Don't write unit tests after you write code. Prefer E2E tests as the testing mechanism. Each E2E run ends with a repeatable artifact: the command, inputs or fixtures, environment requirements and observed results.-- If a system must be tested in isolation, first write down the ways it can fail, then write the code. Keep an isolated test only when it catches a concrete failure that E2E coverage misses. No assertions that mirror the implementation, pin incidental text or restate declarations.-- Tests fake only what we do not own, and only at the network (`tests/fakes`: FakeLLM, FakeModal, vendor, Stripe and Clerk APIs, `scripted` HTTP). Patch `overbae.*` only to capture a Celery `.delay`/`.apply_async`; call public entry points. Each contract has one owning test, and a journey owns a customer promise. The `test-seams` pre-commit hook refuses new seams. Detail: run-tests skill.+- Every test covers one entry of `tests/coverage_map.py` through `pytest.mark.covers`, or a `// covers: <entry>` line in a Console test file; collection refuses a test that covers nothing. A promise is a product vertical with exactly one journey; an edge case is an invariant, contract or logic entry, never a new journey. Severity (S1–S4) sets the gate (run-tests skill).+- Test at the lowest tier that reproduces the behaviour, with one owning test per behaviour. A fix ships with a test that fails before it and passes after it. No assertions that mirror the implementation, pin incidental text or restate declarations. Each journey run leaves a run record in `tests/journeys/.runs/`.+- Tests fake only what we do not own, and only at the network (`tests/fakes`: FakeLLM, FakeModal, vendor, Stripe and Clerk APIs, `scripted` HTTP). Patch `overbae.*` only to capture a Celery `.delay`/`.apply_async`, and never `overmind.*`; call public entry points. Each contract has one owning test. The `test-seams` check (pre-commit and CI) refuses a rise in seams across all test files; moving a test passes. Detail: run-tests skill.- Stay in the asked scope: fix the stated thing plus genuine prerequisites, and list adjacent findings as "found but did not change". If the task is much bigger than framed, say so before editing.- Simple, self-evident fixes need typecheck and lint only; say plainly that tests did not run. When a suite run is warranted, run it once, tee to a log and grep the log.-- Which tests to run (compose Postgres and Redis up): while editing, the feature's test file and its journey (`make test-journeys test_args="-k <name>"`); before a push, `make test` (about 75 s); when a change crosses ingest, sync, the worker, the gateway, MCP or the Console, `make test-journeys` (about 6 min). CI runs the rest.+- Which tests to run (compose Postgres and Redis up): while editing, the feature's test file and its journey (`make test-journeys test_args="-k <name>"`); before a push, `make test`; when a change crosses ingest, sync, the worker, the gateway, MCP or the Console, `make test-journeys`; after a change to admission, landing or streaming, `make test-load`. CI runs the rest.- A change is finished when every surface that reflects it is updated: MCP, Celery routing, `seed_demo`, the generated client, this file and the skills, and the docs repo at `../docs` (pr-etiquette skill lists them). CI cannot catch these.- When a change makes this file, a skill, a hook message or another agent doc untrue, update or delete that line in the same PR; the pr-etiquette skill lists the places to search. There is one copy of every rule.- Commit messages: short subject plus at most one body line, no co-author trailers. Commit and push only when asked; on a sweep branch, one commit per observation.diff --git a/Makefile b/Makefileindex 1f89262a..603022dc 100644--- a/Makefile+++ b/Makefile@@ -1,4 +1,4 @@-.PHONY: test test-serial test-journeys lint-format lint-backend lint-frontend install-hooks psql worker sandbox check-migrations+.PHONY: test test-serial test-journeys test-load lint-format lint-backend lint-frontend install-hooks psql worker sandbox check-migrationsinstall-hooks:uv run pre-commit install@@ -61,11 +61,14 @@ WORKERS ?= autotest_args ?=test: ## Run all tests in parallel (default)- uv run pytest tests/ -n $(WORKERS) --dist worksteal -q $(test_args)+ uv run pytest tests/ -m 'not load' -n $(WORKERS) --dist worksteal -q $(test_args)test-serial: ## Run all tests serially (for debugging)uv run pytest tests/ -v $(test_args)test-journeys: ## Run end-to-end journeys on the live stack (needs compose Postgres and Redis)TEST_REDIS_URL=redis://localhost:6379/15 OVERMIND_JOURNEY_XDIST=1 \- uv run pytest tests/journeys -n $(WORKERS) --maxprocesses 6 --dist loadfile -v -o console_output_style=count --durations=10 $(test_args)+ uv run pytest tests/journeys -m 'not load' -n $(WORKERS) --maxprocesses 6 --dist loadfile -v -o console_output_style=count --durations=10 $(test_args)++test-load: ## Run the capacity checks with wall-clock bounds (needs compose Postgres and Redis)+ TEST_REDIS_URL=redis://localhost:6379/15 uv run pytest tests/journeys tests/test_dataset_scale.py -m load -v $(test_args)diff --git a/PRODUCT.md b/PRODUCT.mddeleted file mode 100644index 35d7f0f7..00000000--- a/PRODUCT.md+++ /dev/null@@ -1,331 +0,0 @@-# Product--<!-- impeccable:product-schema 1 -->--## Platform--web--## Users--AI engineers at startups shipping LLM agents to production. Small teams without-dedicated eval/training infrastructure who need their agents to get better —-and cheaper — using what production already tells them. They live in their-repo and terminal; the Console is where they inspect, decide, and launch work,-not where they live all day.--## Product purpose--Overmind is an agent improvement platform with one goal: continuously improve-agents running in production using real usage data. Success is a team shipping-a measurably better agent (accuracy, cost, reliability) as a scored change in-their own codebase — a diff or coding-agent prompt — driven by their own-production traces.--## Positioning--**The agent model is the product.** Overmind builds a model of a team's-agents (capabilities, behaviours, prompts, and tools) by scanning their repo,-pinning every component to the file and line that defines it. Telemetry binds-to that model. Teams can also start with uploaded data and a written task,-without scanning a repository. The public framing: Overmind builds-a model of the agent and uses traces to validate it.--That model is what the rest depends on:--- **Generated evals.** Each capability card records what the capability does.- Rubrics compile from the card into weighted pass/fail checks the team reviews- before anything is scored, scoped per capability so a triage capability is- not graded on a planner's criteria.-- **Measured coverage.** Discovered components are reconciled against actual- instrumentation and scored `N of M`, with every silent component named and a- fix prompt offered.-- **Changes land as diffs.** The optimiser skill (`/overmind optimise`)- drives a local SDK that edits the team's real agent repo; candidates are- real git diffs scored on the same eval set as the baseline, so every gain is- a measured delta.-- **Team-owned models.** Production traces become the training signal for- private per-team fine-tuned models, benchmarked against the incumbent model- running in production and served on an OpenAI-compatible endpoint.--Each stage feeds the next. Repository workflows use the graph; data-first-model workflows use a saved task interpretation, data lineage and comparison-protocol.--## Operating context--- Data-first onboarding leads to the existing cell-based Workshop. The native coding agent explores- the source and authors explicit transformations through MCP. Saved group-preserving- partitions, standalone decision comparisons, explicit training experiments and- reproducible performance workloads make this path available through Console- and MCP. Calibration and development selection stay separate from final results;- coverage, identity uncertainty and partial cost accounting remain inspectable.- Frozen-source derivation, bounded exploration and sampling feasibility precede- draft/prepare/launch workflows. Saved receipts recover after reconnects; explicit- compatible prediction reuse avoids duplicate work. Runtime profiles and user-defined- planning constraints separate measured evidence from unknown costs.--- Teams instrument agents with the `overmind` SDK (PyPI) or- `@overmind-lab/trace-sdk` (npm), or send existing telemetry via OTLP ingest- (`POST /api/v1/traces`) and connector sync (Langfuse, LangSmith, Braintrust,- Galileo) — no re-instrumentation required.- The public promise is "no wrapper classes, no rewrites, no proprietary wire- format": one SDK setup auto-instruments the LLM libraries already in use,- over OpenTelemetry.--- Capability discovery is local (`overmind setup` → `overmind.toml` →- `overmind sync`). After a fine-tune, the Console and MCP return a copy-paste- prompt that points the capability's code at the new model.--- Optimisation runs from the agent's own repo after `overmind sync`: paste- `/overmind optimise` in the coding agent; the skill drives the SDK, the server- scores candidates, and results return as scores and diffs.--- The Console (console.overmindlab.ai) is where teams manage projects, inspect- agents, browse observability data, build datasets, run evaluations and- optimisation experiments, train and deploy models, monitor jobs, and chat- with frontier or deployed models.--- Separate web properties: the Console, a public marketing site at- www.overmindlab.ai, docs at docs.overmindlab.ai, and a public Discord. The- SDK/CLI lives in the sibling `overmind` repo.--### The four public pillars--The marketing site organises the product under `/product/` into four pillars.-These are the customer-facing names and claims, and they are the vocabulary-future work should match:--| Pillar | Headline | Promise |-| ------------------ | ------------------------------- | ------------------------------------------------------------------------------------------ |-| **Observability** | "Understand your agents" | Capability scanning, automatic tracing, coverage scoring, live scoring on arrival |-| **Data Workshop** | "Turn real behaviour into data" | Production traces become versioned training and eval data through explicit transformations |-| **Agent Testing** | "Measure and improve" | Generated evals, scored candidates, winning diffs in the team's repo |-| **Model Training** | "Own your model" | Fine-tune on your own data, benchmark against the incumbent, serve it |--The pillars line up with the Console's navigation groups. Keep the two-taxonomies in sync rather than letting them drift. Site CTAs are **"Start for-free"** and **"Book a call"**: self-serve signup and a sales conversation.--## Capabilities and constraints--### Console surfaces--Navigation order: Overmind (home), Agent, Observability, Datasets, then an-**Agent Testing** group (Evaluations, Optimiser) and a **Models** group-(Training, Inference), then Settings and Projects. Docs and Discord are-external links. A command palette provides keyboard navigation.--- **Observability** — a metrics overview of scored quality, errors, speed, recorded- cost and recurring behaviour, with Sessions, Signals and Traces as investigation- views. Trace detail retains span trees and flame charts.-- **Agent** — the product graph: one agent per project, made of capabilities- (Agent > Capabilities > Tasks) mapped from a local scan, with each capability's- prompt, tools, control flow, and input/output contracts pinned to file and- line. A capability the scan no longer finds leaves the agent and returns in- place when the code does; a hand delete hides a capability and keeps its data.-- **Datasets / Data Workshop** — promote production traces into datasets,- filtered by capability, eval score, or time window. Dataset intent is named- **Train** (formerly "ft").-- **Evaluations** — runs and samples, generated rubrics, multiple evaluator- kinds, per-metric scores with rationale, LLM-judge cost reported in credits.-- **Optimiser** — Console lists experiments; start them in a coding agent with- `/overmind optimise` (harness) or `/overmind backtest` (model comparison).- Note the spelling split: all prose and UI copy use "Optimiser" and the CLI- command is `overmind optimise`, but backend and SDK identifiers still spell- it `optimizer` (models, modules, API routes, OTel attributes).-- **Training** — fine-tuning jobs, checkpoints, and deployment. Renamed from- "Fine-tuning" in the UI; backend code and modules still use `finetuning`.-- **Inference** — deployed models and per-model detail.-- **Jobs, Models, Projects, Settings** — background work, catalogue,- workspaces, and integrations/API keys.--All surfaces are available to every team. Feature flags remain in the-navigation code but are no longer used to stage access.--### Data Workshop specifics--- Final-output cells expose server-measured Metrics alongside Script/Data, with- alert chips on Data while Metrics is collapsed. Counts, baselines, evidence,- warnings and unperformed checks are bound to the exact data fingerprint and- also delivered through MCP after transformation. These are advisory findings,- not an automatic training-quality approval or a rebalancing policy.--- Data Workshop opens with a project dataset table showing purpose, source,- row count, active version, capability and update time. Selecting a dataset opens- its unchanged, full-size cells on a grid-snapped flow canvas at scale 1:- steps progress downward, sibling branches align side by side on the same layer,- with elbow connections from recorded lineage. Zoom, Fit view and a toggleable- minimap navigate the graph without changing cell dimensions; Reset and linked-cell- focus return to scale 1. Corrections replace the displayed process; there is no repair-history or restore view. Recorded partition links keep train, development, calibration and final outputs connected to their source and scripts.- The right-hand box groups the minimap toggle with the folder button for project- dataset navigation; cell search and the cell-selector strip are removed.- Platform-agent chat and the prompt-style landing are removed.--- The native coding agent owns planning, interpretation, transformation code,- generation and semantic judgment. The platform owns source landing, version- identity, deterministic execution, lineage, impact and consumer pinning.--- Sources may be files, pasted rows or traces; source-free briefs are supported.- Documents and images retain original bytes and extraction evidence, including- local English OCR where needed. Intent is explicit and otherwise stays pending.--- Agents discover reusable project transformations, then validate and preview- against a pinned source. Revisions retain ordered scripts, declared contracts,- parameters and an approved immutable runtime. Compatible sources reuse the exact- revision; adaptations record their origin without changing the original.- Each successful run publishes one cell per step atomically. Preview publishes none.- Agents declare step IDs, input edges and code-referenced branch conditions in the- retained recipe. MCP returns this flow explicitly; execution receipts separately- record actual input cells and output counts. Condition labels are declarations,- not independent verification of script semantics.--- Script packages run in isolated, resource-bounded containers without network or- platform credentials. Native agents own authoring, semantic work and interpretation.- Imported outputs declare all source parents and producer attribution.- Large outputs use an uploaded, checksum-bound artifact. Source attribution- does not independently verify execution or answer correctness.--- Retries with the same request key recover the same work; changed inputs conflict.- Failed or cancelled transformations never replace a readable version.- Runs have durable receipts; unknown work is not blindly replayed.--- Explicitly enabled bindings reuse an exact revision as source datasets or trace- selections change. These are full-snapshot rebuilds, not assumed incremental- scripts. Checkpoints advance only with publication; failed work requires explicit- retry authorization. Existing training and evaluation inputs do not change.--- Technical fit, source preservation, coverage and semantic quality are distinct.- Unmeasured quality stays unknown. Quality findings remain advisory; unreadable- or technically incompatible data blocks consumer use.--- Evaluation, Optimiser and Training freeze the exact version consumed.- Later transformations do not modify those inputs. Training owns- model-specific preprocessing; Workshop remains model-independent.--- MCP is the first-class authoring surface. Chat, mutable-cell editing and script- replay are unavailable in the Console. Native-agent intake inspects record- boundaries before upload and verifies landed counts and values before handoff;- successful transfer does not establish correct ingestion.--### Training and serving specifics--- Up to four tiered experiments are recommended from dataset statistics and- live traffic, **Compact to Large**; adapter training for speed or a full- fine-tune for depth; trace-safe splits.-- Train/validation loss and token accuracy chart live during the run. Development- monitoring adds frozen samples, measured check timing, generated-label/schema/field- evidence and verified retained checkpoints. Early stopping and best-development- checkpoint selection require explicit settings; warnings do not alter training.- Classification observations compare the same scored sample with its majority- baseline and expose represented labels without predictions. These are not- diagnoses or final-test results. Newer loss-only checks do not hide the last- generated-output result from the coding agent.-- Selected final benchmarks compare the trained model with the pinned base or- incumbent. They remain independent of development monitoring. Missing exact- OpenRouter routes and invalid evaluator definitions are visible failures, not- permission to substitute a model or silently launch hosted base inference.-- Successful training automatically deploys each model through its matching- inference runtime. Chat models use shared BF16 adapters or private checkpoints;- decision models retain their verified adapter and full-precision probability- head. Deployment does not change application routing.-- Training and serving run on **Modal** and **Baseten**. Nebius has been- removed. The model catalogue (`/api/models/catalog/`) can disable specific- models, and large models are currently disabled — a live constraint that- contradicts the public "Compact to Large" tiering until re-enabled.--### Platform facts--- Inference is an OpenAI-compatible API (`/api/v1/chat/completions`,- `/api/v1/models`, `/api/v1/models/<model_id>`) covering frontier models and- deployed fine-tuned models.-- Decision deployments accept input-only decisions at- `/api/deployed-models/{id}/inference/` and return a durable request receipt.- `/api/inference-requests/{id}/` exposes ordered probabilities and the exact- artifact identity. They are not chat-completion models.-- Billing meters usage on an append-only credits ledger. **Remaining-credit- caps, Free/Pro plans, Stripe Checkout and top-ups** inject only when- `STRIPE_SECRET_KEY` is set (cloud). Without it (OSS) the Console still shows- spend and usage history, with no remaining-credit cap. The marketing site- owns `/pricing`; the Console's legacy `/pricing` route only redirects there.-- Auth is Clerk, plus issued API keys for SDK/CLI access. Product analytics is- PostHog.-- Training delivery analytics measures result availability, check completion,- coverage, measured overhead and reload-verified checkpoints. It excludes raw- training content and does not infer clarity or delight. Local analytics is off- unless explicitly configured; underlying delivery receipts remain available.--### Stack--Django API (`overbae`) with Celery workers, and a React 19 Console (Vite,-TanStack Router/Query/Table/Form/Virtual, Tailwind v4, Radix, Clerk). Tooling-is `bun` for the frontend and `uv` for the backend; Biome lints the frontend.-The frontend API client is generated from the backend schema-(`make generate_api_client` → `frontend/src/openapi/`) and is never-hand-edited.--### Terminology in product voice--Console, traces/spans, coverage, Observability, Data Workshop,-Agent Testing, Optimiser, executioner, Experiments, incumbent, Training-(marketing writes it as **Model Training**), credits. The hierarchy is-Agent > Capabilities > Tasks: "Agent" is the product (one per project),-"Capability" is a node inside it, "Task" is reserved. Never "Behaviour" or-"Mode" in product copy.--## Brand commitments--- Name: **Overmind** (company: Overmind Lab; domains `overmindlab.ai`,- packages `overmind` on PyPI, `@overmind-lab/trace-sdk` on npm).-- Logo assets exist at `frontend/src/assets/`: `overmind-eye-copper.svg`,- `overmind-eye-mono.svg`, `overmind-union.svg` (an eye mark with copper and- mono variants, plus a union wordmark).-- API codename `overbae` is internal, not customer-facing.-- Public voice is declarative and mechanism-first: short claims stated as- fact ("The agent model is the product", "Stop guessing, start measuring",- "No ML infra"), each backed by the specific thing the system does.--## Evidence on hand--- A working product: live Console, SDK on PyPI/npm, OTLP + connector ingest,- repo scanning into a capability model, generated evals, server-driven- optimisation producing real scored diffs, and training through to- deployed models.-- Stage: design partners / pilots. A handful of teams use it under the radar;- there has been no public launch and **no publicly citable customers**.-- The public marketing site carries **no customer logos, testimonials, case- studies, or benchmark numbers** — its proof is the mechanism described in- specifics. Match that standard.-- Future work must not fabricate testimonials, customer logos, case studies,- usage numbers, or benchmark results. Truthful evidence is the product- mechanism itself (the graph, the loop, the Console, real docs) until pilots- convert to public proof.--## Product principles--1. **Every feature reads the scanned agent.** Discovery, coverage, evals,- optimisation, and training recommendations all read the scanned capability- model. A feature that invents its own model of the agent duplicates the- part that is hard to copy.-1. **Every feature advances the loop.** Each page moves a team from trace to- dataset, to eval, to optimize or train, to a shipped change. A feature that- dead-ends outside the loop is off-strategy.-1. **Real production data over synthetic demos.** Improvements are grounded in- what the agent actually did in production, not hand-written examples.-1. **Measured, not asserted.** Candidates and models are scored against a- baseline or incumbent on the same eval set. Claim a gain only where there is- a delta to point at.-1. **Meet engineers where change ships.** The repo, CLI, and coding agent are- the destination; the Console orchestrates and explains, but the win lands in- the team's own codebase.-1. **Only truthful proof.** At pilot stage, credibility comes from showing the- real mechanism working — never invented social proof or numbers.--## Accessibility and inclusion--No formal conformance standard has been set for this product — that decision is-open. Two constraints hold in the current implementation and future work must-preserve them: the Console ships a **single dark theme**, independent of stored-or operating-system preferences, and motion **respects `prefers-reduced-motion`**.--Script retention is automatic; the native agent owns preparation and repairs. Workshop cells show retained data and scripts, while execution receipts record publication validation.diff --git a/frontend/scripts/check-controls.mjs b/frontend/scripts/check-controls.mjsindex 11b00b34..8b460208 100644--- a/frontend/scripts/check-controls.mjs+++ b/frontend/scripts/check-controls.mjs@@ -125,7 +125,7 @@ const HEIGHT = {const ACRONYMS =/^(API|PR|LLM|OK|JSON|CSV|JSONL|ID|IDs|GitHub|OpenAI|GPU|OTEL|SDK|CLI|UI|URL|LoRA|FT|N\/A)$/;-// Proper nouns exempt from sentence case (PRODUCT.md terminology). Matched as+// Proper nouns exempt from sentence case. Matched as// whole phrases, so "Data" clears only inside "Data Workshop". Add terms here// rather than loosening the word-level check.const PRODUCT_TERMS = [diff --git a/frontend/src/auth-redirect.test.tsx b/frontend/src/auth-redirect.test.tsxindex 1a174c77..3a4b5ee5 100644--- a/frontend/src/auth-redirect.test.tsx+++ b/frontend/src/auth-redirect.test.tsx@@ -1,5 +1,6 @@// @vitest-environment jsdom// @vitest-environment-options {"url":"http://127.0.0.1:5173"}+// covers: authenticationimport { QueryClientProvider } from "@tanstack/react-query";import {diff --git a/frontend/src/client.guest.test.ts b/frontend/src/client.guest.test.tsindex d45cb714..0241727e 100644--- a/frontend/src/client.guest.test.ts+++ b/frontend/src/client.guest.test.ts@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: authenticationimport { afterEach, describe, expect, it, vi } from "vitest";import { dismissGuestPrompt, GuestUpgradeError, onGuestUpgrade } from "@/lib/guest";diff --git a/frontend/src/client.uploads.test.ts b/frontend/src/client.uploads.test.tsdeleted file mode 100644index 25fa065c..00000000--- a/frontend/src/client.uploads.test.ts+++ /dev/null@@ -1,36 +0,0 @@-// @vitest-environment jsdom--import { afterEach, expect, it, vi } from "vitest";--import apiClient from "./client";--afterEach(() => {- vi.unstubAllGlobals();- localStorage.clear();-});--it("inspects uploads through the registered generated client", async () => {- const fetchMock = vi.fn().mockResolvedValue(- new Response(JSON.stringify({ bytes: 120, filename: "rows.csv", rows: 15 }), {- headers: { "Content-Type": "application/json" },- status: 200,- })- );- vi.stubGlobal("fetch", fetchMock);- localStorage.setItem("jwt_access", "test-access-token");-- const inspected = await apiClient.uploads.uploadsInspectCreate({- id: "test-upload",- inspectUploadRequest: { size: 120 },- });-- expect(inspected).toEqual({ bytes: 120, filename: "rows.csv", rows: 15 });- expect(fetchMock).toHaveBeenCalledWith(- expect.stringMatching(/\/api\/uploads\/test-upload\/inspect\/$/),- expect.objectContaining({- body: JSON.stringify({ size: 120 }),- headers: expect.objectContaining({ Authorization: "Bearer test-access-token" }),- method: "POST",- })- );-});diff --git a/frontend/src/components/capability-detail/ModelsTab.test.tsx b/frontend/src/components/capability-detail/ModelsTab.test.tsxindex 5c424f67..8573ec4a 100644--- a/frontend/src/components/capability-detail/ModelsTab.test.tsx+++ b/frontend/src/components/capability-detail/ModelsTab.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport type { ReactNode } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";@@ -206,16 +207,6 @@ describe("ModelsTab alias routing", () => {});});-describe("ModelsTab benchmarks", () => {- it("keeps benchmark selection in training setup, separate from live routing", () => {- renderTab({ count: 1, results: [model("m-live")] }, { ...capability, activeModel: "m-live" });- expect(screen.queryByRole("columnheader", { name: "Benchmark" })).toBeNull();- expect(screen.queryByLabelText(/as benchmark/)).toBeNull();- expect(screen.getByLabelText("ft:m-live is live")).toBeTruthy();- expect(mocks.capabilitiesPartialUpdate).not.toHaveBeenCalled();- });-});-describe("ModelsTab serving state", () => {it("uses inference worker state and omits request-history noise", () => {const routed = { ...bareCapability, activeModel: "m-live" } as unknown as Capability;diff --git a/frontend/src/components/capability-detail/flow/TrajectoryCondition.test.tsx b/frontend/src/components/capability-detail/flow/TrajectoryCondition.test.tsxindex e8eaff2c..4fbe823c 100644--- a/frontend/src/components/capability-detail/flow/TrajectoryCondition.test.tsx+++ b/frontend/src/components/capability-detail/flow/TrajectoryCondition.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, expect, it } from "vitest";diff --git a/frontend/src/components/capability-detail/flow/TrajectoryNodes.test.tsx b/frontend/src/components/capability-detail/flow/TrajectoryNodes.test.tsxindex 589412aa..8d4b355f 100644--- a/frontend/src/components/capability-detail/flow/TrajectoryNodes.test.tsx+++ b/frontend/src/components/capability-detail/flow/TrajectoryNodes.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, fireEvent, render, screen, within } from "@testing-library/react";import { type EdgeProps, type NodeProps, Position, ReactFlowProvider } from "@xyflow/react";import { afterEach, describe, expect, it, vi } from "vitest";@@ -136,32 +137,6 @@ describe("trajectory model call card", () => {expect(onClick).not.toHaveBeenCalled();});- it("shows a branch's local outcome and continuation", () => {- const OutcomeNode = trajectoryNodeTypes.outcome;- render(- <ReactFlowProvider>- <OutcomeNode- {...({- data: {- branch: {- action: "Read dropdown options",- basis: "code",- condition: "Element is a select input",- next: "Return choices to the model",- outcome: "Available choices",- provenance: [],- },- kind: "outcome",- },- id: "branch",- } as unknown as NodeProps)}- />- </ReactFlowProvider>- );- expect(screen.getAllByText("Available choices").length).toBeGreaterThan(0);- expect(screen.getAllByText("Return choices to the model").length).toBeGreaterThan(0);- });-it("groups provider and model identity while retaining the behaviour and contract", () => {renderStep();const chip = screen.getByTestId("model-chip");diff --git a/frontend/src/components/capability-detail/flow/TrajectoryRunPicker.test.tsx b/frontend/src/components/capability-detail/flow/TrajectoryRunPicker.test.tsxindex 3362382a..9a1a1312 100644--- a/frontend/src/components/capability-detail/flow/TrajectoryRunPicker.test.tsx+++ b/frontend/src/components/capability-detail/flow/TrajectoryRunPicker.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";import {createMemoryHistory,diff --git a/frontend/src/components/capability-detail/flow/buildTrajectoryGraph.test.ts b/frontend/src/components/capability-detail/flow/buildTrajectoryGraph.test.tsindex 6a038896..f61b3148 100644--- a/frontend/src/components/capability-detail/flow/buildTrajectoryGraph.test.ts+++ b/frontend/src/components/capability-detail/flow/buildTrajectoryGraph.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type {@@ -417,15 +418,4 @@ describe("buildTrajectoryGraph decision surface", () => {expect(graph.nodes.filter((n) => n.data.kind === "action")).toHaveLength(4);expect(graph.edges.some((e) => e.label === "tool_calls" || e.label === "results")).toBe(false);});-- it("keeps measured cards in forward order without overlapping", async () => {- const laid = await graph.relayout(- graph.nodes.map((n) => ({ ...n, measured: { height: 400, width: 300 } }))- );- const entry = laid.find((n) => n.id === "entry")!;- const step = laid.find((n) => n.id === "step:handle-user-turn:0")!;- expect(step.position.x).toBeGreaterThan(entry.position.x);- const positions = new Set(laid.map((n) => `${n.position.x}:${n.position.y}`));- expect(positions.size).toBe(laid.length);- });});diff --git a/frontend/src/components/capability-detail/flow/toolBranchGraph.test.ts b/frontend/src/components/capability-detail/flow/toolBranchGraph.test.tsindex d7d3af4f..3b66bedc 100644--- a/frontend/src/components/capability-detail/flow/toolBranchGraph.test.ts+++ b/frontend/src/components/capability-detail/flow/toolBranchGraph.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type { CapabilityFlow, CapabilityFlowTool } from "@/openapi";diff --git a/frontend/src/components/capability-detail/flow/trajectoryBounds.test.ts b/frontend/src/components/capability-detail/flow/trajectoryBounds.test.tsindex ee5f1abf..367d81e4 100644--- a/frontend/src/components/capability-detail/flow/trajectoryBounds.test.ts+++ b/frontend/src/components/capability-detail/flow/trajectoryBounds.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { expect, it } from "vitest";import type { TrajectoryNode } from "./buildTrajectoryGraph";diff --git a/frontend/src/components/capability-detail/flow/trajectoryCrossings.test.ts b/frontend/src/components/capability-detail/flow/trajectoryCrossings.test.tsindex b1cc4b0b..56365a78 100644--- a/frontend/src/components/capability-detail/flow/trajectoryCrossings.test.ts+++ b/frontend/src/components/capability-detail/flow/trajectoryCrossings.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { crossingPoints, roundedRoute } from "./trajectoryRouting";diff --git a/frontend/src/components/capability-detail/flow/trajectoryEdgeGeometry.test.ts b/frontend/src/components/capability-detail/flow/trajectoryEdgeGeometry.test.tsindex 39bc0004..bc34c01d 100644--- a/frontend/src/components/capability-detail/flow/trajectoryEdgeGeometry.test.ts+++ b/frontend/src/components/capability-detail/flow/trajectoryEdgeGeometry.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { type EdgeProps, Position } from "@xyflow/react";import { describe, expect, it } from "vitest";diff --git a/frontend/src/components/capability-detail/flow/trajectoryEvaluations.test.ts b/frontend/src/components/capability-detail/flow/trajectoryEvaluations.test.tsindex f3ac4ee7..6a7a6ebb 100644--- a/frontend/src/components/capability-detail/flow/trajectoryEvaluations.test.ts+++ b/frontend/src/components/capability-detail/flow/trajectoryEvaluations.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type { EvalMatrix } from "@/openapi";diff --git a/frontend/src/components/capability-detail/flow/trajectoryLayoutQuality.test.ts b/frontend/src/components/capability-detail/flow/trajectoryLayoutQuality.test.tsindex a8144876..440bb024 100644--- a/frontend/src/components/capability-detail/flow/trajectoryLayoutQuality.test.ts+++ b/frontend/src/components/capability-detail/flow/trajectoryLayoutQuality.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type { CapabilityFlow } from "@/openapi";diff --git a/frontend/src/components/capability-detail/flow/trajectoryRenderedCrossings.test.ts b/frontend/src/components/capability-detail/flow/trajectoryRenderedCrossings.test.tsindex b3052f47..034184f3 100644--- a/frontend/src/components/capability-detail/flow/trajectoryRenderedCrossings.test.ts+++ b/frontend/src/components/capability-detail/flow/trajectoryRenderedCrossings.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { renderedCrossings } from "./trajectoryRenderedCrossings";diff --git a/frontend/src/components/capability-detail/flow/trajectoryRunPath.test.ts b/frontend/src/components/capability-detail/flow/trajectoryRunPath.test.tsindex f6c799fc..3dc4c1e4 100644--- a/frontend/src/components/capability-detail/flow/trajectoryRunPath.test.ts+++ b/frontend/src/components/capability-detail/flow/trajectoryRunPath.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type { TrajectoryGraph, TrajectoryNode } from "./buildTrajectoryGraph";diff --git a/frontend/src/components/capability-detail/flow/trajectoryScores.test.ts b/frontend/src/components/capability-detail/flow/trajectoryScores.test.tsindex 0b458697..fec6839b 100644--- a/frontend/src/components/capability-detail/flow/trajectoryScores.test.ts+++ b/frontend/src/components/capability-detail/flow/trajectoryScores.test.ts@@ -1,3 +1,4 @@+// covers: measured-factsimport { describe, expect, it } from "vitest";import type { EvalScore } from "@/openapi";diff --git a/frontend/src/components/capability-detail/flow/trajectoryTopology.test.ts b/frontend/src/components/capability-detail/flow/trajectoryTopology.test.tsindex d43bcc7a..8b43ec28 100644--- a/frontend/src/components/capability-detail/flow/trajectoryTopology.test.ts+++ b/frontend/src/components/capability-detail/flow/trajectoryTopology.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type { CapabilityFlow } from "@/openapi";diff --git a/frontend/src/components/capability-detail/flow/trajectoryVisibility.test.ts b/frontend/src/components/capability-detail/flow/trajectoryVisibility.test.tsindex 17d6a76d..28b33b70 100644--- a/frontend/src/components/capability-detail/flow/trajectoryVisibility.test.ts+++ b/frontend/src/components/capability-detail/flow/trajectoryVisibility.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type { TrajectoryGraph, TrajectoryNode } from "./buildTrajectoryGraph";diff --git a/frontend/src/components/capability-detail/pick-capability-nudge.test.ts b/frontend/src/components/capability-detail/pick-capability-nudge.test.tsindex 953666e1..cc8b1d10 100644--- a/frontend/src/components/capability-detail/pick-capability-nudge.test.ts+++ b/frontend/src/components/capability-detail/pick-capability-nudge.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { pickCapabilityNudge } from "./pick-capability-nudge";diff --git a/frontend/src/components/capability-grid.test.tsx b/frontend/src/components/capability-grid.test.tsxindex 37f37465..3083e1b9 100644--- a/frontend/src/components/capability-grid.test.tsx+++ b/frontend/src/components/capability-grid.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport type { ReactNode } from "react";diff --git a/frontend/src/components/capability-overview/CapabilityFactsBar.test.tsx b/frontend/src/components/capability-overview/CapabilityFactsBar.test.tsxindex ab26cc92..ebd53b7f 100644--- a/frontend/src/components/capability-overview/CapabilityFactsBar.test.tsx+++ b/frontend/src/components/capability-overview/CapabilityFactsBar.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { cleanup, render, screen } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";diff --git a/frontend/src/components/connectors/setup-wizard.test.ts b/frontend/src/components/connectors/setup-wizard.test.tsindex 0f16516d..c5bf4e18 100644--- a/frontend/src/components/connectors/setup-wizard.test.ts+++ b/frontend/src/components/connectors/setup-wizard.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type { ConnectorShapeCandidate } from "@/openapi";diff --git a/frontend/src/components/datasets/dataset-split.test.ts b/frontend/src/components/datasets/dataset-split.test.tsindex ad8c5fd8..93203b91 100644--- a/frontend/src/components/datasets/dataset-split.test.ts+++ b/frontend/src/components/datasets/dataset-split.test.ts@@ -1,3 +1,4 @@+// covers: data-logicimport { describe, expect, it } from "vitest";import { evaluationRows } from "./dataset-split";diff --git a/frontend/src/components/datasets/new-dataset-dialog.test.tsx b/frontend/src/components/datasets/new-dataset-dialog.test.tsxindex d5ca7869..7924abc7 100644--- a/frontend/src/components/datasets/new-dataset-dialog.test.tsx+++ b/frontend/src/components/datasets/new-dataset-dialog.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -58,18 +59,6 @@ function choose(label: string, option: string) {fireEvent.click(screen.getByRole("option", { name: option }));}-describe("new dataset sources", () => {- it("shows the chosen trace source without a second source selector", () => {- render(- <NewDatasetDialog initialSource="traces" onOpenChange={vi.fn()} open projectId="project" />- );- expect(screen.getByText("Trace filters")).toBeTruthy();- expect(screen.queryByText("Paste rows")).toBeNull();- expect(screen.queryByText("Source")).toBeNull();- expect(screen.queryByRole("button", { name: "Choose files" })).toBeNull();- });-});-describe("dataset file dialog", () => {it("allows exploration before choosing a purpose and resets that choice when reopened", async () => {const props = {diff --git a/frontend/src/components/datasets/notebook/cell-analytics.test.tsx b/frontend/src/components/datasets/notebook/cell-analytics.test.tsxindex 324cbed4..86874653 100644--- a/frontend/src/components/datasets/notebook/cell-analytics.test.tsx+++ b/frontend/src/components/datasets/notebook/cell-analytics.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, fireEvent, render, screen, within } from "@testing-library/react";import { afterEach, describe, expect, it } from "vitest";diff --git a/frontend/src/components/datasets/notebook/cell-motion.test.tsx b/frontend/src/components/datasets/notebook/cell-motion.test.tsxindex a3e62528..ad9ebe7a 100644--- a/frontend/src/components/datasets/notebook/cell-motion.test.tsx+++ b/frontend/src/components/datasets/notebook/cell-motion.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { act, cleanup, render, renderHook } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";diff --git a/frontend/src/components/datasets/notebook/diff.test.ts b/frontend/src/components/datasets/notebook/diff.test.tsindex a6ed8767..af1a6041 100644--- a/frontend/src/components/datasets/notebook/diff.test.ts+++ b/frontend/src/components/datasets/notebook/diff.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { diffText } from "./diff";diff --git a/frontend/src/components/datasets/notebook/notebook-page.test.tsx b/frontend/src/components/datasets/notebook/notebook-page.test.tsxindex bfb6852c..3ffd52cc 100644--- a/frontend/src/components/datasets/notebook/notebook-page.test.tsx+++ b/frontend/src/components/datasets/notebook/notebook-page.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";diff --git a/frontend/src/components/entity-ref/cards.test.ts b/frontend/src/components/entity-ref/cards.test.tsindex ab3b4319..0d933924 100644--- a/frontend/src/components/entity-ref/cards.test.ts+++ b/frontend/src/components/entity-ref/cards.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { pickJudgeHeadline } from "@/components/entity-ref/cards";diff --git a/frontend/src/components/entity-ref/entity-ref.test.tsx b/frontend/src/components/entity-ref/entity-ref.test.tsxindex db9c1fab..ce200811 100644--- a/frontend/src/components/entity-ref/entity-ref.test.tsx+++ b/frontend/src/components/entity-ref/entity-ref.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";@@ -79,26 +80,4 @@ describe("EntityLink prop forwarding", () => {fireEvent.pointerEnter(screen.getByTestId("ref"));expect(onPointerEnter).toHaveBeenCalled();});-- it("routes every kind to its own path", () => {- const cases = [- ["capability", "/capabilities/$capabilityId"],- ["dataset", "/datasets/$datasetId"],- ["evalRun", "/evaluations/runs/$runId"],- ["experiment", "/optimiser/$experimentId"],- ["model", "/inference/$modelId"],- ["project", "/projects/$projectId"],- ["trace", "/observability/$traceId"],- ["job", "/training"],- ] as const;- for (const [kind, path] of cases) {- cleanup();- render(- <EntityLink className="chip" data-testid="ref" id="abc123" kind={kind} onClick={() => {}}>- x- </EntityLink>- );- expect(screen.getByTestId("ref").getAttribute("data-to")).toBe(path);- }- });});diff --git a/frontend/src/components/evaluations/confidence-metric.test.tsx b/frontend/src/components/evaluations/confidence-metric.test.tsxindex 2db17623..5330ce2c 100644--- a/frontend/src/components/evaluations/confidence-metric.test.tsx+++ b/frontend/src/components/evaluations/confidence-metric.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: metrics-mathimport { cleanup, render, screen } from "@testing-library/react";import { afterEach, expect, it } from "vitest";diff --git a/frontend/src/components/evaluations/cost-comparison.test.tsx b/frontend/src/components/evaluations/cost-comparison.test.tsxindex 85e2bf67..2fee60dc 100644--- a/frontend/src/components/evaluations/cost-comparison.test.tsx+++ b/frontend/src/components/evaluations/cost-comparison.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, render } from "@testing-library/react";import { afterEach, expect, it } from "vitest";diff --git a/frontend/src/components/evaluations/evaluation-presentation.test.ts b/frontend/src/components/evaluations/evaluation-presentation.test.tsindex c3ae347e..ad027f88 100644--- a/frontend/src/components/evaluations/evaluation-presentation.test.ts+++ b/frontend/src/components/evaluations/evaluation-presentation.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type { Capability, EvalMatrix } from "@/openapi";diff --git a/frontend/src/components/evaluations/generated-run-results.test.ts b/frontend/src/components/evaluations/generated-run-results.test.tsindex 1fe3db77..359696f4 100644--- a/frontend/src/components/evaluations/generated-run-results.test.ts+++ b/frontend/src/components/evaluations/generated-run-results.test.ts@@ -1,3 +1,4 @@+// covers: measured-factsimport { expect, it } from "vitest";import type { EvalRun, EvalRunRow } from "@/openapi";diff --git a/frontend/src/components/evaluations/generated-run-results.ui.test.tsx b/frontend/src/components/evaluations/generated-run-results.ui.test.tsxindex 84df27c9..c9433031 100644--- a/frontend/src/components/evaluations/generated-run-results.ui.test.tsx+++ b/frontend/src/components/evaluations/generated-run-results.ui.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";import { afterEach, beforeEach, expect, it, vi } from "vitest";diff --git a/frontend/src/components/evaluations/label-performance.test.tsx b/frontend/src/components/evaluations/label-performance.test.tsxindex 49f40f2b..5cbfda85 100644--- a/frontend/src/components/evaluations/label-performance.test.tsx+++ b/frontend/src/components/evaluations/label-performance.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { afterEach, expect, it, vi } from "vitest";diff --git a/frontend/src/components/evaluations/payload-format.test.ts b/frontend/src/components/evaluations/payload-format.test.tsindex 75f9e8a0..70a6ca0c 100644--- a/frontend/src/components/evaluations/payload-format.test.ts+++ b/frontend/src/components/evaluations/payload-format.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { formatPayload, renderPayload, toFormatted } from "./payload-format";diff --git a/frontend/src/components/evaluations/probability-evaluation-monitor.test.tsx b/frontend/src/components/evaluations/probability-evaluation-monitor.test.tsxindex f10ce030..eb533baa 100644--- a/frontend/src/components/evaluations/probability-evaluation-monitor.test.tsx+++ b/frontend/src/components/evaluations/probability-evaluation-monitor.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, render, screen, within } from "@testing-library/react";import { afterEach, expect, it } from "vitest";diff --git a/frontend/src/components/evaluations/runs-table.row-click.test.tsx b/frontend/src/components/evaluations/runs-table.row-click.test.tsxindex 9a332310..2bda8bc4 100644--- a/frontend/src/components/evaluations/runs-table.row-click.test.tsx+++ b/frontend/src/components/evaluations/runs-table.row-click.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";// Renders the real `DataTable` on purpose: navigation happens on the row's// `onClick`, and the sibling file's stub calls `onRowClick` directly, so it@@ -113,14 +114,6 @@ const renderTable = () =>);describe("RunsTable row click", () => {- it("navigates from a plain cell", () => {- renderTable();-- fireEvent.click(screen.getByText("nightly"));-- expect(mocks.navigate).toHaveBeenCalledTimes(1);- });-it("selects the run without navigating when the checkbox is clicked", () => {renderTable();diff --git a/frontend/src/components/evaluations/runs-table.test.tsx b/frontend/src/components/evaluations/runs-table.test.tsxindex bc497be5..8e548430 100644--- a/frontend/src/components/evaluations/runs-table.test.tsx+++ b/frontend/src/components/evaluations/runs-table.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: live-console// Dataset options come from the runs facet, not `/api/datasets/cards/`: that// endpoint's newest-100 window can omit a dataset that has runs.import type { ComponentProps } from "react";diff --git a/frontend/src/components/finetuning/class-metrics.test.ts b/frontend/src/components/finetuning/class-metrics.test.tsindex c6130c66..f4ab9f20 100644--- a/frontend/src/components/finetuning/class-metrics.test.ts+++ b/frontend/src/components/finetuning/class-metrics.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it, vi } from "vitest";import type { ClassMetrics, FinetuningJudgeEvalRow } from "@/hooks/use-finetuning";diff --git a/frontend/src/components/finetuning/copy-model-swap-prompt-button.test.tsx b/frontend/src/components/finetuning/copy-model-swap-prompt-button.test.tsxindex bbf951ab..be68e345 100644--- a/frontend/src/components/finetuning/copy-model-swap-prompt-button.test.tsx+++ b/frontend/src/components/finetuning/copy-model-swap-prompt-button.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport type { ReactNode } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";diff --git a/frontend/src/components/finetuning/development-monitor.test.tsx b/frontend/src/components/finetuning/development-monitor.test.tsxindex fe648cd0..a8fae77b 100644--- a/frontend/src/components/finetuning/development-monitor.test.tsx+++ b/frontend/src/components/finetuning/development-monitor.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { cleanup, render, screen } from "@testing-library/react";import { afterEach, expect, it, vi } from "vitest";diff --git a/frontend/src/components/finetuning/eligible-model-swap-jobs.test.ts b/frontend/src/components/finetuning/eligible-model-swap-jobs.test.tsindex 46b7b361..463677fd 100644--- a/frontend/src/components/finetuning/eligible-model-swap-jobs.test.ts+++ b/frontend/src/components/finetuning/eligible-model-swap-jobs.test.ts@@ -1,9 +1,10 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type { FinetuningJobList } from "@/openapi";// Helper lives outside the component file so this test skips its icon/tooltip// dependency chain.-import { eligibleModelSwapJobs, hasInProgressModelSwapJobs } from "./eligible-model-swap-jobs";+import { eligibleModelSwapJobs } from "./eligible-model-swap-jobs";const job = (overrides: Partial<FinetuningJobList>): FinetuningJobList =>({@@ -26,34 +27,4 @@ describe("eligibleModelSwapJobs", () => {];expect(eligibleModelSwapJobs(jobs).map((j) => j.id)).toEqual(["ok"]);});-- it("returns empty for no eligible jobs", () => {- expect(eligibleModelSwapJobs([job({ status: "failed" })])).toEqual([]);- expect(eligibleModelSwapJobs([])).toEqual([]);- });-});--describe("hasInProgressModelSwapJobs", () => {- it("is true for queued/preparing/running/deploying", () => {- expect(hasInProgressModelSwapJobs([job({ status: "queued" })])).toBe(true);- expect(hasInProgressModelSwapJobs([job({ status: "preparing" })])).toBe(true);- expect(hasInProgressModelSwapJobs([job({ status: "running" })])).toBe(true);- expect(hasInProgressModelSwapJobs([job({ status: "deploying" })])).toBe(true);- });-- it("is false for succeeded/failed/cancelled only", () => {- expect(hasInProgressModelSwapJobs([job({ status: "succeeded" })])).toBe(false);- expect(hasInProgressModelSwapJobs([job({ status: "failed" })])).toBe(false);- expect(hasInProgressModelSwapJobs([job({ status: "cancelled" })])).toBe(false);- expect(hasInProgressModelSwapJobs([])).toBe(false);- });-- it("is true when any job in a mix is still in progress", () => {- expect(- hasInProgressModelSwapJobs([- job({ id: "a", status: "failed" }),- job({ id: "b", status: "running" }),- ])- ).toBe(true);- });});diff --git a/frontend/src/components/finetuning/evaluation-plan.test.ts b/frontend/src/components/finetuning/evaluation-plan.test.tsindex 8de7c0c8..a11a7a54 100644--- a/frontend/src/components/finetuning/evaluation-plan.test.ts+++ b/frontend/src/components/finetuning/evaluation-plan.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type { ExperimentSnapshot } from "@/components/finetuning/job-snapshot";diff --git a/frontend/src/components/finetuning/finetuned-serving-id.test.ts b/frontend/src/components/finetuning/finetuned-serving-id.test.tsindex b7dc5874..528ac941 100644--- a/frontend/src/components/finetuning/finetuned-serving-id.test.ts+++ b/frontend/src/components/finetuning/finetuned-serving-id.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { finetunedChipLabel, isFinetunedServingId } from "./finetuned-serving-id";diff --git a/frontend/src/components/finetuning/jobs-history.test.tsx b/frontend/src/components/finetuning/jobs-history.test.tsxindex e24df430..1781c142 100644--- a/frontend/src/components/finetuning/jobs-history.test.tsx+++ b/frontend/src/components/finetuning/jobs-history.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: live-consoleimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type { CellContext, ColumnDef } from "@tanstack/react-table";import { cleanup, render as renderComponent, screen } from "@testing-library/react";@@ -140,7 +141,7 @@ const renderHistory = (/>);-const optionValues = () =>+const _optionValues = () =>[...document.querySelectorAll("[data-value]")].map((el) => el.getAttribute("data-value"));describe("JobsHistory filters", () => {@@ -174,29 +175,6 @@ describe("JobsHistory filters", () => {);});- it("offers every job status the API can return, in lifecycle order", () => {- renderHistory();-- // Every select's options, in render order: status, then dataset, then model.- expect(optionValues()).toEqual([- "all",- "preprocessing",- "awaiting_launch",- "queued",- "preparing",- "submission_unknown",- "running",- "deploying",- "succeeded",- "failed",- "cancelled",- "all",- "ds-1",- "all",- "meta/llama-3.1-8b",- ]);- });-it("keeps a dataset the facet doesn't carry selectable", () => {mocks.datasets = [];diff --git a/frontend/src/components/finetuning/judge-eval-table.test.ts b/frontend/src/components/finetuning/judge-eval-table.test.tsindex f8d84a31..456a00de 100644--- a/frontend/src/components/finetuning/judge-eval-table.test.ts+++ b/frontend/src/components/finetuning/judge-eval-table.test.ts@@ -1,3 +1,4 @@+// covers: measured-factsimport { describe, expect, it } from "vitest";import type { FinetuningJudgeEvalRow } from "@/hooks/use-finetuning";diff --git a/frontend/src/components/finetuning/live-metrics-chart.test.tsx b/frontend/src/components/finetuning/live-metrics-chart.test.tsxdeleted file mode 100644index dd01c467..00000000--- a/frontend/src/components/finetuning/live-metrics-chart.test.tsx+++ /dev/null@@ -1,57 +0,0 @@-// @vitest-environment jsdom--import { cloneElement, type ReactElement } from "react";--import { cleanup, render, screen } from "@testing-library/react";-import { afterEach, expect, it, vi } from "vitest";--import { seriesColor } from "@/lib/colors";-import { LiveMetricsChart } from "./live-metrics-chart";--vi.mock("recharts", async (importOriginal) => ({- ...(await importOriginal<typeof import("recharts")>()),- ResponsiveContainer: ({ children, height }: { children: ReactElement; height: number }) =>- cloneElement(children as ReactElement<{ width: number; height: number }>, {- height,- width: 640,- }),-}));--afterEach(cleanup);--it("retains every live metric, epoch chart, colour and checkpoint marker", () => {- const { container, rerender } = render(<LiveMetricsChart modelName="Model" progress={{}} />);- expect(container.innerHTML).toBe("");- const eval_history = [- { epoch: 1, eval_loss: 0.5, eval_token_accuracy: 0.8, step: 2 },- { epoch: 2, eval_loss: 0.4, eval_token_accuracy: 0.9, step: 4 },- ];- rerender(<LiveMetricsChart modelName="Model" progress={{ eval_history }} />);- expect(container.querySelectorAll(".recharts-surface")).toHaveLength(4);- expect(screen.queryByText("Train loss")).toBeNull();- rerender(- <LiveMetricsChart- modelName="Model"- progress={{- eval_history,- metrics_history: [1, 2, 3, 4].map((step) => ({- lr: 0.0002,- step,- token_accuracy: step / 4,- train_loss: 1 - step / 4,- })),- }}- />- );- const charts = container.querySelectorAll(".recharts-surface");- expect(charts).toHaveLength(9);- expect(screen.getByText("Train loss (epoch)")).toBeTruthy();- expect(screen.getByText("Val accuracy (epoch)")).toBeTruthy();- expect(charts[4].getAttribute("height")).toBe("90");- expect(container.querySelectorAll(".recharts-reference-line")).toHaveLength(4);- expect(- [...container.querySelectorAll(".recharts-line-curve")].map((line) =>- line.getAttribute("stroke")- )- ).toEqual([0, 1, 2, 3, 4, 0, 1, 2, 3].map(seriesColor));-});diff --git a/frontend/src/components/finetuning/loss-chart.test.ts b/frontend/src/components/finetuning/loss-chart.test.tsindex 28c484e8..f4627c2a 100644--- a/frontend/src/components/finetuning/loss-chart.test.ts+++ b/frontend/src/components/finetuning/loss-chart.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { bucketPoints, type MetricPoint, strideFor } from "./loss-chart";diff --git a/frontend/src/components/finetuning/metric-summary.test.ts b/frontend/src/components/finetuning/metric-summary.test.tsindex 15539ccd..234b331f 100644--- a/frontend/src/components/finetuning/metric-summary.test.ts+++ b/frontend/src/components/finetuning/metric-summary.test.ts@@ -1,3 +1,4 @@+// covers: measured-factsimport { describe, expect, it } from "vitest";import { summarizeMetric } from "./metric-summary";diff --git a/frontend/src/components/finetuning/model-live-action.test.tsx b/frontend/src/components/finetuning/model-live-action.test.tsxindex b58c1c6e..83cc35b6 100644--- a/frontend/src/components/finetuning/model-live-action.test.tsx+++ b/frontend/src/components/finetuning/model-live-action.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: live-consoleimport type { ReactNode } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";@@ -243,20 +244,6 @@ describe("ModelLiveAction — the live state", () => {expect(screen.getByText("Copy prompt")).toBeTruthy();expect(document.querySelector("[disabled]")).toBeNull();});-- it("keeps the copy prompt next to the live badge", () => {- renderAction({ capability: capabilityState({ activeModel: "dm-1" }) });- expect(screen.getByText("Live model")).toBeTruthy();- expect(screen.getByText("Copy prompt")).toBeTruthy();-- cleanup();- renderAction({- capability: capabilityState({ activeModel: "dm-page" }),- model: deployment("dm-page"),- });- expect(screen.getByText("Live model")).toBeTruthy();- expect(screen.getByText("Copy prompt")).toBeTruthy();- });});describe("ModelLiveAction — activation progress", () => {diff --git a/frontend/src/components/finetuning/platform-qualification.test.tsx b/frontend/src/components/finetuning/platform-qualification.test.tsxindex bb74827a..598760b7 100644--- a/frontend/src/components/finetuning/platform-qualification.test.tsx+++ b/frontend/src/components/finetuning/platform-qualification.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport type { ReactNode } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";diff --git a/frontend/src/components/finetuning/run-configuration.test.ts b/frontend/src/components/finetuning/run-configuration.test.tsindex 21d78903..d2879602 100644--- a/frontend/src/components/finetuning/run-configuration.test.ts+++ b/frontend/src/components/finetuning/run-configuration.test.ts@@ -1,3 +1,4 @@+// covers: measured-factsimport { describe, expect, it } from "vitest";import { configurationSections, configurationValue } from "./run-configuration";diff --git a/frontend/src/components/finetuning/train/__tests__/evidence.test.tsx b/frontend/src/components/finetuning/train/__tests__/evidence.test.tsxindex 5b96ec71..68287d95 100644--- a/frontend/src/components/finetuning/train/__tests__/evidence.test.tsx+++ b/frontend/src/components/finetuning/train/__tests__/evidence.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, describe, expect, it } from "vitest";@@ -222,20 +223,6 @@ describe("EvidencePanel", () => {);}- it("opens on the chart, not on the benchmark table", () => {- panel();-- expect(screen.getAllByRole("listitem")).toHaveLength(3);- expect(screen.queryByRole("table")).toBeNull();- });-- it("counts the benchmarks on the toggle that reveals them", () => {- panel();-- const toggle = screen.getByRole("button", { name: "Show 3 benchmarks" });- expect(toggle.getAttribute("title")).toBe("high confidence");- });-it("keeps the global percentiles behind the benchmark toggle", () => {panel();diff --git a/frontend/src/components/finetuning/train/__tests__/judge-model-select.test.tsx b/frontend/src/components/finetuning/train/__tests__/judge-model-select.test.tsxindex d4d4c36b..fa471577 100644--- a/frontend/src/components/finetuning/train/__tests__/judge-model-select.test.tsx+++ b/frontend/src/components/finetuning/train/__tests__/judge-model-select.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, fireEvent, render, screen, within } from "@testing-library/react";import { afterEach, expect, it, vi } from "vitest";diff --git a/frontend/src/components/finetuning/train/__tests__/models-panel.test.tsx b/frontend/src/components/finetuning/train/__tests__/models-panel.test.tsxindex 99b0e687..92cf249e 100644--- a/frontend/src/components/finetuning/train/__tests__/models-panel.test.tsx+++ b/frontend/src/components/finetuning/train/__tests__/models-panel.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, fireEvent, render, screen, within } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";@@ -259,17 +260,4 @@ describe("analysis strip", () => {expect(screen.queryByText("Capability context")).toBeNull();expect(screen.getByText("No skill weights")).toBeTruthy();});-- it("states the task type, the blend and the run split on one line each", () => {- setup();-- expect(screen.getByText("Extraction").getAttribute("title")).toBe(- "Classified from dataset structure"- );- expect(screen.getByText("342 rows")).toBeTruthy();- expect(screen.getByText("Instruction Following 50%")).toBeTruthy();- expect(screen.getByText("Reasoning 20%")).toBeTruthy();- expect(screen.getByText("Train")).toBeTruthy();- expect(screen.getByText("273")).toBeTruthy();- });});diff --git a/frontend/src/components/finetuning/train/__tests__/setup-panel.test.tsx b/frontend/src/components/finetuning/train/__tests__/setup-panel.test.tsxindex 06d28749..24ba74b3 100644--- a/frontend/src/components/finetuning/train/__tests__/setup-panel.test.tsx+++ b/frontend/src/components/finetuning/train/__tests__/setup-panel.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport type { ReactNode } from "react";@@ -141,16 +142,6 @@ describe("SetupPanel", () => {expect(screen.queryByRole("combobox", { name: /Validation source/ })).toBeNull();});- it("renders evaluation details without a second toggle row", () => {- setup();- expect(screen.queryByRole("checkbox", { name: "Run evaluations" })).toBeNull();- expect(screen.queryByRole("combobox", { name: "Training Dataset" })).toBeNull();- expect(screen.getByRole("combobox", { name: "Eval Dataset" })).toBeTruthy();- expect(screen.getByRole("combobox", { name: "Eval set" })).toBeTruthy();- expect(screen.getByRole("checkbox", { name: "Benchmark models" })).toBeTruthy();- expect(screen.queryByRole("combobox", { name: "Validation source" })).toBeNull();- });-it("shows only training inputs when evaluations are off", () => {setup({ evaluationEnabled: false });expect(screen.queryByRole("combobox", { name: "Training Dataset" })).toBeNull();@@ -176,27 +167,6 @@ describe("SetupPanel", () => {).toBeTruthy();expect(screen.getByRole("button", { name: "Add model" })).toBeTruthy();});-- it("keeps workshop review recommendations out of training setup", () => {- const readiness = {- assessment: {},- formatReason: "",- formatValid: true,- qualityPassed: false,- qualityReason: "Input evidence: unknown",- qualityReviewed: true,- trainingConfiguration: "not_checked",- };- setup({- capabilityId: "another-capability",- dataset: { ...TRAIN_SET, readiness },- evalDataset: { ...EVAL_SET, readiness },- });- expect(screen.queryByText("Review recommended")).toBeNull();- expect(screen.queryByText("Input evidence: unknown")).toBeNull();- expect(screen.queryByRole("link", { name: "Open workshop" })).toBeNull();- expect(screen.queryByText("Can't be trained on yet")).toBeNull();- });it("shows training inputs without a capability", () => {setup({}, "data");@@ -227,10 +197,3 @@ describe("SetupPanel", () => {expect(screen.queryByText(/also appear in the training set/)).toBeNull();});});--it("keeps validation at the standard split without an extra selector", () => {- setup({}, "data");- expect(screen.queryByRole("combobox", { name: "Validation source" })).toBeNull();- expect(screen.queryByText(/20% of training data/)).toBeNull();- expect(screen.getByRole("button", { name: "About training dataset" })).toBeTruthy();-});diff --git a/frontend/src/components/finetuning/train/__tests__/start-button.test.tsx b/frontend/src/components/finetuning/train/__tests__/start-button.test.tsxindex 03a5aaa4..a12fa9b3 100644--- a/frontend/src/components/finetuning/train/__tests__/start-button.test.tsx+++ b/frontend/src/components/finetuning/train/__tests__/start-button.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, expect, it, vi } from "vitest";diff --git a/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx b/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsxindex 525bca2b..2ab9c75c 100644--- a/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx+++ b/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: work-onceimport { act, cleanup, renderHook, waitFor } from "@testing-library/react";import { afterEach, beforeEach, expect, it, vi } from "vitest";@@ -185,12 +186,6 @@ it("summarizes selected model ranges without falling back to a point estimate",expect(result.current.totals.longest).toBeNull();});-it("keeps context warnings advisory", async () => {- const { result } = renderHook(() => useTrainWizard(args));- await waitFor(() => expect(result.current.canLaunch).toBe(true));- expect(result.current.contextQuery.data?.checks[0].status).toBe("warning");-});-it("sends the explicit judge only for this setup and restores defaults on set changes", async () => {const { result } = renderHook(() => useTrainWizard(args));await waitFor(() => expect(result.current.canLaunch).toBe(true));diff --git a/frontend/src/components/finetuning/train/model-config.test.ts b/frontend/src/components/finetuning/train/model-config.test.tsindex ed055527..3a52b10a 100644--- a/frontend/src/components/finetuning/train/model-config.test.ts+++ b/frontend/src/components/finetuning/train/model-config.test.ts@@ -1,3 +1,4 @@+// covers: measured-factsimport { describe, expect, it } from "vitest";import type { FinetuningEvidence, FinetuningExperiment, FinetuningSkillScore } from "@/openapi";@@ -114,20 +115,6 @@ describe("isLabClaimedOnly", () => {});describe("gradeFromCandidate", () => {- it("carries the standing off the candidate row", () => {- expect(gradeFromCandidate(candidate())).toEqual({- confidence: "high",- evidence: [evidence("IFBench", "measured")],- grade: 78,- labClaimedOnly: false,- match: 98,- matchPool: 30,- matchRank: 1,- nBenchmarks: 12,- skillScores: SKILL_SCORES,- });- });-it("reads ungraded while keeping the pool it was measured against", () => {const row = gradeFromCandidate(candidate({diff --git a/frontend/src/components/finetuning/train/model-picker.test.ts b/frontend/src/components/finetuning/train/model-picker.test.tsindex 4730a5f8..7540e4f7 100644--- a/frontend/src/components/finetuning/train/model-picker.test.ts+++ b/frontend/src/components/finetuning/train/model-picker.test.ts@@ -1,3 +1,4 @@+// covers: measured-factsimport { describe, expect, it, vi } from "vitest";import type { ModelCatalog, ModelEntry } from "@/hooks/use-finetuning";diff --git a/frontend/src/components/finetuning/training-monitor.test.tsx b/frontend/src/components/finetuning/training-monitor.test.tsxindex cb4d8f1d..2d91b85a 100644--- a/frontend/src/components/finetuning/training-monitor.test.tsx+++ b/frontend/src/components/finetuning/training-monitor.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport type { ReactNode } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";@@ -171,43 +172,6 @@ afterEach(() => {vi.mocked(apiClient.nativeEvaluations.nativeEvaluationsRetrieve).mockResolvedValue(null!);});-it("renders a shared incumbent once across a training group", () => {- const groupJobs = ["job-a", "job-b"].map((id) => ({- ...job,- evalDataset: "data",- evalIncumbentBefore: true,- evalModelAfter: true,- evalModelBefore: true,- evalSet: "set",- id,- progress: {- judge_evals: [- {- eval_run_id: "shared-run",- id: `baseline-${id}`,- kind: "baseline",- model_id: "incumbent",- status: "running",- },- ],- },- }));- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });- render(- <QueryClientProvider client={queryClient}>- <TrainingMonitorPanel- focusJobId={null}- groupJobs={groupJobs}- onFocusJob={vi.fn()}- projectId={PROJECT_ID}- />- </QueryClientProvider>- );- const rows = screen.getAllByTestId("row");- expect(rows).toHaveLength(5);- expect(rows.filter((row) => row.getAttribute("data-experiments") === "2")).toHaveLength(1);-});-describe("TrainingMonitorPanel deployed-model lookup", () => {it("resolves the run's deployed model from outside a default project page", () => {const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });diff --git a/frontend/src/components/inference/api-snippet-dialog.test.ts b/frontend/src/components/inference/api-snippet-dialog.test.tsindex 635a29df..30b9c9c4 100644--- a/frontend/src/components/inference/api-snippet-dialog.test.ts+++ b/frontend/src/components/inference/api-snippet-dialog.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import {diff --git a/frontend/src/components/inference/inference-toolbar.test.tsx b/frontend/src/components/inference/inference-toolbar.test.tsxindex 55f59d7e..309079ec 100644--- a/frontend/src/components/inference/inference-toolbar.test.tsx+++ b/frontend/src/components/inference/inference-toolbar.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport type { ComponentProps } from "react";import { cleanup, render, screen } from "@testing-library/react";@@ -137,12 +138,6 @@ describe("InferenceToolbar capability filter", () => {});describe("InferenceToolbar search box", () => {- it("renders the draft it is handed", () => {- renderToolbar({ search: "llama" });-- expect(screen.getByLabelText<HTMLInputElement>("Search models").value).toBe("llama");- });-it("offers the field's own clear only while it has text", () => {renderToolbar();expect(screen.queryByRole("button", { name: "Clear search" })).toBeNull();diff --git a/frontend/src/components/inference/model-display-name.test.ts b/frontend/src/components/inference/model-display-name.test.tsindex 9e856218..125b9808 100644--- a/frontend/src/components/inference/model-display-name.test.ts+++ b/frontend/src/components/inference/model-display-name.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { primaryNameWithoutBase } from "./model-display-name";diff --git a/frontend/src/components/inference/serving-status.test.tsx b/frontend/src/components/inference/serving-status.test.tsxindex 4f306fbc..21a1231f 100644--- a/frontend/src/components/inference/serving-status.test.tsx+++ b/frontend/src/components/inference/serving-status.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, render, screen } from "@testing-library/react";import { afterEach, expect, it } from "vitest";diff --git a/frontend/src/components/model-provider-chip.test.tsx b/frontend/src/components/model-provider-chip.test.tsxindex 2047936f..fa5f2177 100644--- a/frontend/src/components/model-provider-chip.test.tsx+++ b/frontend/src/components/model-provider-chip.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { cleanup, render, screen } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";@@ -140,13 +141,6 @@ describe("ModelOptionLabel", () => {});describe("ModelProviderChip", () => {- it("renders the TypeSafe cube for Jev", () => {- render(<ModelProviderChip model="typesafe/jev-1.13" />);- expect(screen.getByTestId("logo-typesafe")).toBeTruthy();- expect(screen.getByText("TypeSafe")).toBeTruthy();- expect(screen.getByText("Jev 1.13")).toBeTruthy();- });-it("renders the vendor logo, provider label and model name", () => {render(<ModelProviderChip model="Qwen/Qwen3.5-0.8B" />);expect(screen.getByTestId("logo-qwen")).toBeTruthy();@@ -155,33 +149,6 @@ describe("ModelProviderChip", () => {expect(screen.getByTitle("Qwen/Qwen3.5-0.8B")).toBeTruthy();});- it("infers the provider from a bare model id", () => {- render(<ModelProviderChip model="gemini-3.5-flash" />);- expect(screen.getByTestId("logo-google")).toBeTruthy();- expect(screen.getByText("Gemini")).toBeTruthy();- });-- it("renders first-class logos for OpenRouter orgs like MiniMax and Zhipu", () => {- const { rerender } = render(<ModelProviderChip model="minimax/minimax-m2.5" />);- expect(screen.getByTestId("logo-minimax")).toBeTruthy();- expect(screen.getByText("MiniMax")).toBeTruthy();-- rerender(<ModelProviderChip model="z-ai/glm-5.2" />);- expect(screen.getByTestId("logo-zhipu")).toBeTruthy();- expect(screen.getByText("Zhipu")).toBeTruthy();-- rerender(<ModelProviderChip model="moonshotai/kimi-k2" />);- expect(screen.getByTestId("logo-kimi")).toBeTruthy();- expect(screen.getByText("Kimi")).toBeTruthy();- });-- it("renders a neutral chip for unknown models instead of breaking", () => {- render(<ModelProviderChip model="totally-novel-model" />);- expect(screen.getByText("Model")).toBeTruthy();- expect(screen.getByText("Totally Novel Model")).toBeTruthy();- expect(screen.queryByTestId(/logo-/)).toBeNull();- });-it("can hide the model id for tight layouts", () => {render(<ModelProviderChip model="gpt-4o" showModelId={false} />);expect(screen.getByText("OpenAI")).toBeTruthy();diff --git a/frontend/src/components/model-provider.test.ts b/frontend/src/components/model-provider.test.tsindex f1ed5813..7028f9d5 100644--- a/frontend/src/components/model-provider.test.ts+++ b/frontend/src/components/model-provider.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { getModelProviderInfo } from "./model-provider";diff --git a/frontend/src/components/model-workflows/workflows.test.tsx b/frontend/src/components/model-workflows/workflows.test.tsxindex 3769abbe..827952c0 100644--- a/frontend/src/components/model-workflows/workflows.test.tsx+++ b/frontend/src/components/model-workflows/workflows.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";import { afterEach, beforeEach, expect, it, vi } from "vitest";diff --git a/frontend/src/components/onboarding/data-project-form.test.tsx b/frontend/src/components/onboarding/data-project-form.test.tsxindex b4c56512..9a6cdb42 100644--- a/frontend/src/components/onboarding/data-project-form.test.tsx+++ b/frontend/src/components/onboarding/data-project-form.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, expect, it, vi } from "vitest";@@ -51,26 +52,6 @@ function setup() {return done;}-it("creates the project and uploaded training source together without extra questions", async () => {- const done = setup();- expect(screen.queryByLabelText("Capability")).toBeNull();- expect(screen.queryByLabelText("Purpose")).toBeNull();- expect(screen.queryByLabelText("Intent (optional)")).toBeNull();- fireEvent.click(screen.getByRole("button", { name: "Create dataset" }));- await waitFor(() =>- expect(done).toHaveBeenCalledWith({ datasetId: "dataset-1", projectId: "project-1" })- );- expect(mocks.dataset).toHaveBeenCalledWith({- datasetCreateRequest: expect.objectContaining({- brief: "Explore the uploaded data and determine how best to prepare it for training.",- capability: null,- intent: "train",- project: "project-1",- source: { uploads: ["upload-1"] },- }),- });-});-it("retries a failed dataset creation without creating another project", async () => {mocks.dataset.mockRejectedValueOnce(new Error("Landing unavailable"));const done = setup();diff --git a/frontend/src/components/optimiser/experiment-status.test.ts b/frontend/src/components/optimiser/experiment-status.test.tsindex 154243db..dc77de90 100644--- a/frontend/src/components/optimiser/experiment-status.test.ts+++ b/frontend/src/components/optimiser/experiment-status.test.ts@@ -1,17 +1,13 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type { OptimizerExperiment } from "@/openapi";-import { optimizerModelIds, optimizerRunTypeMeta } from "./experiment-status";+import { optimizerModelIds } from "./experiment-status";const experiment = (overrides: Partial<OptimizerExperiment> = {}) =>({ mode: "optimize", modelIds: null, ...overrides }) as OptimizerExperiment;describe("optimiser run type", () => {- it("uses descriptive names for code and model runs", () => {- expect(optimizerRunTypeMeta("optimize").label).toBe("Prompt & code optimisation");- expect(optimizerRunTypeMeta("model_comparison").label).toBe("Model comparison");- expect(optimizerRunTypeMeta("hybrid").label).toBe("Code + model optimisation");- });it("keeps only valid model ids for counts and search", () => {expect(optimizerModelIds(experiment({ modelIds: ["openai/gpt-4o", 7, null] }))).toEqual(["openai/gpt-4o",diff --git a/frontend/src/components/optimiser/experiment-winner.test.ts b/frontend/src/components/optimiser/experiment-winner.test.tsindex 4d03d1c5..4b5efa7d 100644--- a/frontend/src/components/optimiser/experiment-winner.test.ts+++ b/frontend/src/components/optimiser/experiment-winner.test.ts@@ -1,3 +1,4 @@+// covers: measured-factsimport { describe, expect, it } from "vitest";import type { WinnerCandidate } from "./experiment-winner";diff --git a/frontend/src/components/optimiser/experiments-table.test.tsx b/frontend/src/components/optimiser/experiments-table.test.tsxindex ddba858c..7817331f 100644--- a/frontend/src/components/optimiser/experiments-table.test.tsx+++ b/frontend/src/components/optimiser/experiments-table.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: live-consoleimport { cleanup, render, screen } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";diff --git a/frontend/src/components/optimiser/plateau.test.ts b/frontend/src/components/optimiser/plateau.test.tsindex 15af73b5..c9d83d97 100644--- a/frontend/src/components/optimiser/plateau.test.ts+++ b/frontend/src/components/optimiser/plateau.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import type { OptimizerExperiment } from "@/openapi";diff --git a/frontend/src/components/optimiser/run-locally-dialog.test.tsx b/frontend/src/components/optimiser/run-locally-dialog.test.tsxindex c40c08eb..0c08db4b 100644--- a/frontend/src/components/optimiser/run-locally-dialog.test.tsx+++ b/frontend/src/components/optimiser/run-locally-dialog.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";@@ -140,7 +141,6 @@ vi.mock("@/components/ui/select", () => ({import {buildBacktestPrompt,buildOptimisePrompt,- isBatchModel,isComparisonOptionDisabled,MAX_COMPARISON_MODELS,RunLocallyDialog,@@ -178,13 +178,6 @@ describe("toggleComparisonModel", () => {});});-describe("isBatchModel", () => {- it("detects OpenRouter batch slugs", () => {- expect(isBatchModel("openai/gpt-5-mini:batch")).toBe(true);- expect(isBatchModel("openai/gpt-5-mini")).toBe(false);- });-});-describe("isComparisonOptionDisabled", () => {it("disables the other lane and a sixth selection", () => {expect(isComparisonOptionDisabled(["openai/gpt-5-mini"], "openai/gpt-5-mini:batch")).toBe(true);diff --git a/frontend/src/components/repository-snapshot.test.tsx b/frontend/src/components/repository-snapshot.test.tsxindex 27d86967..d6fc78cd 100644--- a/frontend/src/components/repository-snapshot.test.tsx+++ b/frontend/src/components/repository-snapshot.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, render, screen } from "@testing-library/react";import { afterEach, expect, it } from "vitest";diff --git a/frontend/src/components/traces/filters.test.tsx b/frontend/src/components/traces/filters.test.tsxindex 887b049c..013fdc85 100644--- a/frontend/src/components/traces/filters.test.tsx+++ b/frontend/src/components/traces/filters.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";@@ -94,13 +95,6 @@ const valueSelect = () => screen.getAllByRole("combobox")[2] as HTMLSelectElemenconst optionValues = () => [...valueSelect().options].map((o) => o.value);describe("TracesFilters", () => {- it("labels the empty-state add-field trigger 'Add field', with no separate model-reported field", () => {- renderFilters();-- expect(screen.getByRole("button", { name: "Add field" })).toBeTruthy();- expect(screen.queryByText("Reported a model")).toBeNull();- });-it("commits 'Any model' as a real filter, not as an empty/uncommitted value", async () => {const onFiltersChange = renderFilters();diff --git a/frontend/src/components/traces/trace-bulk-source-picker.test.tsx b/frontend/src/components/traces/trace-bulk-source-picker.test.tsxindex 79e31004..48614d03 100644--- a/frontend/src/components/traces/trace-bulk-source-picker.test.tsx+++ b/frontend/src/components/traces/trace-bulk-source-picker.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logic/*** The selection is resolved server-side against EVERY project the user belongs to,* so it must carry its own project scope — the list request passes the project asdiff --git a/frontend/src/components/traces/trace-inspector.test.tsx b/frontend/src/components/traces/trace-inspector.test.tsxindex 53d948c4..58067095 100644--- a/frontend/src/components/traces/trace-inspector.test.tsx+++ b/frontend/src/components/traces/trace-inspector.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, fireEvent, render, screen, within } from "@testing-library/react";import { afterEach, describe, expect, it } from "vitest";diff --git a/frontend/src/components/traces/traces-table-toolbar.test.tsx b/frontend/src/components/traces/traces-table-toolbar.test.tsxindex 61e13aa7..bd2c6ff4 100644--- a/frontend/src/components/traces/traces-table-toolbar.test.tsx+++ b/frontend/src/components/traces/traces-table-toolbar.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type { Table } from "@tanstack/react-table";diff --git a/frontend/src/components/ui/data-table.a11y.test.tsx b/frontend/src/components/ui/data-table.a11y.test.tsxindex bca82852..a39af22a 100644--- a/frontend/src/components/ui/data-table.a11y.test.tsx+++ b/frontend/src/components/ui/data-table.a11y.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { act, cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";diff --git a/frontend/src/components/ui/data-table.empty-state.test.tsx b/frontend/src/components/ui/data-table.empty-state.test.tsxindex 9b39c559..b38a2191 100644--- a/frontend/src/components/ui/data-table.empty-state.test.tsx+++ b/frontend/src/components/ui/data-table.empty-state.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, render, screen } from "@testing-library/react";import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";diff --git a/frontend/src/components/ui/data-table.fill.test.tsx b/frontend/src/components/ui/data-table.fill.test.tsxindex aaf2c820..fe11721a 100644--- a/frontend/src/components/ui/data-table.fill.test.tsx+++ b/frontend/src/components/ui/data-table.fill.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { cleanup, render, screen } from "@testing-library/react";import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";diff --git a/frontend/src/components/ui/data-table.visibility.test.tsx b/frontend/src/components/ui/data-table.visibility.test.tsxindex 8b2d7df6..6a360048 100644--- a/frontend/src/components/ui/data-table.visibility.test.tsx+++ b/frontend/src/components/ui/data-table.visibility.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";diff --git a/frontend/src/components/ui/data-table.widths.test.ts b/frontend/src/components/ui/data-table.widths.test.tsindex a7bb49c2..1f01b728 100644--- a/frontend/src/components/ui/data-table.widths.test.ts+++ b/frontend/src/components/ui/data-table.widths.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { fillColumnWidths } from "./data-table";diff --git a/frontend/src/components/ui/datetime.test.ts b/frontend/src/components/ui/datetime.test.tsindex d8db7c54..df121917 100644--- a/frontend/src/components/ui/datetime.test.ts+++ b/frontend/src/components/ui/datetime.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { formatSmart } from "./datetime";diff --git a/frontend/src/components/ui/elbow-list.test.ts b/frontend/src/components/ui/elbow-list.test.tsindex dbb327b1..9e117740 100644--- a/frontend/src/components/ui/elbow-list.test.ts+++ b/frontend/src/components/ui/elbow-list.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { elbowHeightPx } from "./elbow-list";diff --git a/frontend/src/components/ui/icons/index.test.tsx b/frontend/src/components/ui/icons/index.test.tsxindex d1263345..5e1fb866 100644--- a/frontend/src/components/ui/icons/index.test.tsx+++ b/frontend/src/components/ui/icons/index.test.tsx@@ -1,3 +1,4 @@+// covers: console-logicimport { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vitest";diff --git a/frontend/src/components/ui/loading-state.test.tsx b/frontend/src/components/ui/loading-state.test.tsxindex 8248d252..f27a8134 100644--- a/frontend/src/components/ui/loading-state.test.tsx+++ b/frontend/src/components/ui/loading-state.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { cleanup, render, screen } from "@testing-library/react";import { afterEach, expect, it } from "vitest";diff --git a/frontend/src/config.test.ts b/frontend/src/config.test.tsindex 8ef82011..e3f1d8da 100644--- a/frontend/src/config.test.ts+++ b/frontend/src/config.test.ts@@ -1,3 +1,4 @@+// covers: bootimport { afterEach, describe, expect, it, vi } from "vitest";describe("clerkReady derivation", () => {diff --git a/frontend/src/hooks/fetch-all-eval-matrix.test.ts b/frontend/src/hooks/fetch-all-eval-matrix.test.tsindex 979c46f0..371c79be 100644--- a/frontend/src/hooks/fetch-all-eval-matrix.test.ts+++ b/frontend/src/hooks/fetch-all-eval-matrix.test.ts@@ -1,3 +1,4 @@+// covers: measured-factsimport { beforeEach, describe, expect, it, vi } from "vitest";vi.mock("@/client", () => ({diff --git a/frontend/src/hooks/fetch-all-eval-runs.test.ts b/frontend/src/hooks/fetch-all-eval-runs.test.tsindex a9e502fd..5e15cbcf 100644--- a/frontend/src/hooks/fetch-all-eval-runs.test.ts+++ b/frontend/src/hooks/fetch-all-eval-runs.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { beforeEach, describe, expect, it, vi } from "vitest";vi.mock("@/client", () => ({@@ -18,27 +19,6 @@ describe("fetchAllEvalRuns", () => {list.mockReset();});- it("returns a single page when next is null", async () => {- list.mockResolvedValueOnce({- count: 2,- next: null,- previous: null,- results: [{ id: "a" }, { id: "b" }],- });-- const data = await fetchAllEvalRuns("proj-1");-- expect(list).toHaveBeenCalledTimes(1);- expect(list).toHaveBeenCalledWith({- ordering: "-created_at",- page: 1,- pageSize: 100,- project: "proj-1",- });- expect(data.results.map((r) => r.id)).toEqual(["a", "b"]);- expect(data.count).toBe(2);- });-it("walks every DRF page until results cover count", async () => {list.mockResolvedValueOnce({diff --git a/frontend/src/hooks/project-datasets.test.ts b/frontend/src/hooks/project-datasets.test.tsindex c5be5bed..b9a3680a 100644--- a/frontend/src/hooks/project-datasets.test.ts+++ b/frontend/src/hooks/project-datasets.test.ts@@ -1,3 +1,4 @@+// covers: measured-factsimport { beforeEach, describe, expect, it, vi } from "vitest";vi.mock("@/client", () => ({diff --git a/frontend/src/hooks/use-capabilities.test.ts b/frontend/src/hooks/use-capabilities.test.tsindex 12f0fb88..efc69428 100644--- a/frontend/src/hooks/use-capabilities.test.ts+++ b/frontend/src/hooks/use-capabilities.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { beforeEach, describe, expect, it, vi } from "vitest";vi.mock("@/client", () => ({@@ -18,26 +19,6 @@ describe("fetchAllCapabilities", () => {list.mockReset();});- it("returns a single page when next is null", async () => {- list.mockResolvedValueOnce({- count: 2,- next: null,- previous: null,- results: [{ id: "a" }, { id: "b" }],- });-- const data = await fetchAllCapabilities("proj-1");-- expect(list).toHaveBeenCalledTimes(1);- expect(list).toHaveBeenCalledWith({- page: 1,- pageSize: 100,- project: "proj-1",- });- expect(data.results.map((r) => r.id)).toEqual(["a", "b"]);- expect(data.count).toBe(2);- });-it("walks every DRF page until results cover count", async () => {list.mockResolvedValueOnce({diff --git a/frontend/src/hooks/use-datasets.create.test.tsx b/frontend/src/hooks/use-datasets.create.test.tsxindex 51a90469..4d156bc1 100644--- a/frontend/src/hooks/use-datasets.create.test.tsx+++ b/frontend/src/hooks/use-datasets.create.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport type { ReactNode } from "react";diff --git a/frontend/src/hooks/use-evaluations.delete.test.tsx b/frontend/src/hooks/use-evaluations.delete.test.tsxindex 4e2debd0..dc06260b 100644--- a/frontend/src/hooks/use-evaluations.delete.test.tsx+++ b/frontend/src/hooks/use-evaluations.delete.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { act, cleanup, renderHook } from "@testing-library/react";import { afterEach, expect, it, vi } from "vitest";diff --git a/frontend/src/hooks/use-evaluations.rows.test.tsx b/frontend/src/hooks/use-evaluations.rows.test.tsxindex 2734251d..1264a7f2 100644--- a/frontend/src/hooks/use-evaluations.rows.test.tsx+++ b/frontend/src/hooks/use-evaluations.rows.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { cleanup, renderHook, waitFor } from "@testing-library/react";import { afterEach, expect, it, vi } from "vitest";diff --git a/frontend/src/hooks/use-finetuning.name.test.ts b/frontend/src/hooks/use-finetuning.name.test.tsindex b752f93e..387818df 100644--- a/frontend/src/hooks/use-finetuning.name.test.ts+++ b/frontend/src/hooks/use-finetuning.name.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { defaultFinetuneName } from "./use-finetuning";diff --git a/frontend/src/hooks/use-finetuning.poll.test.ts b/frontend/src/hooks/use-finetuning.poll.test.tsindex db3ff24f..d4c9d85b 100644--- a/frontend/src/hooks/use-finetuning.poll.test.ts+++ b/frontend/src/hooks/use-finetuning.poll.test.ts@@ -1,3 +1,4 @@+// covers: console-logic/** The poll must terminate: the key carries page and filters, so a* never-stopping interval means one live 5s loop per visited page. */import { describe, expect, it } from "vitest";diff --git a/frontend/src/hooks/use-finetuning.runs.test.ts b/frontend/src/hooks/use-finetuning.runs.test.tsindex d5f1108e..1678d5cf 100644--- a/frontend/src/hooks/use-finetuning.runs.test.ts+++ b/frontend/src/hooks/use-finetuning.runs.test.ts@@ -1,3 +1,4 @@+// covers: live-consoleimport type { UseQueryOptions } from "@tanstack/react-query";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -103,74 +104,6 @@ describe("useFinetuningRunsQuery", () => {expect(poll(query([{ status: "preprocessing" }]))).toBe(5_000);expect(poll(query([], 3))).toBe(false);});-- it("keys every param and sends none of the empty ones", async () => {- const options = optionsOf(() =>- useFinetuningRunsQuery({ page: 2, pageSize: 25, projectId: "proj-1", search: " " })- );-- expect(options.queryKey).toEqual([- "finetuning-runs",- null,- "proj-1",- 2,- 25,- null,- null,- null,- null,- ]);-- await fetchWith(options);- expect(mocks.runsList).toHaveBeenCalledWith({- baseModel: undefined,- dataset: undefined,- ordering: undefined,- page: 2,- pageSize: 25,- project: "proj-1",- search: undefined,- status: undefined,- });- });-- it("carries the filters into both the key and the request", async () => {- const options = optionsOf(() =>- useFinetuningRunsQuery({- baseModel: "meta/llama-3.1-8b",- dataset: "ds-1",- ordering: "-credits",- page: 1,- pageSize: 25,- projectId: "proj-1",- search: " nightly ",- status: "failed",- })- );-- expect(options.queryKey).toEqual([- "finetuning-runs",- "-credits",- "proj-1",- 1,- 25,- "nightly",- "failed",- "ds-1",- "meta/llama-3.1-8b",- ]);-- await fetchWith(options);- expect(mocks.runsList).toHaveBeenCalledWith(- expect.objectContaining({- baseModel: "meta/llama-3.1-8b",- dataset: "ds-1",- ordering: "-credits",- search: "nightly",- status: "failed",- })- );- });});describe("useFinetuningRunJobsQuery", () => {diff --git a/frontend/src/hooks/use-guest-gate.test.tsx b/frontend/src/hooks/use-guest-gate.test.tsxindex 0ab5c03d..4004598e 100644--- a/frontend/src/hooks/use-guest-gate.test.tsx+++ b/frontend/src/hooks/use-guest-gate.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: authenticationimport { renderHook } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";diff --git a/frontend/src/hooks/use-inference.scope.test.tsx b/frontend/src/hooks/use-inference.scope.test.tsxindex 0be72cbc..46bfdafa 100644--- a/frontend/src/hooks/use-inference.scope.test.tsx+++ b/frontend/src/hooks/use-inference.scope.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport type { ReactNode } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";diff --git a/frontend/src/hooks/use-project-search-sync.test.ts b/frontend/src/hooks/use-project-search-sync.test.tsindex c01fe580..c73ab1e0 100644--- a/frontend/src/hooks/use-project-search-sync.test.ts+++ b/frontend/src/hooks/use-project-search-sync.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { projectIdFromProjectsDetailPath } from "./use-project-search-sync";diff --git a/frontend/src/hooks/use-table-sort.test.tsx b/frontend/src/hooks/use-table-sort.test.tsxindex df5a8049..2257d880 100644--- a/frontend/src/hooks/use-table-sort.test.tsx+++ b/frontend/src/hooks/use-table-sort.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { cleanup, fireEvent, render, screen, within } from "@testing-library/react";import { afterEach, expect, it } from "vitest";diff --git a/frontend/src/hooks/use-traces.model.test.ts b/frontend/src/hooks/use-traces.model.test.tsindex 097fb886..6c75d905 100644--- a/frontend/src/hooks/use-traces.model.test.ts+++ b/frontend/src/hooks/use-traces.model.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { pickModel } from "./use-traces";diff --git a/frontend/src/hooks/use-traces.request.test.ts b/frontend/src/hooks/use-traces.request.test.tsindex 5f310fcc..e4d2abcd 100644--- a/frontend/src/hooks/use-traces.request.test.ts+++ b/frontend/src/hooks/use-traces.request.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { tracesSearchSchema } from "@/lib/schemas";diff --git a/frontend/src/hooks/use-uploads.test.ts b/frontend/src/hooks/use-uploads.test.tsindex c17f88b4..cf1bda1e 100644--- a/frontend/src/hooks/use-uploads.test.ts+++ b/frontend/src/hooks/use-uploads.test.ts@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: measured-factsimport { act, cleanup, renderHook, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";diff --git a/frontend/src/lib/autohide-scrollbars.test.ts b/frontend/src/lib/autohide-scrollbars.test.tsindex 4854d639..71cf1eb3 100644--- a/frontend/src/lib/autohide-scrollbars.test.ts+++ b/frontend/src/lib/autohide-scrollbars.test.ts@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { installAutohideScrollbars } from "./autohide-scrollbars";diff --git a/frontend/src/lib/chunk-error.test.ts b/frontend/src/lib/chunk-error.test.tsindex 71c21c1f..317f9d67 100644--- a/frontend/src/lib/chunk-error.test.ts+++ b/frontend/src/lib/chunk-error.test.ts@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";diff --git a/frontend/src/lib/clipboard.test.ts b/frontend/src/lib/clipboard.test.tsindex 7ec87e22..e37e08a3 100644--- a/frontend/src/lib/clipboard.test.ts+++ b/frontend/src/lib/clipboard.test.ts@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { afterEach, describe, expect, it, vi } from "vitest";import { writeClipboardText } from "./clipboard";diff --git a/frontend/src/lib/colors.test.ts b/frontend/src/lib/colors.test.tsindex 86e0d321..4bc7abfe 100644--- a/frontend/src/lib/colors.test.ts+++ b/frontend/src/lib/colors.test.ts@@ -1,3 +1,4 @@+// covers: measured-factsimport { describe, expect, it } from "vitest";import { domainStatus, scoreChipClass, scoreTone, TONE_CHIP } from "./colors";diff --git a/frontend/src/lib/drf-ordering.test.ts b/frontend/src/lib/drf-ordering.test.tsindex bf3dbac9..05258a54 100644--- a/frontend/src/lib/drf-ordering.test.ts+++ b/frontend/src/lib/drf-ordering.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { cycleDrfOrdering, parseDrfOrdering } from "./drf-ordering";diff --git a/frontend/src/lib/eval-preload.test.ts b/frontend/src/lib/eval-preload.test.tsindex 712431cf..43400dbf 100644--- a/frontend/src/lib/eval-preload.test.ts+++ b/frontend/src/lib/eval-preload.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import {diff --git a/frontend/src/lib/formatters.test.ts b/frontend/src/lib/formatters.test.tsindex d42d3150..b4a5efba 100644--- a/frontend/src/lib/formatters.test.ts+++ b/frontend/src/lib/formatters.test.ts@@ -1,3 +1,4 @@+// covers: measured-factsimport { describe, expect, it } from "vitest";import { formatCost, formatDuration, formatNumber, truncateText } from "./formatters";diff --git a/frontend/src/lib/guest.test.ts b/frontend/src/lib/guest.test.tsindex 1a5bd1ba..7783e4b6 100644--- a/frontend/src/lib/guest.test.ts+++ b/frontend/src/lib/guest.test.ts@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: authenticationimport { beforeEach, describe, expect, it, vi } from "vitest";import {diff --git a/frontend/src/lib/label-case.test.ts b/frontend/src/lib/label-case.test.tsindex 92dc0333..bc05df69 100644--- a/frontend/src/lib/label-case.test.ts+++ b/frontend/src/lib/label-case.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import { humanizeKey, sentenceCase } from "./label-case";diff --git a/frontend/src/lib/mcp-setup.test.ts b/frontend/src/lib/mcp-setup.test.tsindex 6792856d..5315496c 100644--- a/frontend/src/lib/mcp-setup.test.ts+++ b/frontend/src/lib/mcp-setup.test.ts@@ -1,3 +1,4 @@+// covers: mcp-surfaceimport { describe, expect, it, vi } from "vitest";import {@@ -42,19 +43,6 @@ describe("mcp setup snippets", () => {);});- it("installs from PyPI on every host", () => {- for (const host of [STAGING, PROD, LOCAL]) {- expect(sdkPipInstall(host)).toBe('python -m pip install "overmind>=0.1.106"');- expect(sdkPipInstall(host, "tracing")).toBe(- 'python -m pip install "overmind[tracing]>=0.1.106"'- );- }- });-- it("preflights with the CLI version", () => {- expect(SDK_PREFLIGHT_COMMAND).toBe("python -m overmind --version");- });-it("flags --env from the Console API host", () => {expect(mcpInitEnvFlag(PROD)).toBe("");expect(mcpInitEnvFlag(`${PROD}/`)).toBe("");diff --git a/frontend/src/lib/running-jobs.test.ts b/frontend/src/lib/running-jobs.test.tsindex 18d7414c..451f80af 100644--- a/frontend/src/lib/running-jobs.test.ts+++ b/frontend/src/lib/running-jobs.test.ts@@ -1,3 +1,4 @@+// covers: live-consoleimport { describe, expect, it } from "vitest";import {diff --git a/frontend/src/lib/schemas.test.ts b/frontend/src/lib/schemas.test.tsindex 30772810..97ef22d1 100644--- a/frontend/src/lib/schemas.test.ts+++ b/frontend/src/lib/schemas.test.ts@@ -1,3 +1,4 @@+// covers: live-consoleimport { describe, expect, it } from "vitest";import {@@ -10,26 +11,6 @@ import {describe("schemas", () => {describe("tracesSearchSchema", () => {- it("parses empty object with defaults", () => {- const result = tracesSearchSchema.parse({});- expect(result.timeRange).toBe("all");- expect(result.ordering).toBe("-start_time_ns");- expect(result.page).toBe(1);- expect(result.page_size).toBe(25);- expect(result.view).toBe("roots");- });-- it("parses valid search params", () => {- const result = tracesSearchSchema.parse({- projectId: "proj-1",- search: "test",- timeRange: "past24h",- });- expect(result.projectId).toBe("proj-1");- expect(result.timeRange).toBe("past24h");- expect(result.search).toBe("test");- });-it("opens old reporting links in Traces", () => {expect(tracesSearchSchema.parse({ view: "overview" }).view).toBe("roots");});@@ -80,14 +61,6 @@ describe("schemas", () => {});describe("evaluationsSearchSchema", () => {- it("parses empty with unfiltered defaults", () => {- const result = evaluationsSearchSchema.parse({});- expect(result.view).toBe("runs");- expect(result.run_status).toBe("all");- expect(result.run_capability).toBe("all");- expect(result.run_dataset).toBe("all");- expect(result.run_search).toBe("");- });it("round-trips a deep link carrying both a page and runs filters", () => {const result = evaluationsSearchSchema.parse({page: "3",@@ -130,12 +103,6 @@ describe("schemas", () => {expect(result.run_search).toBe("gpt");expect(result.run_status).toBe("running");});- it("defaults to unfiltered", () => {- const result = optimiserSearchSchema.parse({});- expect(result.run_status).toBe("all");- expect(result.run_capability).toBe("all");- expect(result.run_search).toBe("");- });it("accepts optimize + capability deep-link params", () => {const result = optimiserSearchSchema.parse({capabilityId: "capability-1",@@ -147,15 +114,6 @@ describe("schemas", () => {});describe("trainingSearchSchema", () => {- it("parses empty with unfiltered defaults", () => {- const result = trainingSearchSchema.parse({});- expect(result.page).toBe(1);- expect(result.page_size).toBe(25);- expect(result.ft_status).toBe("all");- expect(result.ft_dataset).toBe("all");- expect(result.ft_model).toBe("all");- expect(result.ft_search).toBe("");- });it("round-trips a page, the history filters and an open run together", () => {const result = trainingSearchSchema.parse({ft_dataset: "ds-1",@@ -186,12 +144,6 @@ describe("schemas", () => {});describe("datasetsSearchSchema", () => {- it("parses empty with unfiltered defaults", () => {- const result = datasetsSearchSchema.parse({});- expect(result.ds_search).toBe("");- expect(result.ds_role).toBe("all");- expect(result.ds_capability).toBe("all");- });it("accepts the create deep-link param", () => {const result = datasetsSearchSchema.parse({ create: true, ds_capability: "capability-1" });expect(result.create).toBe(true);diff --git a/frontend/src/lib/scroll-lock-escape.test.ts b/frontend/src/lib/scroll-lock-escape.test.tsindex 442bba20..f69a0d3f 100644--- a/frontend/src/lib/scroll-lock-escape.test.ts+++ b/frontend/src/lib/scroll-lock-escape.test.ts@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: console-logicimport { afterEach, describe, expect, it } from "vitest";import { escapeScrollLock } from "./scroll-lock-escape";diff --git a/frontend/src/lib/utils.test.ts b/frontend/src/lib/utils.test.tsindex 897d742e..4e23954c 100644--- a/frontend/src/lib/utils.test.ts+++ b/frontend/src/lib/utils.test.ts@@ -1,3 +1,4 @@+// covers: console-logicimport { describe, expect, it } from "vitest";import {diff --git a/frontend/src/local-login.test.tsx b/frontend/src/local-login.test.tsxdeleted file mode 100644index 9e9a2fc8..00000000--- a/frontend/src/local-login.test.tsx+++ /dev/null@@ -1,62 +0,0 @@-// @vitest-environment jsdom-// @vitest-environment-options {"url":"http://127.0.0.1:5173"}--import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- authLocalCreate: vi.fn(),- invalidateQueries: vi.fn(),- setTokens: vi.fn(),-}));--vi.mock("@/client", () => ({- default: {- auth: { authLocalCreate: mocks.authLocalCreate },- },- setTokens: mocks.setTokens,-}));--vi.mock("@/integrations/tanstack-query", () => ({- getContext: () => ({ queryClient: { invalidateQueries: mocks.invalidateQueries } }),-}));--import { LocalLoginForm } from "./components/local-login-form";--afterEach(cleanup);--beforeEach(() => {- vi.clearAllMocks();- mocks.authLocalCreate.mockReset();- mocks.setTokens.mockReset();- mocks.invalidateQueries.mockReset();-});--describe("LocalLoginForm", () => {- it("posts email and password to authLocalCreate and stores tokens", async () => {- mocks.authLocalCreate.mockResolvedValue({- access: "access-token",- refresh: "refresh-token",- user: { email: "[email protected]" },- });- const onSignedIn = vi.fn();-- render(<LocalLoginForm onSignedIn={onSignedIn} />);-- fireEvent.change(screen.getByLabelText("Email"), {- target: { value: "[email protected]" },- });- fireEvent.change(screen.getByLabelText("Password"), {- target: { value: "password123" },- });- fireEvent.click(screen.getByRole("button", { name: "Continue" }));-- await waitFor(() => {- expect(mocks.authLocalCreate).toHaveBeenCalledWith({- localSessionRequest: { email: "[email protected]", password: "password123" },- });- });- expect(mocks.setTokens).toHaveBeenCalledWith("access-token", "refresh-token");- expect(onSignedIn).toHaveBeenCalled();- });-});diff --git a/frontend/src/routes/_auth/-inference.filter.test.tsx b/frontend/src/routes/_auth/-inference.filter.test.tsxindex 1610b45b..e34e8d71 100644--- a/frontend/src/routes/_auth/-inference.filter.test.tsx+++ b/frontend/src/routes/_auth/-inference.filter.test.tsx@@ -1,4 +1,5 @@// @vitest-environment jsdom+// covers: live-console// Forwarding `?capability=all` would 400 the list (the backend filter is a// `UUIDFilter`), and re-filtering a fetched page client-side would leave `count`// describing a different set than `results`.diff --git a/frontend/src/routes/_auth/-inference.search.test.ts b/frontend/src/routes/_auth/-inference.search.test.tsindex d6145588..a1d16e84 100644--- a/frontend/src/routes/_auth/-inference.search.test.ts+++ b/frontend/src/routes/_auth/-inference.search.test.ts@@ -1,3 +1,4 @@+// covers: live-console// A deep-linked page has to survive the route's own search validation: zod// strips keys the schema doesn't declare, and the request follows the parsed// search, not the URL.@@ -46,15 +47,6 @@ describe("Inference route search", () => {// The filters scope the request, so a missing one must parse to "unfiltered"// rather than let `undefined` reach the query.- it("falls back to the unfiltered first page", () => {- expect(parse({ projectId: "proj-1" })).toEqual({- inf_capability: "all",- inf_search: "",- page: 1,- page_size: 25,- projectId: "proj-1",- });- });});// The model URL is the only copy of the list's filters, and every affordance@@ -86,13 +78,4 @@ describe("Model detail route search", () => {"__none__");});-- it("still parses a bare project link into the list's defaults", () => {- expect(parseDetail({ projectId: "proj-1" })).toMatchObject({- inf_capability: "all",- inf_search: "",- page: 1,- page_size: 25,- });- });});diff --git a/frontend/src/self-hosted-analytics.test.ts b/frontend/src/self-hosted-analytics.test.tsindex 3aa913dd..170337a2 100644--- a/frontend/src/self-hosted-analytics.test.ts+++ b/frontend/src/self-hosted-analytics.test.ts@@ -1,3 +1,4 @@+// covers: privacyimport { afterEach, describe, expect, it, vi } from "vitest";const posthogInit = vi.fn();diff --git a/frontend/src/test/setup.ts b/frontend/src/test/setup.tsindex 3f096367..038da2e1 100644--- a/frontend/src/test/setup.ts+++ b/frontend/src/test/setup.ts@@ -1,3 +1,7 @@+import { readFileSync } from "node:fs";+import { resolve } from "node:path";+import { beforeAll } from "vitest";+// Node 22+ can expose a broken window.localStorage under jsdom without// --localstorage-file; guest and client tests need a working store.function ensureLocalStorage(): void {@@ -38,3 +42,35 @@ function ensureLocalStorage(): void {}ensureLocalStorage();++const ENTRY_KINDS = new Map(+ Array.from(+ readFileSync(resolve(process.cwd(), "../tests/coverage_map.py"), "utf8").matchAll(+ /"([\w-]+)": Entry\(\s*S\d,\s*(PROMISE|INVARIANT|CONTRACT|LOGIC)/g+ ),+ ([, slug, kind]) => [slug, kind]+ )+);++// Every test file names the one tests/coverage_map.py entry it covers, as pytest+// collection requires of backend tests.+// biome-ignore lint/correctness/noEmptyPattern: vitest 4 passes the suite second and requires a destructured context first.+beforeAll(({}, suite) => {+ const path = suite.file.filepath;+ const covers = Array.from(+ readFileSync(path, "utf8").matchAll(/^\/\/ covers: (\S+)$/gm),+ ([, slug]) => slug+ );+ if (covers.length !== 1) {+ throw new Error(+ `${path}: add one "// covers: <entry>" line naming its tests/coverage_map.py entry`+ );+ }+ const kind = ENTRY_KINDS.get(covers[0]);+ if (kind === undefined) {+ throw new Error(`${path}: "${covers[0]}" is not in tests/coverage_map.py`);+ }+ if (kind === "PROMISE") {+ throw new Error(`${path}: a promise is covered only by its journey`);+ }+});diff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.pyindex 77291ff8..e4611492 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.114"+__version__ = "0.1.115"from .client import Client, ModelDeleted, OvermindInferenceErrordiff --git a/overmind/pyproject.toml b/overmind/pyproject.tomlindex 640d12ad..9c286de7 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.114"+version = "0.1.115"[project.urls]"Agent setup" = "https://console.overmindlab.ai/setup.md"diff --git a/overmind/tests/conftest.py b/overmind/tests/conftest.pyindex aa06c415..84afeac4 100644--- a/overmind/tests/conftest.py+++ b/overmind/tests/conftest.py@@ -3,6 +3,9 @@from __future__ import annotationsimport os+import sys+import types+from pathlib import Pathimport pytestfrom opentelemetry import trace as _otel_trace@@ -10,6 +13,16 @@ from opentelemetry.sdk.trace import TracerProviderimport overmind.tracing as _overmind_tracing+# The coverage map is monorepo-wide: the platform's collection guard checks these tests too.+_platform_tests = types.ModuleType("platform_tests")+_platform_tests.__path__ = [str(Path(__file__).resolve().parents[2] / "tests")]+sys.modules["platform_tests"] = _platform_tests++from platform_tests.coverage_guard import ( # noqa: E402+ pytest_collection_modifyitems, # noqa: F401+ pytest_configure, # noqa: F401+)+## ``overmind.start_span`` / ``overmind.observe`` / ``overmind.set_tag`` all# go through ``overmind.tracing.get_tracer()`` which raises untildiff --git a/overmind/tests/test_analytics.py b/overmind/tests/test_analytics.pyindex c0d50471..d9a1c063 100644--- a/overmind/tests/test_analytics.py+++ b/overmind/tests/test_analytics.py@@ -11,6 +11,8 @@ import pytestimport overmind.analytics as analytics+pytestmark = pytest.mark.covers("privacy")+@pytest.fixture(autouse=True)def _reset_analytics(tmp_path, monkeypatch):@@ -42,6 +44,7 @@ def test_enabled_defaults_on(monkeypatch):assert analytics.enabled() is True[email protected]("sdk-install")def test_cli_and_client_work_without_posthog(tmp_path):script = """import sys@@ -129,6 +132,7 @@ def test_capture_sends_allowed_properties_only(monkeypatch, posthog_client):assert "prompt" not in props[email protected]("sdk-install")def test_capture_swallows_client_errors(monkeypatch, posthog_client):monkeypatch.setenv("OVERMIND_ANALYTICS_ENABLED", "true")monkeypatch.setattr(analytics, "ensure_identified", lambda **_: False)@@ -136,28 +140,6 @@ def test_capture_swallows_client_errors(monkeypatch, posthog_client):analytics.capture("sdk_init", outcome="keyless")-def test_distinct_id_persists(tmp_path, monkeypatch):- path = tmp_path / "analytics_id"- monkeypatch.setattr(analytics, "_ANALYTICS_ID_PATH", path)- first = analytics._distinct_id()- second = analytics._distinct_id()- assert first == second- assert path.read_text(encoding="utf-8").strip() == first--- "argv,command",- [- (["overmind", "sync"], "sync"),- (["overmind", "dataset", "upload", "data.jsonl"], "dataset upload"),- (["overmind", "optimise", "start", "--json"], "optimise start"),- (["overmind", "--version"], ""),- ],-)-def test_cli_command_from_argv(argv, command):- assert analytics.cli_command_from_argv(argv) == command--def test_redact_argv_strips_secrets():line = analytics._redact_argv(["overmind",@@ -200,52 +182,6 @@ def test_cli_flags_and_args(argv, flags, args):assert analytics.cli_flags_and_args(argv) == (flags, args)-def test_track_cli_invocation_emits_full_command(monkeypatch, posthog_client):- monkeypatch.setenv("OVERMIND_ANALYTICS_ENABLED", "true")- monkeypatch.setattr(analytics, "ensure_identified", lambda **_: False)- monkeypatch.setattr(- analytics,- "_redact_argv",- lambda argv=None: "overmind skills list --json",- )- monkeypatch.setattr(- analytics,- "cli_flags_and_args",- lambda argv=None: ({"json": True}, []),- )-- analytics.track_cli_invocation(command="skills list", exit_code=0, duration_ms=42)-- call = posthog_client.capture.call_args- assert call.args == ("cli.invoked",)- props = call.kwargs["properties"]- # ``command`` is the full line people look for in PostHog.- assert props["command"] == "overmind skills list --json"- assert props["command_path"] == "skills list"- assert props["flags"] == {"json": True}- assert props["args"] == []- assert props["exit_code"] == 0- assert props["duration_ms"] == 42- assert props["success"] is True- assert props["surface"] == "cli"- # The CLI process is short-lived: the event must be flushed, not queued.- posthog_client.flush.assert_called_once()---def test_track_cli_invocation_records_failure(monkeypatch, posthog_client):- monkeypatch.setenv("OVERMIND_ANALYTICS_ENABLED", "true")- monkeypatch.setattr(analytics, "ensure_identified", lambda **_: False)- monkeypatch.setattr(analytics, "_redact_argv", lambda argv=None: "overmind boom")-- analytics.track_cli_invocation(command="boom", exit_code=1, duration_ms=3)-- props = posthog_client.capture.call_args.kwargs["properties"]- assert props["command"] == "overmind boom"- assert props["command_path"] == "boom"- assert props["exit_code"] == 1- assert props["success"] is False--def test_ensure_identified_caches_per_key(monkeypatch, tmp_path, posthog_client):monkeypatch.setenv("OVERMIND_ANALYTICS_ENABLED", "true")monkeypatch.setattr(analytics, "_IDENTITY_CACHE_PATH", tmp_path / "identity")diff --git a/overmind/tests/test_attrs.py b/overmind/tests/test_attrs.pydeleted file mode 100644index 2954855b..00000000--- a/overmind/tests/test_attrs.py+++ /dev/null@@ -1,48 +0,0 @@-"""Regression guards for ``overmind.attrs`` constant values.--These tests pin the wire-format namespaces so an accidental rename does not-silently break trace ingestion.--The CANONICAL token/cost namespace the Overmind server rolls up is ``genai.*``-(see ``overbae/api/overmind_attrs.py`` + ``otlp.py::_build_span_usage``). The-SDK emits those keys AND, alongside them, the OTel GenAI semconv ``gen_ai.*``-keys (defined here as ``OTEL_*``) so OTel-native consumers and the optimiser's-:mod:`overmind.optimize.trace_reader` keep resolving model + tokens.-"""--from __future__ import annotations--from overmind import attrs---class TestLLMNamespace:- """Canonical LLM_* constants must live in the server's ``genai.*`` namespace."""-- def test_all_llm_constants_start_with_genai(self) -> None:- offenders = [- (name, value)- for name, value in vars(attrs).items()- if name.startswith("LLM_") and isinstance(value, str) and not value.startswith("genai.")- ]- assert offenders == [], (- f"Found LLM_* constants outside the genai.* namespace: {offenders}. "- "The backend ingest rolls up genai.* keys; OTel semconv keys live under OTEL_*."- )-- def test_otel_semconv_aliases_stay_in_gen_ai_namespace(self) -> None:- # The dual-emitted OTel semconv keys the trace_reader depends on.- assert attrs.OTEL_LLM_REQUEST_MODEL == "gen_ai.request.model"- assert attrs.OTEL_LLM_SYSTEM == "gen_ai.system"- assert attrs.OTEL_LLM_USAGE_PROMPT_TOKENS == "gen_ai.usage.prompt_tokens"- assert attrs.OTEL_LLM_USAGE_COMPLETION_TOKENS == "gen_ai.usage.completion_tokens"- assert attrs.OTEL_LLM_USAGE_TOTAL_TOKENS == "gen_ai.usage.total_tokens"---class TestBehaviourKey:- def test_declared_task_key_is_pinned(self) -> None:- assert attrs.BEHAVIOUR_KEY == "overmind.behaviour.key"---class TestErrorSummary:- def test_error_summary_key(self) -> None:- assert attrs.ERROR_SUMMARY == "overmind.error"diff --git a/overmind/tests/test_backtest.py b/overmind/tests/test_backtest.pyindex 0dd88ca7..dd19abed 100644--- a/overmind/tests/test_backtest.py+++ b/overmind/tests/test_backtest.py@@ -12,6 +12,8 @@ import pytestfrom overmind.backtest import OPENROUTER_BASE_URL, openrouter_env, rewrite_repo, write_state+pytestmark = pytest.mark.covers("agent-code")+def test_openrouter_env_requires_key(monkeypatch):monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)@@ -20,14 +22,6 @@ def test_openrouter_env_requires_key(monkeypatch):openrouter_env("openai/gpt-5-mini")-def test_openrouter_env_sets_model_and_base(monkeypatch):- monkeypatch.setenv("OPENROUTER_API_KEY", "sk-test")- env = openrouter_env("anthropic/claude-sonnet-4")- assert env["OPENROUTER_MODEL"] == "anthropic/claude-sonnet-4"- assert env["OPENAI_BASE_URL"] == OPENROUTER_BASE_URL- assert env["OPENAI_API_KEY"] == "sk-test"--def test_write_state_merges(tmp_path):path = write_state(tmp_path, {"experiment_id": "aaa", "models": ["m1"]})write_state(tmp_path, {"models": ["m1", "m2"]})diff --git a/overmind/tests/test_capability.py b/overmind/tests/test_capability.pyindex a58c5dac..2a5afe76 100644--- a/overmind/tests/test_capability.py+++ b/overmind/tests/test_capability.py@@ -28,6 +28,8 @@ from overmind.tracing import (tool,)+pytestmark = pytest.mark.covers("sdk-wire")+@pytest.fixturedef exporter(monkeypatch):diff --git a/overmind/tests/test_chassis.py b/overmind/tests/test_chassis.pyindex 32c1f66f..b436a616 100644--- a/overmind/tests/test_chassis.py+++ b/overmind/tests/test_chassis.py@@ -1,10 +1,8 @@-import jsonimport textwrapfrom pathlib import Path-from typer.testing import CliRunner+import pytest-from overmind.__main__ import appfrom overmind.chassis import (chassis_digest,declared_expectations,@@ -12,8 +10,8 @@ from overmind.chassis import (reachable_names,verify_trajectory_claims,)-from overmind.config import load-from overmind.utils import convert_json_to_toml++pytestmark = pytest.mark.covers("agent-code")AGENT_SRC = textwrap.dedent("""@@ -89,53 +87,6 @@ def test_verify_trajectory_claims_stamps_verified(tmp_path):assert by_id["anchorless"]["verified"] is False-def test_convert_json_to_toml_stamps_verified(tmp_path):- _repo(tmp_path)- src = tmp_path / "overmind_capabilities.json"- src.write_text(- json.dumps({- "repo_summary": "demo",- "capabilities": [- {- "slug_hint": "triage",- "name": "Triage",- "capability_card": {- "task": "triage",- "anchors": [- {- "qualname": "app.agent.run_turn",- "kind": "entry_point",- "file": "app/agent.py",- },- {- "qualname": "app.agent.call_llm_tools",- "kind": "function",- "file": "app/agent.py",- },- ],- "trajectory_map": [- {- "id": "handle-turn",- "anchors": ["app.agent.run_turn", "app.agent.call_llm_tools"],- },- {- "id": "fabricated",- "anchors": ["app.agent.does_not_exist"],- },- ],- },- "eval_matrix": [{"name": "Quality", "type": "custom_judge", "rubric": "score"}],- }- ],- })- )- dest = tmp_path / "overmind.toml"- convert_json_to_toml(src, dest, repo_root=tmp_path)- paths = {p["id"]: p for p in load(dest).capabilities["triage"].capability_card["trajectory_map"]}- assert paths["handle-turn"]["verified"] is True- assert paths["fabricated"]["verified"] is False--DECORATED_SRC = textwrap.dedent("""import overmind@@ -170,15 +121,6 @@ def test_declared_expectations_follow_the_entry_points_call_graph(tmp_path):}-def test_chassis_cli_prints_digest(tmp_path, monkeypatch):- _repo(tmp_path)- monkeypatch.chdir(tmp_path)- result = CliRunner().invoke(app, ["chassis"], catch_exceptions=False)- assert result.exit_code == 0, result.output- assert "app.agent.run_turn" in result.output- assert "5 functions across 1 files" in result.output--def test_declarations_keep_the_entrypoint_module_when_class_names_repeat(tmp_path):for name in ("browser", "helper"):(tmp_path / f"{name}.py").write_text(diff --git a/overmind/tests/test_checkpoint_transfer_journey.py b/overmind/tests/test_checkpoint_transfer_journey.pyindex 50865f7e..d8a1ad2f 100644--- a/overmind/tests/test_checkpoint_transfer_journey.py+++ b/overmind/tests/test_checkpoint_transfer_journey.py@@ -6,7 +6,8 @@ import pytestfrom typer.testing import CliRunnerfrom overmind.__main__ import app-from overmind.config import Config, dump++pytestmark = pytest.mark.covers("privacy")@pytest.fixture@@ -73,20 +74,6 @@ def test_repository_free_download_uses_address_bound_account_without_forwarding_assert "local-test-account" not in result.output[email protected]("credentials", ["saved", "repository"])-def test_checkpoint_endpoint_override_cannot_move_a_bound_key(checkpoint_host, credentials):- base, observed, _, _ = checkpoint_host- if credentials == "repository":- dump(- Config(api_key="repository-test-key", base_url=base, project_id="project"),- __import__("pathlib").Path("overmind.toml"),- )- result = run_download("--api-url", "http://localhost:1")- assert result.exit_code == 1- assert "different API" in result.output- assert observed == []--@pytest.mark.parametrize("stage", ["metadata", "artifact"])def test_checkpoint_redirects_are_refused_without_following_or_retaining_bytes(checkpoint_host, tmp_path, stage):base, observed, mode, _ = checkpoint_hostdiff --git a/overmind/tests/test_client.py b/overmind/tests/test_client.pyindex 05507b37..0dc14839 100644--- a/overmind/tests/test_client.py+++ b/overmind/tests/test_client.py@@ -18,6 +18,8 @@ from overmind.client import (_raise_for_status,)+pytestmark = pytest.mark.covers("sdk-wire")+def _make_client(base_url: str = "https://api.example.com") -> Client:return Client(api_key="om-test-key", base_url=base_url)@@ -47,6 +49,7 @@ def _sse_response(lines: list[str]) -> MagicMock:return resp[email protected]("authentication")class TestClientInit:def test_raises_without_api_key(self, monkeypatch):monkeypatch.delenv("OVERMIND_API_KEY", raising=False)@@ -78,15 +81,6 @@ class TestClientInit:c = Client(api_key="k", base_url="https://explicit.example.com")assert c._base_url == "https://explicit.example.com"- def test_default_base_url_when_no_env(self, monkeypatch):- monkeypatch.delenv("OVERMIND_API_URL", raising=False)- c = Client(api_key="k")- assert c._base_url == "https://api.overmindlab.ai"-- def test_content_type_header_set(self):- c = _make_client()- assert c._session.headers.get("Content-Type") == "application/json"-class TestRaiseForStatus:def test_error_falls_back_to_text_when_no_json(self):@@ -254,18 +248,6 @@ class TestModelsGet:"base_model": "meta-llama/llama-3.1-8b-instruct",}- def test_404_raises_inference_error(self):- c = _make_client()- c._session.get = MagicMock(- return_value=_mock_response(- ok=False,- status_code=404,- json_data={"error": {"message": "Model not found"}},- )- )- with pytest.raises(OvermindInferenceError, match="404"):- c.models.get("ft-nonexistent")-def test_network_error_raises(self):c = _make_client()c._session.get = MagicMock(side_effect=requests.exceptions.Timeout())diff --git a/overmind/tests/test_code_identity.py b/overmind/tests/test_code_identity.pyindex 00d3eb62..2222442c 100644--- a/overmind/tests/test_code_identity.py+++ b/overmind/tests/test_code_identity.py@@ -28,6 +28,8 @@ from overmind.tracing import (workflow,)+pytestmark = pytest.mark.covers("sdk-wire")+@pytest.fixturedef inmem(monkeypatch):diff --git a/overmind/tests/test_config_toml.py b/overmind/tests/test_config_toml.pyindex f0fe197c..75a491e6 100644--- a/overmind/tests/test_config_toml.py+++ b/overmind/tests/test_config_toml.py@@ -15,7 +15,10 @@ from overmind.config import ()from overmind.utils import convert_json_to_toml+pytestmark = pytest.mark.covers("privacy")+[email protected]("sdk-wire")def test_dump_writes_nested_capability_card(tmp_path: Path):path = tmp_path / "overmind.toml"dump(@@ -65,6 +68,7 @@ def test_dump_writes_nested_capability_card(tmp_path: Path):assert credentials_path(path).stat().st_mode & 0o777 == 0o600[email protected]("sdk-wire")def test_load_accepts_legacy_json_string_card(tmp_path: Path):path = tmp_path / "overmind.toml"card = {"task": "legacy", "trajectory_map": [{"id": "a"}]}@@ -119,6 +123,7 @@ def test_convert_json_to_toml_preserves_card_shape(tmp_path: Path):assert loaded.project_name == tmp_path.name[email protected]("sdk-wire")def test_convert_json_to_toml_keeps_scan_modes_utilities_and_policy(tmp_path: Path):src = tmp_path / "overmind_capabilities.json"src.write_text(@@ -160,6 +165,7 @@ def test_convert_json_to_toml_keeps_scan_modes_utilities_and_policy(tmp_path: Paassert wire["writer"]["capability_card"]["modes"][0]["name"] == "outline"[email protected]("authentication")def test_credentials_only_apply_to_their_project(tmp_path: Path):path = tmp_path / "overmind.toml"dump(Config(api_key="project-a-key", project_id="project-a"), path)diff --git a/overmind/tests/test_connector_cmd.py b/overmind/tests/test_connector_cmd.pyindex 084394f9..b43ae7c3 100644--- a/overmind/tests/test_connector_cmd.py+++ b/overmind/tests/test_connector_cmd.py@@ -11,6 +11,8 @@ from overmind.__main__ import appfrom overmind.config import Config, dumpfrom overmind.connector_cmd import ConnectorAddError, add_connector+pytestmark = pytest.mark.covers("privacy")+class FakeResponse:def __init__(self, payload: dict, status_code: int = 201):@@ -37,6 +39,7 @@ class FakeSession:pass[email protected]("cli-contract")def test_add_connector_rejects_unknown_type():with pytest.raises(ConnectorAddError, match="Unsupported connector type"):add_connector(@@ -48,6 +51,7 @@ def test_add_connector_rejects_unknown_type():)[email protected]("cli-contract")def test_add_connector_surfaces_http_detail():session = FakeSession(FakeResponse({"detail": "Verify failed"}, status_code=400))diff --git a/overmind/tests/test_dataset_cmd.py b/overmind/tests/test_dataset_cmd.pyindex 7054834d..4166dd83 100644--- a/overmind/tests/test_dataset_cmd.py+++ b/overmind/tests/test_dataset_cmd.py@@ -11,6 +11,8 @@ from overmind.__main__ import appfrom overmind.config import Config, dumpfrom overmind.dataset_cmd import DatasetExportError, DatasetUploadError, export_dataset, upload_file+pytestmark = pytest.mark.covers("lineage")+class FakeResponse:def __init__(self, payload: dict, status_code: int = 200, *, headers=None, chunks=None):@@ -68,6 +70,7 @@ def test_original_source_export_verifies_bytes_and_removes_corrupt_download(tmp_assert session.calls[0][2]["allow_redirects"] is False[email protected]("cli-contract")def test_original_source_rejects_cell_selection_and_invalid_identity_before_network(tmp_path):session = ExportSession(FakeResponse({}))for source, cell in (("../escape", None), ("a" * 64, "cell-id")):@@ -84,6 +87,7 @@ def test_original_source_rejects_cell_selection_and_invalid_identity_before_netwassert session.calls == [][email protected]("cli-contract")def test_upload_file_rejects_a_bad_split_before_network(tmp_path: Path):path = tmp_path / "rows.jsonl"path.write_bytes(b"ab")@@ -100,6 +104,7 @@ def test_upload_file_rejects_a_bad_split_before_network(tmp_path: Path):assert session.calls == [][email protected]("cli-contract")def test_upload_file_rejects_ft_intent_before_network(tmp_path: Path):path = tmp_path / "rows.jsonl"path.write_bytes(b"{}\n")@@ -117,6 +122,7 @@ def test_upload_file_rejects_ft_intent_before_network(tmp_path: Path):assert session.calls == [][email protected]("cli-contract")def test_upload_command_prints_uuid_state_and_mcp_follow_up(tmp_path: Path, monkeypatch):file = tmp_path / "rows.jsonl"file.write_text("{}\n")@@ -155,6 +161,7 @@ def test_upload_command_prints_uuid_state_and_mcp_follow_up(tmp_path: Path, monkassert "get_job(kind=dataset_run, id=" in human.output[email protected]("cli-contract")def test_upload_command_passes_split_flags_and_prints_the_eval_dataset(tmp_path: Path, monkeypatch):file = tmp_path / "rows.jsonl"file.write_text("{}\n")@@ -182,14 +189,6 @@ def test_upload_command_passes_split_flags_and_prints_the_eval_dataset(tmp_path:assert "Eval dataset dataset-2." in result.output-def test_upload_command_rejects_removed_flags(tmp_path: Path):- file = tmp_path / "rows.jsonl"- file.write_text("{}\n")- result = CliRunner().invoke(app, ["dataset", "upload", str(file), "--surface", "model"])- assert result.exit_code != 0- assert "no such option" in result.output.lower()--def test_export_dataset_streams_csv_to_explicit_path_with_cell(tmp_path: Path):response = FakeResponse({},@@ -232,6 +231,7 @@ def test_export_dataset_streams_csv_to_explicit_path_with_cell(tmp_path: Path):assert "workshop" not in session.calls[0][1][email protected]("measured-facts")def test_export_dataset_omits_cell_for_active_version(tmp_path: Path):response = FakeResponse({},@@ -256,6 +256,7 @@ def test_export_dataset_omits_cell_for_active_version(tmp_path: Path):assert "fingerprint" not in result[email protected]("privacy")def test_export_dataset_sanitizes_server_filename_and_refuses_overwrite(tmp_path: Path, monkeypatch):monkeypatch.chdir(tmp_path)response = FakeResponse(@@ -285,6 +286,7 @@ def test_export_dataset_sanitizes_server_filename_and_refuses_overwrite(tmp_path)[email protected]("privacy")@pytest.mark.parametrize(("server_filename", "safe_filename"),[@@ -316,6 +318,7 @@ def test_export_dataset_sanitizes_windows_filename_rules(assert Path(safe_filename).read_bytes() == b"{}\n"[email protected]("privacy")def test_export_dataset_redacts_api_key_from_server_errors(tmp_path: Path):response = FakeResponse({"detail": "invalid secret-key"}, 401)@@ -330,6 +333,7 @@ def test_export_dataset_redacts_api_key_from_server_errors(tmp_path: Path):assert not (tmp_path / "rows.jsonl").exists()[email protected]("privacy")def test_export_refuses_redirects_without_forwarding_account_credentials(tmp_path):session = ExportSession(FakeResponse({}, 302, headers={"Location": "https://other.invalid"}))with pytest.raises(DatasetExportError, match="redirect"):@@ -340,6 +344,7 @@ def test_export_refuses_redirects_without_forwarding_account_credentials(tmp_patassert not (tmp_path / "rows.jsonl").exists()[email protected]("cli-contract")def test_export_command_emits_machine_readable_success(tmp_path: Path, monkeypatch):captured: dict = {}@@ -392,6 +397,7 @@ def test_export_command_emits_machine_readable_success(tmp_path: Path, monkeypatassert "no such option" in sha.output.lower()[email protected]("cli-contract")@pytest.mark.parametrize(("config", "args", "message"),[@@ -417,6 +423,7 @@ def test_upload_command_reports_missing_configuration(assert message in str(json.loads(result.output)["error"])[email protected]("state-machines")def test_wait_until_ready_polls_past_busy_states_and_raises_the_dataset_error(monkeypatch):from overmind import dataset_cmddiff --git a/overmind/tests/test_enrich.py b/overmind/tests/test_enrich.pyindex 780877b2..b64c5b38 100644--- a/overmind/tests/test_enrich.py+++ b/overmind/tests/test_enrich.py@@ -6,6 +6,8 @@ import pytestfrom overmind.config import loadfrom overmind.utils import convert_json_to_toml+pytestmark = pytest.mark.covers("agent-code")+def test_convert_enriches_then_stamps_verified(tmp_path: Path):pkg = tmp_path / "app"@@ -244,6 +246,7 @@ def test_incomplete_scan_preserves_previous_snapshot(tmp_path, decision_scan, deassert dest.read_text() == 'project-name = "preserved"\n'[email protected]("identity")def test_detailed_scan_preserves_branches_and_loop_transitions(tmp_path, decision_scan):decision_scan["capabilities"][0]["capability_card"]["trajectory_map"].append({"id": "declared-task",diff --git a/overmind/tests/test_evals.py b/overmind/tests/test_evals.pyindex 8df26291..444e2620 100644--- a/overmind/tests/test_evals.py+++ b/overmind/tests/test_evals.py@@ -17,6 +17,8 @@ from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanEfrom overmind import attrsfrom overmind.evals import checkpoint, end_conversation, eval_context, expect, intent+pytestmark = pytest.mark.covers("sdk-wire")+@pytest.fixturedef inmem():diff --git a/overmind/tests/test_evidence_contract.py b/overmind/tests/test_evidence_contract.pyindex 09f6a68e..836850b3 100644--- a/overmind/tests/test_evidence_contract.py+++ b/overmind/tests/test_evidence_contract.py@@ -20,6 +20,8 @@ import overmind.tracing as tracingfrom overmind import attrsfrom overmind.tracing import SpanType, deliver, entry_point, observe, retrieval, start_span, tool+pytestmark = pytest.mark.covers("sdk-wire")+@pytest.fixturedef exporter(monkeypatch):diff --git a/overmind/tests/test_extras_isolation.py b/overmind/tests/test_extras_isolation.pyindex d3f19cdd..52202688 100644--- a/overmind/tests/test_extras_isolation.py+++ b/overmind/tests/test_extras_isolation.py@@ -10,6 +10,10 @@ import subprocessimport sysimport textwrap+import pytest++pytestmark = pytest.mark.covers("sdk-install")+_SCRIPT = textwrap.dedent("""import sysdiff --git a/overmind/tests/test_genai_tracing.py b/overmind/tests/test_genai_tracing.pyindex af0a76b6..0bff5215 100644--- a/overmind/tests/test_genai_tracing.py+++ b/overmind/tests/test_genai_tracing.py@@ -32,6 +32,8 @@ from overmind.tracing import (_span_processor_on_start,)+pytestmark = pytest.mark.covers("sdk-wire")+@pytest.fixturedef inmem():@@ -130,23 +132,6 @@ def test_identity_stamped_on_spans(inmem):assert span.attributes[attrs.PROJECT_ID] == "proj-uuid-9"-def test_tool_decorator_stamps_metadata(inmem):- provider, exporter = inmem- from overmind import tool-- @tool()- def search_kb(query, limit=5):- return {"hits": 1}-- search_kb("refund policy", limit=3)- provider.force_flush()-- span = exporter.get_finished_spans()[-1]- assert span.attributes[attrs.SPAN_TYPE] == "tool_call"- assert span.attributes[attrs.TOOL_NAME] == "search_kb"- assert set(span.attributes[attrs.TOOL_ARG_KEYS]) == {"query", "limit"}--def test_tool_decorator_records_error(inmem):provider, exporter = inmemfrom overmind import tool@@ -162,25 +147,3 @@ def test_tool_decorator_records_error(inmem):span = exporter.get_finished_spans()[-1]assert span.attributes[attrs.TOOL_ERROR] == "ValueError"assert span.attributes[attrs.STATUS] == "failed"---def test_nested_tool_under_workflow_keeps_parent(inmem):- provider, exporter = inmem- from overmind import tool, workflow-- @tool()- def inner_tool(x):- return x-- @workflow()- def outer():- return inner_tool(1)-- outer()- provider.force_flush()-- spans = {s.name.rsplit(".", 1)[-1]: s for s in exporter.get_finished_spans()}- parent = spans["outer"]- child = spans["inner_tool"]- assert child.parent is not None- assert child.parent.span_id == parent.context.span_iddiff --git a/overmind/tests/test_init.py b/overmind/tests/test_init.pyindex 6c9247a3..a7d8ad2c 100644--- a/overmind/tests/test_init.py+++ b/overmind/tests/test_init.py@@ -10,6 +10,8 @@ from overmind.__main__ import appfrom overmind.config import Config, dumpfrom overmind.init_cmd import claude_config_path+pytestmark = pytest.mark.covers("mcp-surface")+runner = CliRunner()SKILL_SOURCE = Path(__file__).resolve().parents[1] / "skills" / "overmind"SURFACE_SKILLS = (@@ -86,15 +88,6 @@ def test_init_delivers_current_onboarding_workflow(tmp_path, monkeypatch, ide, sassert (installed / "agents/openai.yaml").read_bytes() == (source / "agents/openai.yaml").read_bytes()-def test_init_writes_cursor_mcp_json(tmp_path, monkeypatch):- monkeypatch.chdir(tmp_path)- _init(tmp_path, "cursor")- cfg = json.loads((tmp_path / ".cursor" / "mcp.json").read_text())- assert cfg["mcpServers"]["overmind"] == {"url": "http://localhost:8000/api/mcp/"}- assert (tmp_path / ".agents" / "skills" / "overmind" / "SKILL.md").is_file()- assert (tmp_path / ".agents" / "skills" / "overmind" / "references" / "setup.md").is_file()--def test_cursor_init_replaces_previous_skill_installs(tmp_path, monkeypatch):monkeypatch.chdir(tmp_path)legacy = tmp_path / ".cursor" / "skills" / "overmind"@@ -208,6 +201,7 @@ def test_init_claude_preserves_other_config_and_tracked_mcp_json(tmp_path, monkeassert (tmp_path / ".mcp.json").read_text() == tracked[email protected]("privacy")def test_init_keeps_bootstrap_key_out_of_local_files(tmp_path, monkeypatch):monkeypatch.chdir(tmp_path)monkeypatch.setenv("OVERMIND_API_KEY", "secret")@@ -276,6 +270,7 @@ def test_init_codex_replaces_own_section_and_preserves_other_config(tmp_path, moassert stat.S_IMODE(config_path.stat().st_mode) == 0o600[email protected]("privacy")def test_init_does_not_copy_saved_project_key_into_mcp(tmp_path, monkeypatch):monkeypatch.chdir(tmp_path)monkeypatch.delenv("OVERMIND_API_URL", raising=False)@@ -295,6 +290,7 @@ def test_init_does_not_copy_saved_project_key_into_mcp(tmp_path, monkeypatch):assert _claude_overmind(tmp_path) == {"type": "http", "url": "http://localhost:8000/api/mcp/"}[email protected]("privacy")def test_init_does_not_copy_legacy_inline_key_into_mcp(tmp_path, monkeypatch):monkeypatch.chdir(tmp_path)(tmp_path / "overmind.toml").write_text(@@ -312,6 +308,7 @@ def test_init_does_not_copy_legacy_inline_key_into_mcp(tmp_path, monkeypatch):assert not (tmp_path / ".overmind" / "credentials.toml").exists()[email protected]("privacy")def test_init_can_prepare_a_tracked_unauthenticated_mcp_config(tmp_path, monkeypatch):monkeypatch.chdir(tmp_path)subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)diff --git a/overmind/tests/test_langgraph_binder.py b/overmind/tests/test_langgraph_binder.pyindex df12e502..3322105f 100644--- a/overmind/tests/test_langgraph_binder.py+++ b/overmind/tests/test_langgraph_binder.py@@ -21,6 +21,8 @@ from overmind import attrsfrom overmind.integrations.langgraph import bind, slugfrom overmind.tracing import _span_processor_on_start, start_span+pytestmark = pytest.mark.covers("sdk-wire")+@pytest.fixturedef exporter(monkeypatch):diff --git a/overmind/tests/test_layer_cmd.py b/overmind/tests/test_layer_cmd.pyindex 936d6bc2..19e3309a 100644--- a/overmind/tests/test_layer_cmd.py+++ b/overmind/tests/test_layer_cmd.py@@ -17,6 +17,8 @@ from overmind.layer_cmd import (run_finetune,)+pytestmark = pytest.mark.covers("cli-contract")+class Response:def __init__(self, payload, status_code=200):diff --git a/overmind/tests/test_lifecycle.py b/overmind/tests/test_lifecycle.pyindex 67532703..33ed7212 100644--- a/overmind/tests/test_lifecycle.py+++ b/overmind/tests/test_lifecycle.py@@ -19,6 +19,8 @@ from overmind import attrsfrom overmind.lifecycle import RunHandle, runfrom overmind.tracing import _span_processor_on_start, start_span, task+pytestmark = pytest.mark.covers("sdk-wire")+@pytest.fixturedef exporter(monkeypatch):@@ -180,6 +182,7 @@ def test_exception_marks_the_run_failed_and_reraises(exporter):assert root.attributes[attrs.ERROR_TYPE] == "ValueError"[email protected]("sdk-install")def test_run_is_a_noop_when_uninitialised(monkeypatch):monkeypatch.setattr(tracing, "_initialized", False)@@ -266,6 +269,7 @@ def test_run_decorator_callable_failure_degrades_to_none(exporter):assert "conversation.id" not in _by_name(exporter, "r").attributes[email protected]("sdk-install")def test_run_decorator_is_noop_when_uninitialised(monkeypatch):monkeypatch.setattr(tracing, "_initialized", False)diff --git a/overmind/tests/test_model_cmd.py b/overmind/tests/test_model_cmd.pyindex 2dabab61..65a719bd 100644--- a/overmind/tests/test_model_cmd.py+++ b/overmind/tests/test_model_cmd.py@@ -1,6 +1,5 @@from __future__ import annotations-import jsonimport reimport threadingfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer@@ -8,12 +7,11 @@ from pathlib import Pathimport pytestimport requests-from typer.testing import CliRunner-from overmind.__main__ import app-from overmind.config import Config, dumpfrom overmind.model_cmd import CheckpointDownloadError, download_checkpoint+pytestmark = pytest.mark.covers("privacy")+class FakeResponse:def __init__(self, payload=None, status_code: int = 200, *, chunks=None):@@ -127,6 +125,7 @@ def test_download_checkpoint_sanitizes_windows_reserved_filename(tmp_path: Path,assert Path("_CON.zip").read_bytes() == b"weights"[email protected]("lineage")def test_download_checkpoint_removes_partial_file_after_stream_error(tmp_path: Path):class FailingResponse(FakeResponse):def iter_content(self, chunk_size):@@ -152,6 +151,7 @@ def test_download_checkpoint_removes_partial_file_after_stream_error(tmp_path: Passert not output.exists()[email protected]("lineage")@pytest.mark.parametrize(("expected_size", "chunks"),[(10, [b"short"]), (3, [b"longer"])],@@ -222,34 +222,6 @@ def test_download_checkpoint_closes_owned_session(monkeypatch, tmp_path: Path):assert session.closed is True-def test_download_checkpoint_command_uses_config_and_emits_safe_json(tmp_path: Path, monkeypatch):- config_path = tmp_path / "overmind.toml"- dump(- Config(- api_key="toml-key",- base_url="https://configured.example",- project_id="11111111-1111-1111-1111-111111111111",- ),- config_path,- )- result_data = {- "path": str(tmp_path / "checkpoint.zip"),- "deployment_id": "deployment-1",- "filename": "checkpoint.zip",- "expected_size": 4,- "bytes_written": 4,- }- monkeypatch.setattr("overmind.model_cmd.download_checkpoint", lambda *args, **kwargs: result_data)-- result = CliRunner().invoke(- app,- ["model", "download-checkpoint", "deployment-1", "--path", str(config_path), "--json"],- )-- assert result.exit_code == 0, result.output- assert json.loads(result.output) == result_data--def _serve(handler):server = ThreadingHTTPServer(("127.0.0.1", 0), handler)threading.Thread(target=server.serve_forever, daemon=True).start()diff --git a/overmind/tests/test_observe_capture.py b/overmind/tests/test_observe_capture.pyindex 8e4756c2..8858bc80 100644--- a/overmind/tests/test_observe_capture.py+++ b/overmind/tests/test_observe_capture.py@@ -16,6 +16,8 @@ import overmind.tracing as tracingfrom overmind import attrsfrom overmind.tracing import SpanType, normalize_messages, observe, start_span, tool+pytestmark = pytest.mark.covers("sdk-wire")+@pytest.fixturedef exporter(monkeypatch):@@ -31,6 +33,7 @@ def _only_span(exporter):return span[email protected]("privacy")def test_capture_auto_records_scrubbed_inputs_and_outputs(exporter):@observe("op")def op(query, api_key):@@ -42,6 +45,7 @@ def test_capture_auto_records_scrubbed_inputs_and_outputs(exporter):assert json.loads(span.attributes["outputs"]) == {"hits": ["refunds"]}[email protected]("privacy")def test_capture_none_records_no_payloads(exporter):@observe("op", capture="none")def op(secret):diff --git a/overmind/tests/test_optimizer.py b/overmind/tests/test_optimizer.pyindex 4d8aea35..bf7ac802 100644--- a/overmind/tests/test_optimizer.py+++ b/overmind/tests/test_optimizer.py@@ -9,54 +9,10 @@ import pytestfrom overmind.optimizer import OptimiseLoopfrom overmind.optimizer_api import (- TOKENS,- _new_traceparent,- _render_command,_run_datapoint,)--def test_traceparent_shape():- header, trace_id = _new_traceparent()- assert header == f"00-{trace_id}-{header.split('-')[2]}-01"- assert len(trace_id) == 32 and int(trace_id, 16) >= 0---def test_render_command_substitutes_tokens():- rendered = _render_command(- "echo __DATAPOINT_INPUT__ __CANDIDATE_ID__ __DATAPOINT_INDEX__",- experiment_id="e1",- capability_id="c1",- project_id="p1",- candidate_id="cand",- iteration_id="it",- datapoint_index=3,- trace_type="candidate",- original_trace_id="",- datapoint_input={"q": 1},- )- assert TOKENS["DATAPOINT_INPUT"] not in rendered- assert "{'q': 1}" in rendered- assert "cand" in rendered- assert rendered.endswith("3") or " 3" in rendered---def test_run_datapoint_success_round_trip(tmp_path):- result = _run_datapoint(- template="echo hi",- experiment_id="e",- capability_id="c",- project_id="p",- candidate_id="cand",- iteration_id="it",- datapoint_index=0,- datapoint_input="x",- cwd=str(tmp_path),- timeout=10,- )- assert result["success"] is True- assert result["output"].strip() == "hi"- assert len(result["trace_id"]) == 32+pytestmark = pytest.mark.covers("state-machines")def test_run_datapoint_failure_reports_error(tmp_path):@@ -76,6 +32,7 @@ def test_run_datapoint_failure_reports_error(tmp_path):assert "boom" in (result.get("error") or "")[email protected]("lineage")def test_export_dataset_reuses_a_cache_whose_hash_matches_the_pin(tmp_path):from overmind.optimizer_api import OptimizerAPI@@ -90,23 +47,7 @@ def test_export_dataset_reuses_a_cache_whose_hash_matches_the_pin(tmp_path):api._session.get.assert_not_called()-def test_export_dataset_fetches_the_pinned_checkpoint_and_keeps_its_hash(tmp_path):- from overmind.optimizer_api import OptimizerAPI-- api = OptimizerAPI("http://api", "k")- api._session = MagicMock()- api._session.get.return_value.iter_content.return_value = [b'{"input": 1}\n']- api._session.get.return_value.headers = {"X-Overmind-Fingerprint": "abc"}- cache = tmp_path / "datasets"- path = api.export_dataset("ds-1", "ver-9", cache)- assert path == cache / "ver-9.jsonl"- assert path.read_text() == '{"input": 1}\n'- assert (cache / "ver-9.hash").read_text() == "abc"- call = api._session.get.call_args- assert call.args[0] == "http://api/api/datasets/ds-1/export/"- assert call.kwargs["params"] == {"fmt": "jsonl", "cell": "ver-9"}--[email protected]("lineage")def test_export_dataset_refetches_when_the_hash_is_stale_or_missing(tmp_path):from overmind.optimizer_api import OptimizerAPI@@ -126,6 +67,7 @@ def test_export_dataset_refetches_when_the_hash_is_stale_or_missing(tmp_path):assert api._session.get.call_count == 2[email protected]("lineage")def test_export_dataset_needs_a_used_version(tmp_path):from overmind.optimizer_api import OptimizerAPI@@ -172,59 +114,3 @@ def _loop_with_experiment(tmp_path, exp: dict) -> OptimiseLoop:dataset_path=dataset,state_path=state_path,)---def test_next_action_completes_on_plateau(tmp_path):- loop = _loop_with_experiment(- tmp_path,- {- "id": "e1",- "status": "evaluated_candidate_outputs",- "command_template": "run.sh",- "iterations": [{"order": 0}, {"order": 1}, {"order": 2}],- "current_iteration": 2,- "num_iterations": 5,- "stalled_iterations": 3,- "max_iterations_without_improvement": 3,- "scores": {"baseline": 70.0, "best": 70.5},- },- )- action = loop.next_action()- assert action["action"] == "COMPLETE"- assert "plateau" in action["reason"]---def test_next_action_keeps_iterating_below_plateau(tmp_path):- loop = _loop_with_experiment(- tmp_path,- {- "id": "e1",- "status": "evaluated_candidate_outputs",- "command_template": "run.sh",- "iterations": [{"order": 0}, {"order": 1}],- "current_iteration": 1,- "num_iterations": 5,- "stalled_iterations": 1,- "max_iterations_without_improvement": 3,- "scores": {"baseline": 70.0, "best": 80.0},- },- )- action = loop.next_action()- assert action["action"] == "WRITE_CANDIDATES"---def test_add_candidate_diff_queues_locally(tmp_path):- api = MagicMock()- dataset = tmp_path / "ds.jsonl"- dataset.write_text("{}\n")- loop = OptimiseLoop(- api,- "e1",- repo_cwd=str(tmp_path),- dataset_path=dataset,- state_path=tmp_path / "state.json",- )- result = loop.add_candidate_diff("diff --git a/x b/x\n")- assert result["pending"] == 1- state = json.loads((tmp_path / "state.json").read_text())- assert len(state["pending_diffs"]) == 1diff --git a/overmind/tests/test_orphan_suppression.py b/overmind/tests/test_orphan_suppression.pyindex 18726533..21763d41 100644--- a/overmind/tests/test_orphan_suppression.py+++ b/overmind/tests/test_orphan_suppression.py@@ -22,6 +22,8 @@ from opentelemetry.trace import NonRecordingSpan, SpanContext, TraceFlagsimport overmind.tracing as tracingfrom overmind.tracing import _span_processor_on_start, observe, start_span, task+pytestmark = pytest.mark.covers("sdk-wire")+@pytest.fixturedef exporter(monkeypatch):diff --git a/overmind/tests/test_plugin_manifests.py b/overmind/tests/test_plugin_manifests.pyindex 8cc17db7..0198b11f 100644--- a/overmind/tests/test_plugin_manifests.py+++ b/overmind/tests/test_plugin_manifests.py@@ -5,6 +5,8 @@ import pytestfrom overmind.skills_db import SKILLS_VERSION+pytestmark = pytest.mark.covers("mcp-surface")+SDK_ROOT = Path(__file__).resolve().parents[1]diff --git a/overmind/tests/test_repository_snapshot.py b/overmind/tests/test_repository_snapshot.pyindex 91fcdfa5..a19e5362 100644--- a/overmind/tests/test_repository_snapshot.py+++ b/overmind/tests/test_repository_snapshot.py@@ -2,11 +2,13 @@ import jsonimport subprocessimport pytest+from overmind.config import Config, dump, loadfrom overmind.repository_snapshot import begin_repository_scan, capture_repository_snapshot, finish_repository_scan-from overmind.utils import convert_json_to_toml+pytestmark = pytest.mark.covers("sdk-wire")+def git(root, *args):return subprocess.run(["git", "-C", str(root), *args], check=True, capture_output=True, text=True).stdout.strip()@@ -23,6 +25,7 @@ def repo(tmp_path):return tmp_path[email protected]("privacy")@pytest.mark.parametrize("remote", ["https://user:[email protected]/acme/agent.git?token=hidden", "[email protected]:acme/agent.git"])diff --git a/overmind/tests/test_resumable_transfer.py b/overmind/tests/test_resumable_transfer.pyindex d0d25eab..1619697b 100644--- a/overmind/tests/test_resumable_transfer.py+++ b/overmind/tests/test_resumable_transfer.py@@ -10,6 +10,8 @@ from overmind.__main__ import appfrom overmind.dataset_cmd import upload_filefrom overmind.transfer_connection import TransferError+pytestmark = pytest.mark.covers("work-once")+class Response:def __init__(self, data, status=200):@@ -260,6 +262,7 @@ def test_recovered_upload_does_not_present_saved_landing_state_as_current(tmp_paassert server.publications == 1[email protected]("privacy")@pytest.mark.parametrize("code", ["file_too_large", ["file_too_large"]])def test_document_limit_has_actionable_safe_error_without_a_transfer(tmp_path, code):path = tmp_path / "large.pdf"@@ -282,6 +285,7 @@ def test_document_limit_has_actionable_safe_error_without_a_transfer(tmp_path, cassert server.receipt is None and server.publications == 0[email protected]("privacy")def test_readiness_reports_denied_transport_without_mutation_or_secrets(monkeypatch):server = TransferServer()@@ -364,6 +368,7 @@ def test_readiness_preserves_auth_permission_and_redirect_failures(monkeypatch,assert "secret-key" not in result.output[email protected]("authentication")def test_global_setup_uses_one_connection_without_pinning_a_project(tmp_path, monkeypatch):from pathlib import Pathdiff --git a/overmind/tests/test_sdk.py b/overmind/tests/test_sdk.pyindex f840b6b9..215c5b8c 100644--- a/overmind/tests/test_sdk.py+++ b/overmind/tests/test_sdk.py@@ -3,6 +3,8 @@ from unittest.mock import MagicMock, patchimport pytest+pytestmark = pytest.mark.covers("sdk-install")+@pytest.fixture(autouse=True)def reset_sdk_state():@@ -48,37 +50,6 @@ def mock_opentelemetry():}-def test_sdk_init_configures_tracing(mock_opentelemetry):- from overmind import tracing-- with (- patch.object(tracing, "FastAPIInstrumentor", create=True) as mock_fastapi,- patch.object(tracing, "OpenAIInstrumentor", create=True) as mock_openai,- patch.dict(- "sys.modules",- {- "opentelemetry.instrumentation.fastapi": MagicMock(FastAPIInstrumentor=mock_fastapi),- "opentelemetry.instrumentation.openai": MagicMock(OpenAIInstrumentor=mock_openai),- },- ),- ):- # Mock the dynamic imports- tracing.init(- overmind_api_key="test_key",- overmind_base_url="http://localhost:4318",- service_name="test-service",- environment="testing",- )-- # Verify Exporter configuration- mock_opentelemetry["exporter"].assert_called_with(- endpoint="http://localhost:4318/api/v1/traces", headers={"X-Api-Key": "test_key"}- )-- # Verify tracer provider was set- mock_opentelemetry["trace"].set_tracer_provider.assert_called_once()--def test_sdk_init_only_once():from overmind import tracing@@ -130,6 +101,7 @@ def test_init_without_key_raises_in_strict_mode(no_api_key, monkeypatch):tracing.init()[email protected]("authentication")def test_init_uses_synced_local_credential(no_api_key, mock_opentelemetry, tmp_path, monkeypatch):from overmind import tracingfrom overmind.config import Config, dump@@ -183,20 +155,6 @@ def test_get_tracer_before_init():tracing.get_tracer()-def test_set_user(mock_opentelemetry):- from overmind import tracing-- mock_span = MagicMock()- mock_span.is_recording.return_value = True- mock_opentelemetry["trace"].get_current_span.return_value = mock_span-- tracing.init(overmind_api_key="test_key", overmind_base_url="http://localhost:4318")- tracing.set_user(user_id="user123", email="[email protected]")-- mock_span.set_attribute.assert_any_call("user.id", "user123")- mock_span.set_attribute.assert_any_call("user.email", "[email protected]")--def test_set_tag(mock_opentelemetry):from overmind import tracingdiff --git a/overmind/tests/test_spans.py b/overmind/tests/test_spans.pyindex cbb98e76..dd7fad45 100644--- a/overmind/tests/test_spans.py+++ b/overmind/tests/test_spans.py@@ -10,8 +10,11 @@ from importlib.metadata import versionfrom pathlib import Pathfrom threading import Thread+import pytestfrom opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest+pytestmark = pytest.mark.covers("sdk-wire")+SCRIPT = """import jsonimport sysdiff --git a/overmind/tests/test_stamping_invariants.py b/overmind/tests/test_stamping_invariants.pyindex c8b3a2f2..85a9a0a7 100644--- a/overmind/tests/test_stamping_invariants.py+++ b/overmind/tests/test_stamping_invariants.py@@ -45,6 +45,8 @@ from overmind.tracing import (task,)+pytestmark = pytest.mark.covers("sdk-wire")+@pytest.fixturedef exporter(monkeypatch):diff --git a/overmind/tests/test_sync_ensure_project.py b/overmind/tests/test_sync_ensure_project.pyindex f748fb01..41d280af 100644--- a/overmind/tests/test_sync_ensure_project.py+++ b/overmind/tests/test_sync_ensure_project.py@@ -14,13 +14,14 @@ from overmind.sync import (SyncError,_api_key_scope,_slugify,- ensure_mcp_project_key,ensure_project_id,resolve_api_key,run_down,run_up,)+pytestmark = pytest.mark.covers("authentication")+def test_slugify_strips_and_caps():assert _slugify(" Hello World!! ") == "hello-world"@@ -36,6 +37,7 @@ def test_ensure_project_id_noop_when_present(tmp_path: Path):assert created is False[email protected]("cli-contract")def test_ensure_project_id_falls_back_to_directory_name(tmp_path: Path):path = tmp_path / "overmind.toml"cfg = Config(@@ -52,6 +54,7 @@ def test_ensure_project_id_falls_back_to_directory_name(tmp_path: Path):assert load(path).project_name == tmp_path.name[email protected]("cli-contract")def test_ensure_project_id_surfaces_project_scoped_refusal(tmp_path: Path):path = tmp_path / "overmind.toml"cfg = Config(api_key="k", project_id="")@@ -82,48 +85,7 @@ def test_api_key_scope_reads_current_endpoint():assert _api_key_scope("acct", "https://api.example") == "account"-def test_ensure_mcp_project_key_swaps_account_scoped_key(tmp_path: Path):- path = tmp_path / "overmind.toml"- project_id = "11111111-1111-1111-1111-111111111111"- cfg = Config(api_key="acct", project_id=project_id, project_name="demo")- dump(cfg, path)-- with (- patch("overmind.sync.mint_project_api_key", return_value="ovr_project_key") as mint,- ):- out, key = ensure_mcp_project_key(- cfg,- path,- "acct",- "https://api.example",- key_scope="account",- )-- mint.assert_called_once_with("https://api.example", "acct", project_id)- assert key == "ovr_project_key"- assert out.api_key == "ovr_project_key"- assert load(path).api_key == "ovr_project_key"- assert "api-key" not in path.read_text()---def test_ensure_mcp_project_key_noop_for_project_scoped_key(tmp_path: Path):- path = tmp_path / "overmind.toml"- cfg = Config(api_key="already-project", project_id="11111111-1111-1111-1111-111111111111")- dump(cfg, path)-- out, key = ensure_mcp_project_key(- cfg,- path,- "already-project",- "https://api.example",- key_scope="project",- )-- assert key == "already-project"- assert out.api_key == "already-project"- assert load(path).api_key == "already-project"--[email protected]("privacy")def test_sync_saves_project_key_without_touching_oauth_mcp_configs(tmp_path: Path, monkeypatch, capsys):path = tmp_path / "overmind.toml"project_id = "11111111-1111-1111-1111-111111111111"@@ -162,6 +124,7 @@ def test_saved_project_key_wins_over_stale_bootstrap_environment(tmp_path: Path,assert resolve_api_key("replacement", load(path)) == "replacement"[email protected]("privacy")@pytest.mark.parametrize("sync", [run_up, run_down])@pytest.mark.parametrize("explicit_key", ["", "saved-project-key"])def test_sync_rejects_saved_key_on_another_endpoint(tmp_path, monkeypatch, sync, explicit_key):@@ -208,6 +171,7 @@ def test_setup_sync_reuses_saved_project_key_without_minting_another(tmp_path: Pmint.assert_called_once_with("https://api.example", "bootstrap", project_id)[email protected]("cli-contract")def test_sync_does_not_add_overmind_to_uninitialized_ide_config(tmp_path: Path):path = tmp_path / "overmind.toml"project_id = "11111111-1111-1111-1111-111111111111"diff --git a/overmind/tests/test_task.py b/overmind/tests/test_task.pyindex d59f309d..d94825f3 100644--- a/overmind/tests/test_task.py+++ b/overmind/tests/test_task.py@@ -16,6 +16,8 @@ import overmind.tracing as tracingfrom overmind import attrsfrom overmind.tracing import _span_processor_on_start, start_span, task+pytestmark = pytest.mark.covers("sdk-wire")+@pytest.fixturedef exporter(monkeypatch):diff --git a/overmind/tests/test_tracer.py b/overmind/tests/test_tracer.pyindex 19233aa4..050b3260 100644--- a/overmind/tests/test_tracer.py+++ b/overmind/tests/test_tracer.py@@ -9,6 +9,8 @@ from opentelemetry.trace import StatusCodefrom overmind.tracing import observe+pytestmark = pytest.mark.covers("sdk-wire")+@pytest.fixture(autouse=True)def reset_sdk_state():@@ -141,26 +143,3 @@ def test_observe_skips_cls_in_classmethod(mock_tracer):# Verify cls is not in the captured inputscaptured_inputs = str(input_calls[0])assert "cls" not in captured_inputs or '"cls"' not in captured_inputs---def test_observe_async_class_method(mock_tracer):- import asyncio-- mock_tracer_obj, _ = mock_tracer-- with patch("overmind.tracing.get_tracer", return_value=mock_tracer_obj):-- class AsyncTestClass:- def __init__(self):- self.value = 15-- @observe()- async def async_method(self, x: int):- await asyncio.sleep(0.01)- return self.value * x-- obj = AsyncTestClass()- result = asyncio.run(obj.async_method(2))-- assert result == 30- mock_tracer_obj.start_as_current_span.assert_called_once()diff --git a/overmind/tests/test_tracing_lifecycle.py b/overmind/tests/test_tracing_lifecycle.pyindex 870cba4d..85d22128 100644--- a/overmind/tests/test_tracing_lifecycle.py+++ b/overmind/tests/test_tracing_lifecycle.py@@ -26,6 +26,8 @@ from overmind.tracing import (set_workflow_name,)+pytestmark = pytest.mark.covers("sdk-wire")+def test_api_settings_reuse_synced_project_credential(tmp_path, monkeypatch):monkeypatch.chdir(tmp_path)@@ -110,16 +112,3 @@ class TestForceFlushTraces:with patch("overmind.tracing.trace.get_tracer_provider", return_value=provider):force_flush_traces(timeout_millis=750)provider.force_flush.assert_called_once_with(timeout_millis=750)---class TestInitDebug:- def test_debug_logs_setup_summary(self, caplog):- import overmind.tracing as tr-- # conftest already initialised the SDK, so this exercises the re-init path.- with caplog.at_level("INFO", logger="overmind"):- assert tr.init(debug=True) is True-- (record,) = (r for r in caplog.records if r.message.startswith("Overmind debug:"))- for fragment in ("endpoint=", "capability_id=", "providers=", "export=", "export_orphan_spans="):- assert fragment in record.messagediff --git a/overmind/tests/test_tracing_providers.py b/overmind/tests/test_tracing_providers.pyindex dfc6be8b..e0630698 100644--- a/overmind/tests/test_tracing_providers.py+++ b/overmind/tests/test_tracing_providers.py@@ -16,6 +16,8 @@ import pytestfrom overmind import tracing+pytestmark = pytest.mark.covers("sdk-install")+@pytest.fixture(autouse=True)def _reset_provider_state():@@ -31,19 +33,6 @@ def _reset_provider_state():class TestEnableProvider:"""Direct tests for the shared :func:`_enable_provider` helper."""- def test_instruments_when_module_available(self):- instrumentor_cls = MagicMock()- module = MagicMock(DemoInstrumentor=instrumentor_cls)- with (- patch("importlib.util.find_spec", return_value=object()),- patch("importlib.import_module", return_value=module),- ):- tracing._enable_provider("demo", "demo_module", "instr.demo", "DemoInstrumentor")-- instrumentor_cls.assert_called_once_with()- instrumentor_cls.return_value.instrument.assert_called_once_with()- assert "demo" in tracing._providers-def test_is_idempotent_on_repeated_calls(self):instrumentor_cls = MagicMock()module = MagicMock(DemoInstrumentor=instrumentor_cls)@@ -67,16 +56,20 @@ class TestEnableProvider:def test_raises_when_module_missing_in_strict_mode(self):tracing._strict_mode = True- with patch("importlib.util.find_spec", return_value=None):- with pytest.raises(ImportError, match="not installed"):- tracing._enable_provider("demo", "demo_module", "instr.demo", "DemoInstrumentor")+ with (+ patch("importlib.util.find_spec", return_value=None),+ pytest.raises(ImportError, match="not installed"),+ ):+ tracing._enable_provider("demo", "demo_module", "instr.demo", "DemoInstrumentor")def test_dotted_module_name_collapsed_for_install_hint(self):"""``google.genai`` shouldn't appear in `pip install google.genai`."""tracing._strict_mode = True- with patch("importlib.util.find_spec", return_value=None):- with pytest.raises(ImportError, match=r"pip install google-genai"):- tracing._enable_provider("google", "google.genai", "instr.google", "GoogleInstrumentor")+ with (+ patch("importlib.util.find_spec", return_value=None),+ pytest.raises(ImportError, match=r"pip install google-genai"),+ ):+ tracing._enable_provider("google", "google.genai", "instr.google", "GoogleInstrumentor")def test_missing_extra_instrumentor_warns_with_extra_hint(self, caplog):"""Target library installed but the extra-shipped instrumentor absent:@@ -92,9 +85,11 @@ class TestEnableProvider:def test_missing_extra_instrumentor_raises_in_strict_mode(self):tracing._strict_mode = Truegate, instrumentation, cls = tracing._PROVIDER_MODULES["openai"]- with patch("importlib.util.find_spec", side_effect=lambda mod: object() if mod == gate else None):- with pytest.raises(ImportError, match=r"overmind\[tracing\]"):- tracing._enable_provider("openai", gate, instrumentation, cls)+ with (+ patch("importlib.util.find_spec", side_effect=lambda mod: object() if mod == gate else None),+ pytest.raises(ImportError, match=r"overmind\[tracing\]"),+ ):+ tracing._enable_provider("openai", gate, instrumentation, cls)def test_missing_namespace_package_treated_as_absent(self):"""find_spec raises ModuleNotFoundError when a dotted parent package@@ -112,38 +107,12 @@ class TestEnableProvider:assert "langchain" not in tracing._providers- def test_langchain_provider_registered(self):- gate, instrumentation, cls = tracing._PROVIDER_MODULES["langchain"]- assert gate == "langchain_core"- assert instrumentation == "openinference.instrumentation.langchain"- assert cls == "LangChainInstrumentor"-class TestEnableTracingDispatcher:- def test_empty_list_enables_all_known_providers(self):- with patch.object(tracing, "_enable_provider") as enable:- tracing.enable_tracing([])-- enabled = [call.args[0] for call in enable.call_args_list]- assert enabled == list(tracing._PROVIDER_MODULES)-- def test_none_short_circuits(self):- with patch.object(tracing, "_enable_provider") as enable:- tracing.enable_tracing(None)-- enable.assert_not_called()-def test_unknown_provider_does_not_crash(self, caplog):tracing.enable_tracing(["definitely-not-real"])assert any("Unknown tracing provider" in rec.message for rec in caplog.records)- def test_routes_named_providers_through_helper(self):- with patch.object(tracing, "_enable_provider") as enable:- tracing.enable_tracing(["openai", "anthropic"])-- enabled = [call.args[0] for call in enable.call_args_list]- assert enabled == ["openai", "anthropic"]-class TestAutoProviders:"""``providers="auto"`` — detect installed target libraries and enable@@ -165,23 +134,6 @@ class TestAutoProviders:assert [call.args[0] for call in enable.call_args_list] == ["openai"]- def test_logs_resolved_list_at_info(self, caplog):- detected = {- "anthropic",- "opentelemetry.instrumentation.anthropic",- "openai",- "opentelemetry.instrumentation.openai",- }- with (- caplog.at_level("INFO"),- patch.object(tracing, "_module_installed", side_effect=lambda m: m in detected),- patch.object(tracing, "_enable_provider"),- ):- tracing.enable_tracing("auto")-- (record,) = (r for r in caplog.records if 'providers="auto"' in r.message)- assert "openai, anthropic" in record.message-def test_nothing_installed_resolves_to_none(self, caplog):with (caplog.at_level("INFO"),diff --git a/overmind/tests/test_tracing_serialize.py b/overmind/tests/test_tracing_serialize.pyindex e34372f0..362e8037 100644--- a/overmind/tests/test_tracing_serialize.py+++ b/overmind/tests/test_tracing_serialize.py@@ -17,7 +17,11 @@ import dataclassesimport jsonfrom pathlib import PurePath-from overmind.tracing import _coerce_to_otel_attribute, _json_dumps, _normalize_for_json+import pytest++from overmind.tracing import _coerce_to_otel_attribute, _normalize_for_json++pytestmark = pytest.mark.covers("sdk-wire")@dataclasses.dataclass@@ -73,9 +77,6 @@ class TestNormalizeForJson:assert isinstance(result, list)assert sorted(result) == [1, 2, 3]- def test_frozenset_normalises_to_list(self):- assert sorted(_normalize_for_json(frozenset({"a", "b"}))) == ["a", "b"]-def test_tuple_normalises_to_list(self):assert _normalize_for_json((1, "x", True)) == [1, "x", True]@@ -93,14 +94,7 @@ class TestNormalizeForJson:assert _normalize_for_json({1: "a"}) == {"1": "a"}-class TestJsonDumps:- def test_round_trip_via_json_loads(self):- raw = _json_dumps({"point": _Point(1, 2), "tags": {"alpha"}})- loaded = json.loads(raw)- assert loaded["point"] == {"x": 1, "y": 2}- assert loaded["tags"] == ["alpha"]--[email protected]("privacy")class TestScrubbing:"""Secrets and binary blobs are redacted during serialisation; text isnever truncated."""diff --git a/overmind/tests/test_transfer_connection.py b/overmind/tests/test_transfer_connection.pyindex 8f1e642f..1aca4481 100644--- a/overmind/tests/test_transfer_connection.py+++ b/overmind/tests/test_transfer_connection.py@@ -7,6 +7,8 @@ from typer.testing import CliRunnerfrom overmind.__main__ import app+pytestmark = pytest.mark.covers("privacy")+@pytest.fixturedef transfer_workspace(tmp_path, monkeypatch):diff --git a/overmind/tests/test_typescript_chassis.py b/overmind/tests/test_typescript_chassis.pyindex 60970e5c..841c075a 100644--- a/overmind/tests/test_typescript_chassis.py+++ b/overmind/tests/test_typescript_chassis.py@@ -2,6 +2,7 @@ import jsonimport textwrapfrom pathlib import Path+import pytestfrom typer.testing import CliRunnerfrom overmind.__main__ import app@@ -9,6 +10,8 @@ from overmind.chassis import extract_chassis, reachable_namesfrom overmind.config import loadfrom overmind.utils import convert_json_to_toml+pytestmark = pytest.mark.covers("agent-code")+AGENT_SRC = textwrap.dedent("""import OpenAI from "openai";diff --git a/overmind/uv.lock b/overmind/uv.lockindex 000334d5..a38811a4 100644--- a/overmind/uv.lock+++ b/overmind/uv.lock@@ -923,7 +923,7 @@ wheels = [[[package]]name = "overmind"-version = "0.1.114"+version = "0.1.115"source = { editable = "." }dependencies = [{ name = "packaging" },diff --git a/pyproject.toml b/pyproject.tomlindex 7831af30..dc30e006 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -165,7 +165,8 @@ DJANGO_SETTINGS_MODULE = "tests.settings"testpaths = ["tests"]# Model-state tables instead of replaying the squashed migration (~4s/worker).# Migration-specific tests opt into the migration executor explicitly.-addopts = "--nomigrations -p tests.journey_xdist"+addopts = "--nomigrations -p tests.journey_xdist -p tests.coverage_guard"+markers = ["load: capacity checks with wall-clock bounds; `make test-load` runs them"][tool.uv]# aiohttp is transitive (litellm, modal); floor it for the CVE fix in 3.14.3.diff --git a/scripts/check_coverage_map.py b/scripts/check_coverage_map.pynew file mode 100644index 00000000..bcf2899f--- /dev/null+++ b/scripts/check_coverage_map.py@@ -0,0 +1,51 @@+"""Every test file names one coverage-map entry, and every entry has an owning test.++Pytest collection checks the platform and SDK markers; Console test files carry a+``// covers: <entry>`` line that the vitest setup and this script check.+"""++from __future__ import annotations++import re+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))++from tests.coverage_map import COVERAGE_MAP, Kind # noqa: E402++COVERS = re.compile(r"""pytest\.mark\.covers\(\s*["']([\w-]+)["']""")+VITEST_COVERS = re.compile(r"^// covers: (\S+)$", re.M)+++def main() -> int:+ problems = []+ owned = set()+ for tests in (ROOT / "tests", ROOT / "overmind/tests"):+ for path in sorted(tests.rglob("test_*.py")):+ for entry in COVERS.findall(path.read_text()):+ if entry in COVERAGE_MAP:+ owned.add(entry)+ else:+ problems.append(f"{path.relative_to(ROOT)}: {entry!r} is not a map entry")+ for path in sorted((ROOT / "frontend/src").rglob("*.test.ts*")):+ name = path.relative_to(ROOT)+ covers = VITEST_COVERS.findall(path.read_text())+ if len(covers) != 1 or covers[0] not in COVERAGE_MAP:+ problems.append(f"{name}: add one '// covers: <entry>' line naming a map entry")+ elif COVERAGE_MAP[covers[0]].kind is Kind.PROMISE:+ problems.append(f"{name}: a promise is covered only by its journey")+ else:+ owned.add(covers[0])+ problems += [+ f"{entry}: no test covers this coverage-map entry"+ for entry in sorted(set(COVERAGE_MAP) - owned)+ ]+ for problem in problems:+ print(problem)+ return 1 if problems else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/check_journey_budget.py b/scripts/check_journey_budget.pynew file mode 100644index 00000000..bfd557c7--- /dev/null+++ b/scripts/check_journey_budget.py@@ -0,0 +1,37 @@+"""Fail when the journeys run exceeds its CI budget or one journey takes over a third of it."""++from __future__ import annotations++import sys+import xml.etree.ElementTree as ET+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))++from tests.coverage_map import JOURNEY_BUDGET_SECONDS # noqa: E402++LONGEST = JOURNEY_BUDGET_SECONDS / 3+++def main(junit: str) -> int:+ root = ET.parse(junit).getroot()+ suites = [root] if root.tag == "testsuite" else list(root.iter("testsuite"))+ wall = max(float(suite.get("time") or 0) for suite in suites)+ failures = []+ if wall > JOURNEY_BUDGET_SECONDS:+ failures.append(f"journeys took {wall:.0f} s; the budget is {JOURNEY_BUDGET_SECONDS} s")+ for case in root.iter("testcase"):+ seconds = float(case.get("time") or 0)+ if seconds > LONGEST:+ failures.append(+ f"{case.get('classname')}::{case.get('name')} took {seconds:.0f} s; "+ f"one test may take {LONGEST:.0f} s"+ )+ for failure in failures:+ print(failure)+ return 1 if failures else 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1]))diff --git a/scripts/check_test_seams.py b/scripts/check_test_seams.pyindex 3068eb5e..ca81f0ac 100644--- a/scripts/check_test_seams.py+++ b/scripts/check_test_seams.py@@ -2,8 +2,10 @@A test may capture a Celery dispatch (``.delay`` / ``.apply_async``) and fakeoutside services through ``tests/fakes``. It may not patch other ``overbae.*``-targets or import private ``overbae`` names. Existing seams are counted, not-listed: a file fails only when a change adds one.+or ``overmind.*`` targets or import their private names, and a journey may not wait on wall+time, animations or fonts. A Console test may mock third-party modules and the+network edge (``@/client``, ``@/openapi``), not our other modules. Existing seams are counted, not listed: a change fails+only when it raises a count across all test files, so moving a test passes."""from __future__ import annotations@@ -13,22 +15,59 @@ import osimport reimport subprocessimport sys+from collections import Counter+from itertools import chainfrom pathlib import Path-PATCH_TARGET = re.compile(r"""(?:patch|setattr)\(\s*["'](overbae\.[\w.]+)["']""")+PATCH_TARGET = re.compile(r"""(?:patch|setattr)\(\s*["']((?:overbae|overmind)\.[\w.]+)["']""")CELERY_CAPTURES = (".delay", ".apply_async")+JOURNEY_WAIT = re.compile(r"time\.sleep\(|getAnimations|document\.fonts|fontFamily")+VITEST_MOCK = re.compile(r"""vi\.mock\(\s*["']((?:@/|\.{1,2}/)[^"']+)["']""")+NETWORK_EDGE = ("@/client", "@/openapi")+CONSOLE_TESTS = (".test.ts", ".test.tsx")+PYTHON_TESTS = ("tests/", "overmind/tests/")+ROOTS = ("tests", "overmind/tests", "frontend/src")-def _source(ref: str, path: str) -> str:- result = subprocess.run(["git", "show", f"{ref}:{path}"], capture_output=True, text=True)- return result.stdout if result.returncode == 0 else ""+def _git(*args: str, stdin: bytes | None = None) -> bytes:+ return subprocess.run(["git", *args], input=stdin, capture_output=True, check=True).stdout-def _working(path: str) -> str:- try:- return Path(path).read_text(encoding="utf-8")- except OSError:- return ""+def _tracked(path: str) -> bool:+ if path.startswith("frontend/src/"):+ return path.endswith(CONSOLE_TESTS)+ return path.startswith(PYTHON_TESTS) and path.endswith(".py")+++def _committed(ref: str) -> dict[str, str]:+ listed = _git("ls-tree", "-r", "-z", "--name-only", ref, "--", *ROOTS)+ paths = [path for path in listed.decode().split("\0") if _tracked(path)]+ blobs = _git("cat-file", "--batch", stdin="".join(f"{ref}:{p}\n" for p in paths).encode())+ sources, offset = {}, 0+ for path in paths:+ header = blobs.index(b"\n", offset)+ size = int(blobs[offset:header].split()[2])+ sources[path] = blobs[header + 1 : header + 1 + size].decode("utf-8", errors="replace")+ offset = header + 2 + size+ return sources+++def _working() -> dict[str, str]:+ listed = _git(+ "ls-files",+ "-z",+ "--cached",+ "--others",+ "--exclude-standard",+ "--",+ "tests",+ "frontend/src",+ )+ return {+ path: Path(path).read_text(encoding="utf-8")+ for path in listed.decode().split("\0")+ if _tracked(path) and Path(path).is_file()+ }def _patches(source: str) -> list[str]:@@ -43,30 +82,55 @@ def _private_imports(source: str) -> list[str]:return [f"{node.module}.{alias.name}"for node in ast.walk(tree)- if isinstance(node, ast.ImportFrom) and (node.module or "").startswith("overbae")+ if isinstance(node, ast.ImportFrom)+ and (node.module or "").startswith(("overbae", "overmind"))for alias in node.namesif alias.name.startswith("_")]-def main(paths: list[str]) -> int:+def _journey_waits(source: str) -> list[str]:+ return JOURNEY_WAIT.findall(source)+++def _console_mocks(source: str) -> list[str]:+ return [t for t in VITEST_MOCK.findall(source) if not t.startswith(NETWORK_EDGE)]+++KINDS = (+ ("patch of", _patches, PYTHON_TESTS),+ ("private import of", _private_imports, PYTHON_TESTS),+ ("wait on", _journey_waits, "tests/journeys/"),+ ("mock of", _console_mocks, "frontend/src/"),+)+++def main() -> int:+ before = _committed(os.environ.get("PRE_COMMIT_FROM_REF") or "HEAD")+ after = _working()failures = []- for path in paths:- before = _source(os.environ.get("PRE_COMMIT_FROM_REF") or "HEAD", path)- after = _working(path)- for kind, count in (("patch of", _patches), ("private import of", _private_imports)):- added = sorted(set(count(after)) - set(count(before)))- if len(count(after)) > len(count(before)):- failures.append(f"{path}: new {kind} {', '.join(added) or 'our own code'}")+ for kind, count, scope in KINDS:+ old = {path: count(source) for path, source in before.items() if path.startswith(scope)}+ new = {path: count(source) for path, source in after.items() if path.startswith(scope)}+ added = Counter(chain.from_iterable(new.values())) - Counter(+ chain.from_iterable(old.values())+ )+ for target in sorted(added):+ paths = [+ path+ for path, found in sorted(new.items())+ if found.count(target) > old.get(path, []).count(target)+ ]+ failures.append(f"new {kind} {target}: {', '.join(paths)}")for failure in failures:print(failure)if failures:print(- "Fake outside services through tests/fakes and call public entry points; "- "see the run-tests skill."+ "Fake outside services through tests/fakes, call public entry points and wait "+ "on observable state; see the run-tests skill.")return 1 if failures else 0if __name__ == "__main__":- sys.exit(main(sys.argv[1:]))+ sys.exit(main())diff --git a/tests/conftest.py b/tests/conftest.pyindex c457471e..10fab773 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -12,10 +12,11 @@ import httpximport pytestfrom asgiref.sync import SyncToAsync, async_to_syncfrom django.db import connections, transaction+from django.test import TransactionTestCasefrom fakes.clerk import ClerkAPIfrom fakes.http import ScriptedAPIfrom fakes.llm import FakeLLM, Network-from fakes.modal import FakeModal, ServingBackend, SftBackend+from fakes.modal import DecisionBackend, FakeModal, ServingBackend, SftBackendfrom fakes.stripe import StripeAPI@@ -30,6 +31,39 @@ def pytest_ignore_collect(collection_path, config):return True if parallel or not os.environ.get("TEST_REDIS_URL") else None+# Static rows that post_migrate creates once per test database.+_KEPT_TABLES = {"django_content_type", "auth_permission", "django_migrations"}+++def _truncate_written_tables(self):+ # Django's flush truncates every table and re-runs post_migrate (about 3 s a test);+ # emptying only the tables a test wrote leaves the database in the same state.+ for alias in self._databases_names(include_mirrors=False):+ connection = connections[alias]+ quote = connection.ops.quote_name+ tables = sorted(+ set(connection.introspection.django_table_names(only_existing=True)) - _KEPT_TABLES+ )+ with connection.cursor() as cursor:+ cursor.execute(+ " UNION ALL ".join(+ f"SELECT %s WHERE EXISTS (SELECT 1 FROM {quote(table)})" for table in tables+ ),+ tables,+ )+ written = [row[0] for row in cursor.fetchall()]+ if written:+ # DELETE skips TRUNCATE's per-table file work; replica mode skips FK order.+ cursor.execute(+ "SET session_replication_role = replica;"+ + "".join(f"DELETE FROM {quote(table)};" for table in written)+ + "SET session_replication_role = DEFAULT;"+ )+++TransactionTestCase._fixture_teardown = _truncate_written_tables++def drain_stream(response) -> bytes:"""Collect a streaming response body in a sync test.@@ -161,6 +195,11 @@ def serving(fake_modal) -> ServingBackend:return ServingBackend(fake_modal, url="http://inference.test").install()+def decisions(fake_modal) -> DecisionBackend:+ return DecisionBackend(fake_modal).install()++@pytest.fixture(autouse=True)def _close_sync_to_async_connections():yielddiff --git a/tests/coverage_guard.py b/tests/coverage_guard.pynew file mode 100644index 00000000..0d746390--- /dev/null+++ b/tests/coverage_guard.py@@ -0,0 +1,47 @@+"""Collection fails unless every test covers exactly one coverage-map entry."""++from __future__ import annotations++from collections import defaultdict+from pathlib import Path++import pytest++from .coverage_map import COVERAGE_MAP, Kind++JOURNEYS = Path(__file__).parent / "journeys"+++def pytest_configure(config):+ config.addinivalue_line("markers", "covers(entry): the coverage-map entry this test owns")++[email protected](trylast=True)+def pytest_collection_modifyitems(config, items):+ problems = []+ journeys = defaultdict(set)+ for item in items:+ marker = item.get_closest_marker("covers")+ if marker is None or len(marker.args) != 1:+ problems.append(f"{item.nodeid}: add pytest.mark.covers(<entry>)")+ continue+ entry = COVERAGE_MAP.get(marker.args[0])+ if entry is None:+ problems.append(f"{item.nodeid}: {marker.args[0]!r} is not in tests/coverage_map.py")+ continue+ if entry.kind is not Kind.PROMISE:+ continue+ if JOURNEYS not in Path(item.path).parents:+ problems.append(f"{item.nodeid}: a promise is covered only by its journey")+ journeys[marker.args[0]].add(item.originalname)+ variant = item.callspec.id if hasattr(item, "callspec") else None+ if variant not in (entry.variants or (None,)):+ problems.append(+ f"{item.nodeid}: declare variant {variant!r} for {marker.args[0]!r} "+ "in tests/coverage_map.py"+ )+ for promise, names in journeys.items():+ if len(names) > 1:+ problems.append(f"{promise}: one journey per promise, found {sorted(names)}")+ if problems:+ raise pytest.UsageError("Coverage map:\n " + "\n ".join(problems))diff --git a/tests/coverage_map.py b/tests/coverage_map.pynew file mode 100644index 00000000..cf37b8b8--- /dev/null+++ b/tests/coverage_map.py@@ -0,0 +1,269 @@+"""The product coverage map: every test file covers exactly one entry.++A promise is one product vertical, owned by one journey. Invariants hold across+verticals, contracts guard wire formats and boundaries, logic covers pure+computation with real edge cases.+"""++from __future__ import annotations++from dataclasses import dataclass+from enum import StrEnum+++class Severity(StrEnum):+ # A security breach, a wrong charge, or lost or changed data.+ CRITICAL = "S1"+ # A vertical, or the platform, stops for every customer.+ HIGH = "S2"+ # One path, integration, model family or displayed fact is wrong.+ MEDIUM = "S3"+ # A heuristic or a presentation detail is wrong.+ LOW = "S4"+++class Kind(StrEnum):+ PROMISE = "promise"+ INVARIANT = "invariant"+ CONTRACT = "contract"+ LOGIC = "logic"+++@dataclass(frozen=True)+class Entry:+ severity: Severity+ kind: Kind+ holds: str+ variants: tuple[str, ...] = ()+++# Pytest wall time of the journeys run on a 4-vCPU CI runner; one journey may take a third.+JOURNEY_BUDGET_SECONDS = 300++S1, S2, S3, S4 = Severity.CRITICAL, Severity.HIGH, Severity.MEDIUM, Severity.LOW+PROMISE, INVARIANT, CONTRACT, LOGIC = Kind.PROMISE, Kind.INVARIANT, Kind.CONTRACT, Kind.LOGIC++COVERAGE_MAP: dict[str, Entry] = {+ "tenancy": Entry(+ S1,+ INVARIANT,+ "No other account and no anonymous caller reads or writes a project's rows: "+ "REST, MCP, Console and ingest.",+ ),+ "authentication": Entry(+ S1,+ INVARIANT,+ "Each surface admits only its own credentials, with their permissions: API key "+ "scopes, MCP OAuth, sessions, the guest gate, invites and seats, Overwatch tokens.",+ ),+ "privacy": Entry(+ S1,+ INVARIANT,+ "Secrets and private content never leave: keys, error text, tool arguments, raw "+ "worker text, analytics from a self-hosted install.",+ ),+ "ledger": Entry(+ S1,+ INVARIANT,+ "Each charge is metered once from measured usage at the current price; the hosted "+ "cap stops spend at zero; a top-up, renewal or webhook applies once.",+ ),+ "work-once": Entry(+ S1,+ INVARIANT,+ "A request key returns the same record and a changed payload conflicts; "+ "redelivery never repeats work; an unknown provider ack is reconciled, never "+ "resubmitted.",+ ),+ "spend-stops": Entry(+ S1,+ INVARIANT,+ "A failed or cancelled GPU job stops its provider call, deploys nothing, and its "+ "volume data is purged.",+ ),+ "lineage": Entry(+ S1,+ INVARIANT,+ "A used dataset version never changes; landing and publication are atomic; "+ "consumers pin versions; a sealed artifact cannot change under its identity.",+ ),+ "migrations": Entry(+ S1,+ INVARIANT,+ "The migration graph check passes; a data migration ships a replay test until a "+ "release applies it.",+ ),+ "observe": Entry(+ S2,+ PROMISE,+ "A coding agent connects and syncs the agent; its traces arrive as rooted trees "+ "bound to capabilities, are scored once per evidence and raise signals.",+ ),+ "data": Entry(+ S2,+ PROMISE,+ "A source lands, a pipeline publishes a dataset version, and a consumer's use freezes it.",+ ),+ "evaluate": Entry(+ S2,+ PROMISE,+ "An eval set runs every candidate and backtests it against the recorded baseline.",+ ),+ "optimise": Entry(S2, PROMISE, "Failing traces become a measured winning diff."),+ "train": Entry(+ S2,+ PROMISE,+ "A dataset version trains a model; the native benchmark measures it; it deploys "+ "and switches in by alias or pin.",+ ),+ "serve": Entry(+ S2,+ PROMISE,+ "The SDK and the gateway reach served, frontier and dedicated models, and each "+ "call is metered.",+ ),+ "decide": Entry(+ S2,+ PROMISE,+ "A decision dataset trains a decision model; its quality is measured before and "+ "after training; it answers through /api/v1/systemone.",+ ),+ "boot": Entry(+ S2,+ INVARIANT,+ "Hosted and self-hosted installs boot from their environment and answer health; "+ "a missing variable stops startup by name.",+ ),+ "topology": Entry(+ S2,+ INVARIANT,+ "Celery routes, compose, make worker and the worker topology agree; every "+ "scheduled task is registered; a release drains workers.",+ ),+ "recovery": Entry(+ S2,+ INVARIANT,+ "Work never stays stuck: lost tasks, worker loss and provider interruptions are "+ "reconciled; locks expire; periodic tasks recover.",+ ),+ "capacity": Entry(+ S2,+ INVARIANT,+ "Per-project limits hold under concurrency, one project never starves another, "+ "and the declared scale stays inside its query and task budgets.",+ ),+ "identity": Entry(+ S2,+ INVARIANT,+ "OTLP never creates a capability, a scan never deletes one, rebinding is by ID "+ "only, and DELETE is soft.",+ ),+ "sdk-install": Entry(+ S2,+ INVARIANT,+ "The published SDK never breaks its host: the default install imports and runs, and "+ "a missing extra, provider library, key or analytics backend degrades to a no-op or "+ "an install hint.",+ ),+ "measured-facts": Entry(+ S3,+ INVARIANT,+ "Missing usage, progress, cost, ETA and scores stay unknown; partial coverage "+ "reads as partial.",+ ),+ "live-console": Entry(+ S3,+ CONTRACT,+ "The open Console receives live updates and keeps its state after a reload.",+ ),+ "otlp-ingest": Entry(+ S3, CONTRACT, "Each OTLP dialect lands as its native span type, with sessions and errors."+ ),+ "sdk-wire": Entry(+ S3,+ CONTRACT,+ "SDK decorators and scopes build the trace the server reads (run boundaries, turns, "+ "handoffs, capability scope), and the SDK and the server agree on span attributes, "+ "usage keys, model names and scanned codebase cards.",+ ),+ "cli-contract": Entry(+ S3,+ CONTRACT,+ "Each CLI command validates its input before any request, changes only its own files, "+ "and exits non-zero with a machine-readable error.",+ ),+ "vendor-connectors": Entry(+ S3,+ CONTRACT,+ "Each vendor maps to rooted, capability-bound traces, with backfill, polling and "+ "rate limits.",+ ),+ "llm-gateway": Entry(+ S3,+ CONTRACT,+ "Each provider works through the gateway (streaming, tool calls, schemas, "+ "deadlines, routing); the model catalog and registry resolve.",+ ),+ "mcp-surface": Entry(+ S3,+ CONTRACT,+ "MCP schemas, manifest size, contract version, transport, prompts, resources and "+ "error shapes hold; every command handed to an agent parses.",+ ),+ "http-api": Entry(+ S3,+ CONTRACT,+ "REST matches the OpenAPI schema, the generated client is in sync, and every "+ "Console route renders without errors.",+ ),+ "model-runtime": Entry(+ S3,+ CONTRACT,+ "Training and serving runtimes work per model family: chat templates, hooks, "+ "adapter and weight formats, stacks, pinned releases.",+ ),+ "sandbox": Entry(+ S3,+ CONTRACT,+ "A pipeline step runs from its retained package with its pinned runtime and no "+ "network; a failed exit never reports success.",+ ),+ "metrics-math": Entry(+ S3,+ LOGIC,+ "Scores, judges, signals, benchmark grading, decision metrics, token accuracy, "+ "span cost and usage aggregation.",+ ),+ "data-logic": Entry(+ S3,+ LOGIC,+ "Transforms, splits, partitions, fan-in, fingerprints, file typing and the train "+ "and eval row contracts.",+ ),+ "agent-code": Entry(+ S3,+ LOGIC,+ "The CLI reads agent code into the call graphs, anchors and trajectories that exist, "+ "never overwrites config from an incomplete scan, and rewrites entrypoints that still run.",+ ),+ "plans": Entry(+ S3,+ LOGIC,+ "Hyperparameters, context budgets, batching, eval schedules and monitoring plans.",+ ),+ "state-machines": Entry(+ S3,+ LOGIC,+ "Job lifecycle, the optimiser, the native evaluation plan and model activation.",+ ),+ "recommendations": Entry(+ S4,+ LOGIC,+ "Model ranking and constraints, task-type classification, dataset profiling.",+ ),+ "console-logic": Entry(+ S4,+ LOGIC,+ "Formatters, table state, polling, upload state, charts and trajectory layout.",+ ),+}diff --git a/tests/fakes/clerk.py b/tests/fakes/clerk.pyindex dcb50dfd..a3efaeaf 100644--- a/tests/fakes/clerk.py+++ b/tests/fakes/clerk.py@@ -20,27 +20,6 @@ _KID = "ins_fake"_ids = itertools.count(1)-PENDING_BROWSER_FORM_SCRIPT = """-window.Clerk = {- loaded: true,- user: null,- session: null,- organization: null,- client: { signIn: {}, signUp: {} },- load: async () => {},- addListener(listener) {- listener({ client: this.client, user: null, session: null, organization: null });- return () => {};- },- mountSignIn() { fetch('https://clerk.example.invalid/pending-form'); },- mountSignUp() { fetch('https://clerk.example.invalid/pending-form'); },- unmountSignIn() {},- unmountSignUp() {},- __unstable__updateProps() {},-};-"""--def _json(body: Any, status: int = 200) -> tuple[int, dict, bytes]:return status, {"content-type": "application/json"}, json.dumps(body).encode()diff --git a/tests/fakes/modal.py b/tests/fakes/modal.pyindex 6ff887dc..c7b736ca 100644--- a/tests/fakes/modal.py+++ b/tests/fakes/modal.py@@ -4,6 +4,7 @@ import gzipimport hashlibimport itertoolsimport json+import mathimport threadingfrom collections.abc import Callablefrom contextlib import contextmanager@@ -16,6 +17,8 @@ import modalfrom asgiref.sync import sync_to_asyncfrom modal.exception import NotFoundError+from modal_shared.decisions import DECISION_OBJECTIVES+_ids = itertools.count(1)@@ -176,6 +179,19 @@ class _FakeInstance:return FakeFunction(self._cloud, self._app, f"{self._cls}.{method}")+@dataclass+class _FakeCls:+ cloud: FakeModal+ app: str+ cls: str++ def with_options(self, **_options) -> _FakeCls:+ return self++ def __call__(self, **_parameters) -> _FakeInstance:+ return _FakeInstance(self.cloud, self.app, self.cls)++@dataclassclass FakeModal:handlers: dict[tuple[str, str], tuple[Callable[..., Any], bool]] = field(default_factory=dict)@@ -281,7 +297,7 @@ class FakeModal:class Cls:@staticmethoddef from_name(app: str, cls: str, **_):- return lambda **__: _FakeInstance(cloud, app, cls)+ return _FakeCls(cloud, app, cls)class Volume:@staticmethod@@ -378,7 +394,7 @@ class SftBackend:self.cloud.fail("sft_", RuntimeError(message))def _train(self, run_id: str, env: dict, *, gpu_type: str = "", gpu_count: int = 1) -> dict:- self.runs[run_id]["status"] = "succeeded"+ self.runs[run_id].update(status="succeeded", objective=env.get("TRAINING_OBJECTIVE"))return {"run_id": run_id, "status": "succeeded"}def _cancelled(self, run_id: str) -> dict:@@ -399,13 +415,25 @@ class SftBackend:}for step in range(1, run["steps"] + 1)]- return {+ progress = {"run_id": run_id,"found": True,"meta": {"status": run["status"]},"metrics": metrics,"has_final_checkpoint": run["status"] == "succeeded" or bool(run.get("final")),}+ if run["status"] == "succeeded" and run.get("objective") in DECISION_OBJECTIVES:+ progress["native_artifact"] = {+ "artifact_identity": hashlib.sha256(run_id.encode()).hexdigest(),+ "reload_verification": {+ "decisions": len(self.materialized[run_id]["data"]),+ "max_absolute_error": 0.0,+ "tolerance": 1e-4,+ "weight_reload": "exact",+ },+ "training": {"objective": run["objective"]},+ }+ return progress@dataclass@@ -440,3 +468,98 @@ class ServingBackend:def _pre_warm(self, *, model_id: str, **_) -> dict:self.warmed.append(model_id)return {"ok": True}+++def _uniform(request: dict, trained: bool) -> list[float]:+ return [1 / len(request["options"])] * len(request["options"])+++@dataclass+class DecisionBackend:+ """Native decision evaluation on the training release and the decision serving worker.++ ``answer(request, trained)`` returns the option probabilities a model gives."""++ cloud: FakeModal+ answer: Callable[[dict, bool], list[float]] = _uniform+ prepared: dict[str, str] = field(default_factory=dict)++ def install(self) -> DecisionBackend:+ from overbae.services.decision_serving import current_runtime+ from overbae.services.native_evaluation import runtime++ self.release = runtime()+ serve = current_runtime()["app"]+ self.cloud.deploy(self.release["app"], "prepare", self._prepare)+ self.cloud.deploy(self.release["app"], "predict", self._predict)+ self.cloud.deploy(serve, "publish", self._publish)+ self.cloud.deploy(serve, "pre_warm", self._pre_warm)+ self.cloud.deploy(serve, "DecisionEndpoint.predict", self._serve)+ return self++ def _inputs(self, evaluation_id: str) -> tuple[bytes, list[dict]]:+ body = self.cloud.files[f"/decision-evaluations/{evaluation_id}/inputs.jsonl"]+ return body, [json.loads(line) for line in body.splitlines() if line]++ def _prepare(self, evaluation_id, model_run, input_sha256, *, foundation=None, inference=None):+ body, rows = self._inputs(evaluation_id)+ assert hashlib.sha256(body).hexdigest() == input_sha256+ identity = (+ hashlib.sha256(model_run.encode()).hexdigest()+ if model_run+ else f"foundation:{foundation['model']}"+ )+ self.prepared[evaluation_id] = identity+ self.cloud.files[f"/decision-evaluations/{evaluation_id}/failures.jsonl"] = b""+ return {+ "artifact_identity": identity,+ "input_sha256": input_sha256,+ "ready_decisions": len(rows),+ "failures_sha256": hashlib.sha256(b"").hexdigest(),+ }++ def _predict(self, evaluation_id, model_run, *, base_only, inference=None):+ body, rows = self._inputs(evaluation_id)+ identity = self.prepared[evaluation_id]+ predictions = []+ for row in rows:+ probabilities = self.answer(row["decision"], not base_only)+ predictions.append(+ {+ "key": row["key"],+ "input_sha256": row["input_sha256"],+ "kind": row["decision"]["kind"],+ "model_identity": identity,+ "probabilities": probabilities,+ "log_probabilities": [math.log(p) for p in probabilities],+ }+ )+ output = "".join(json.dumps(p) + "\n" for p in predictions).encode()+ name = "base" if base_only else "candidate"+ self.cloud.files[f"/decision-evaluations/{evaluation_id}/{name}.jsonl"] = output+ return {+ "artifact_identity": identity,+ "input_sha256": hashlib.sha256(body).hexdigest(),+ "runtime_fingerprint": self.release["training"],+ "predictions_sha256": hashlib.sha256(output).hexdigest(),+ "decisions": len(predictions),+ }++ def _publish(self, *, remote_id, artifact_identity) -> dict:+ return {+ "weights_path": f"/weights/decisions/{remote_id}",+ "artifact_identity": artifact_identity,+ }++ def _pre_warm(self, *, weights_path, artifact_identity, max_model_len, gpu_type) -> dict:+ return {"verified": True, "artifact_identity": artifact_identity}++ def _serve(self, requests: list[dict]) -> dict:+ return {+ "predictions": [+ {"options": request["options"], "probabilities": self.answer(request, True)}+ for request in requests+ ],+ "usage": {"prompt_tokens": 8 * len(requests), "completion_tokens": 0},+ "finish_reason": "stop",+ }diff --git a/tests/journeys/console/conftest.py b/tests/journeys/browser.pysimilarity index 66%rename from tests/journeys/console/conftest.pyrename to tests/journeys/browser.pyindex 13991a62..96c2b7fb 100644--- a/tests/journeys/console/conftest.py+++ b/tests/journeys/browser.py@@ -1,45 +1,51 @@+from __future__ import annotations++import fcntlimport functoolsimport jsonimport os-import re+import shutilimport subprocessimport threading+from collections.abc import Iteratorfrom concurrent.futures import ThreadPoolExecutor+from contextlib import contextmanagerfrom http.server import SimpleHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Path-import pytestfrom playwright.sync_api import sync_playwright-from ..conftest import RUNS+from .stack import RUNS-FRONTEND = Path(__file__).resolve().parents[3] / "frontend"+FRONTEND = Path(__file__).resolve().parents[2] / "frontend"PASSWORD = "test-pass-123"--[email protected](scope="session")-def replay_recorder(tmp_path_factory):- bundle = tmp_path_factory.mktemp("replay-recorder") / "recorder.js"- entry = bundle.with_suffix(".ts")- entry.write_text(- f"import {{ record }} from {json.dumps(str(FRONTEND / 'node_modules/posthog-js/dist/rrweb.js'))};"- "window.ReplayRecorder = { record };"- )- subprocess.run(- [- "bun",- "build",- str(entry),- "--format=iife",- "--outfile",- str(bundle),- ],- cwd=FRONTEND,- check=True,- capture_output=True,- timeout=60,- )- return bundle+# Vite inlines VITE_API_BASE_URL; each worker swaps it for its own live API after the build.+API_PLACEHOLDER = "http://journey-api.invalid"+++def build_console(shared: Path) -> Path:+ dist = shared / "dist"+ shared.mkdir(parents=True, exist_ok=True)+ with (shared / "build.lock").open("w") as lock:+ fcntl.flock(lock, fcntl.LOCK_EX)+ if not (dist / "index.html").exists():+ env = {+ **os.environ,+ "VITE_API_BASE_URL": API_PLACEHOLDER,+ "VITE_SELF_HOSTED": "true",+ "VITE_CLERK_PUBLISHABLE_KEY": "",+ "VITE_PUBLIC_POSTHOG_KEY": "",+ "VITE_FEATURE_SIGNALS": "true",+ }+ subprocess.run(+ ["bun", "run", "build", "--outDir", str(dist), "--emptyOutDir"],+ cwd=FRONTEND,+ env=env,+ check=True,+ capture_output=True,+ timeout=300,+ )+ return distclass _SinglePageApp(SimpleHTTPRequestHandler):@@ -52,34 +58,23 @@ class _SinglePageApp(SimpleHTTPRequestHandler):pass[email protected](scope="session")-def console_url(live_api, tmp_path_factory, request):- dist = tmp_path_factory.mktemp("console")- env = {- **os.environ,- "VITE_API_BASE_URL": live_api.url,- "VITE_SELF_HOSTED": "true",- "VITE_CLERK_PUBLISHABLE_KEY": "",- "VITE_PUBLIC_POSTHOG_KEY": "",- "VITE_FEATURE_SIGNALS": "true",- }- if getattr(request, "param", None) == "clerk":- env["VITE_SELF_HOSTED"] = "false"- env["VITE_CLERK_PUBLISHABLE_KEY"] = "pk_test_Y2xlcmsuZXhhbXBsZS5pbnZhbGlkJA"- subprocess.run(- ["bun", "run", "build", "--outDir", str(dist), "--emptyOutDir"],- cwd=FRONTEND,- env=env,- check=True,- capture_output=True,- timeout=300,- )+@contextmanager+def serve_console(built: Path, into: Path, api_url: str) -> Iterator[str]:+ dist = into / "dist"+ shutil.copytree(built, dist)+ for path in dist.rglob("*"):+ if path.suffix in {".js", ".html"}:+ text = path.read_text()+ if API_PLACEHOLDER in text:+ path.write_text(text.replace(API_PLACEHOLDER, api_url))server = ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(_SinglePageApp, directory=str(dist)))threading.Thread(target=server.serve_forever, daemon=True).start()- yield f"http://127.0.0.1:{server.server_address[1]}"- server.shutdown()+ try:+ yield f"http://127.0.0.1:{server.server_address[1]}"+ finally:+ server.shutdown()class Browser:@@ -94,7 +89,7 @@ class Browser:def call(self, fn, *args):return self._thread.submit(fn, *args).result()- def page(self, base_url: str) -> "Console":+ def page(self, base_url: str) -> Console:page = self.call(lambda: self._browser.new_page(base_url=base_url))self.call(page.set_default_timeout, 20_000)return Console(self, page)@@ -177,30 +172,3 @@ class Console:def close(self) -> None:self._browser.call(self._page.close)--[email protected](scope="session")-def browser():- browser = Browser()- yield browser- browser.close()---def console(browser, console_url, account, settings, request) -> Console:- settings.CORS_ALLOW_ALL_ORIGINS = True- user, _key = account- console = browser.page(console_url)- console.goto("/login")- console.fill("#local-email", user.email)- console.fill("#local-password", PASSWORD)- console.press("Continue")- console.wait_until("() => !!localStorage.getItem('jwt_access')")- console.goto("/onboarding")- console.sees("Agent")- yield console- try:- console.save_evidence(re.sub(r"[^\w.-]+", "_", request.node.nodeid))- console.healthy()- finally:- console.close()diff --git a/tests/journeys/conftest.py b/tests/journeys/conftest.pyindex 21133efe..a6e329b5 100644--- a/tests/journeys/conftest.py+++ b/tests/journeys/conftest.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport jsonimport osimport re+import subprocessimport sysimport timefrom datetime import UTC, datetime@@ -19,11 +20,17 @@ from factories import make_user # noqa: E402import overmind # noqa: E402from overbae.models import APIToken # noqa: E402-from .stack import LiveAPI, celery_worker, drain # noqa: E402+from .browser import ( # noqa: E402+ FRONTEND,+ PASSWORD,+ Browser,+ Console,+ build_console,+ serve_console,+)+from .stack import RUNS, LiveAPI, celery_worker, drain # noqa: E402from .surfaces import CliSurface, McpSurface, RestSurface, SampleAgent # noqa: E402-RUNS = Path(__file__).parent / ".runs" / datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")-def pytest_configure(config):config.addinivalue_line("markers", "journey: end-to-end journey on the live stack")@@ -89,6 +96,7 @@ def worker(_worker_ledger):yield _worker_ledger_release_connector_chunks(_worker_ledger)drain(_worker_ledger)+ _worker_ledger.revoke_scheduled()failed = {k: v for k, v in _worker_ledger.failed().items() if k not in failed_before}assert not failed, f"Background tasks failed: {failed}"@@ -249,3 +257,57 @@ def beat(worker, clock):drain(worker)return tick++[email protected](scope="session")+def replay_recorder(tmp_path_factory):+ bundle = tmp_path_factory.mktemp("replay-recorder") / "recorder.js"+ entry = bundle.with_suffix(".ts")+ rrweb = FRONTEND / "node_modules/posthog-js/dist/rrweb.js"+ entry.write_text(+ f"import {{ record }} from {json.dumps(str(rrweb))};window.ReplayRecorder = {{ record }};"+ )+ subprocess.run(+ ["bun", "build", str(entry), "--format=iife", "--outfile", str(bundle)],+ cwd=FRONTEND,+ check=True,+ capture_output=True,+ timeout=60,+ )+ return bundle++[email protected](scope="session")+def console_url(live_api, tmp_path_factory, worker_id):+ # xdist workers share this run's base temp parent; a serial run's parent outlives it.+ run = tmp_path_factory.getbasetemp()+ built = build_console((run if worker_id == "master" else run.parent) / "console")+ with serve_console(built, tmp_path_factory.mktemp("console"), live_api.url) as url:+ yield url++[email protected](scope="session")+def browser():+ browser = Browser()+ yield browser+ browser.close()+++def console(browser, console_url, account, settings, request) -> Console:+ settings.CORS_ALLOW_ALL_ORIGINS = True+ user, _key = account+ console = browser.page(console_url)+ console.goto("/login")+ console.fill("#local-email", user.email)+ console.fill("#local-password", PASSWORD)+ console.press("Continue")+ console.wait_until("() => !!localStorage.getItem('jwt_access')")+ console.goto("/onboarding")+ console.sees("Agent")+ yield console+ try:+ console.save_evidence(re.sub(r"[^\w.-]+", "_", request.node.nodeid))+ console.healthy()+ finally:+ console.close()diff --git a/tests/journeys/console/__init__.py b/tests/journeys/console/__init__.pydeleted file mode 100644index e69de29b..00000000diff --git a/tests/journeys/console/test_console.py b/tests/journeys/console/test_console.pydeleted file mode 100644index 2f41c092..00000000--- a/tests/journeys/console/test_console.py+++ /dev/null@@ -1,1495 +0,0 @@-import hashlib-import json-import uuid-from datetime import timedelta--import pytest-from django.utils import timezone--from modal_shared.training_monitoring import fingerprint-from overbae.models import (- Activity,- BillingTelemetry,- Cell,- DataPartitionMember,- DataPartitionPlan,- Dataset,- DatasetContext,- DatasetPipeline,- DatasetPipelineRun,- DatasetPreparation,- DedicatedDeployment,- DeployedModel,- EvalRun,- FinetuningJob,- NativeEvaluationPlan,- OperationalRun,- Subscription,-)-from overbae.services import activity as activity_service-from overbae.services import training_monitoring-from overbae.tasks.datasets import reap_stuck_runs-from tests.fakes.clerk import PENDING_BROWSER_FORM_SCRIPT--from ..datasets import tickets, upload-from ..stack import drain, settle---def test_project_navigation_keeps_the_destination_without_a_project(console):- console.goto("/inference?inf_search=needle")- console.sees("Copy onboarding prompt")- console.wait_until(- "() => location.pathname === '/inference' && "- "new URLSearchParams(location.search).get('inf_search') === 'needle'"- )- console.save_evidence("project-navigation-without-project")---def test_translated_onboarding_prompt_can_be_copied(console):- console.goto("/inference")- console.sees("Copy onboarding prompt")- console._browser.call(- lambda: console._page.context.grant_permissions(["clipboard-read", "clipboard-write"])- )- console._browser.call(- console._page.evaluate,- """() => {- const button = [...document.querySelectorAll('button')].find(- element => element.textContent.includes('Copy onboarding prompt'));- const texts = document.createTreeWalker(button, NodeFilter.SHOW_TEXT);- const nodes = [];- while (texts.nextNode()) nodes.push(texts.currentNode);- for (const text of nodes) {- if (!text.textContent.includes('Copy onboarding prompt')) continue;- const translated = document.createElement('font');- translated.textContent = 'Copiar instrucciones';- text.replaceWith(translated);- }- }""",- )- console.press("Copiar instrucciones")- console.sees("Paste the prompt into your coding agent to start setup.")- assert "/setup.md" in console._browser.call(- lambda: console._page.evaluate("navigator.clipboard.readText()")- )- console.save_evidence("translated-onboarding-prompt-copied")---def test_project_navigation_selects_the_only_project_without_leaving(console, workshop):- project = workshop.project()["id"]- console._browser.call(console._page.evaluate, "localStorage.removeItem('__selectedProject')")- console.goto("/inference?inf_search=needle")- console.wait_until(- f"() => location.pathname === '/inference' && "- f"new URLSearchParams(location.search).get('projectId') === '{project}' && "- "new URLSearchParams(location.search).get('inf_search') === 'needle'"- )- console.save_evidence("project-navigation-destination")---def test_onboarding_prompt_retains_the_selected_project(console, rest_for, account_key):- project = rest_for(account_key).request(- "POST", "/api/projects/", json={"name": "Existing setup", "slug": "existing-setup"}- )["id"]- console.goto(f"/?projectId={project}")- console._browser.call(- console._page.context.grant_permissions, ["clipboard-read", "clipboard-write"]- )- console.press("Copy onboarding prompt")- console.sees("Prompt copied")- prompt = console._browser.call(console._page.evaluate, "navigator.clipboard.readText()")- assert f"project_id: {project}" in prompt- assert "dataset_id" not in prompt- console.save_evidence("onboarding-selected-project")--[email protected]("console_url", ["clerk"], indirect=True)-def test_sign_in_script_failure_offers_a_document_reload(browser, console_url):- console = browser.page(console_url)- attempts = []-- def external_request(route):- if route.request.url.startswith(console_url):- route.continue_()- else:- attempts.append(route.request.url)- route.abort()-- console._browser.call(console._page.route, "**/*", external_request)- try:- console.goto("/login")- console.sees("Sign in unavailable")- before = len(attempts)- console.press("Reload sign in")- console.sees("Sign in unavailable")- assert len(attempts) > before- assert any("clerk" in url for url in attempts)- console.save_evidence("sign-in-script-failure")- finally:- console.close()--[email protected]("console_url", ["clerk"], indirect=True)-def test_pending_sign_in_offers_a_document_reload(browser, console_url):- console = browser.page(console_url)- pending = []-- def external_request(route):- if route.request.url.startswith(console_url):- route.continue_()- elif "clerk" in route.request.url:- pending.append(route)- else:- route.abort()-- console._browser.call(console._page.route, "**/*", external_request)- try:- console._browser.call(lambda: console._page.goto("/login", wait_until="domcontentloaded"))- console.sees("Loading sign in")- console.save_evidence("sign-in-pending")- console._browser.call(- lambda: console._page.get_by_role("button", name="Reload sign in").wait_for(- state="visible", timeout=15000- )- )- before = len(pending)-- def reload_sign_in():- with console._page.expect_request(lambda request: "clerk" in request.url):- console._page.get_by_role("button", name="Reload sign in").click()-- console._browser.call(reload_sign_in)- console.sees("Loading sign in")- assert len(pending) > before- console.save_evidence("sign-in-pending-recovery")- finally:- console.close()--[email protected]("console_url", ["clerk"], indirect=True)[email protected]("mode", ["signin", "signup"])-def test_pending_authentication_form_offers_recovery(browser, console_url, mode):- console = browser.page(console_url)- pending = []-- def external_request(route):- if route.request.url.startswith(console_url):- route.continue_()- elif "clerk.browser.js" in route.request.url:- route.fulfill(content_type="application/javascript", body=PENDING_BROWSER_FORM_SCRIPT)- elif route.request.url.endswith("/pending-form"):- pending.append(route)- else:- route.abort()-- console._browser.call(console._page.route, "**/*", external_request)- try:-- def open_form():- with console._page.expect_request("**/pending-form"):- console._page.goto("/login?mode=signup" if mode == "signup" else "/login")-- console._browser.call(open_form)- console.sees("Set up locally")- assert pending- console.save_evidence(f"authentication-form-pending-{mode}")- console.sees("Loading sign in")-- def reload_form():- with console._page.expect_request("**/pending-form"):- console._page.get_by_role("button", name="Reload sign in").click()-- console._browser.call(reload_form)- console.sees("Loading sign in")- console.save_evidence(f"authentication-form-recovery-{mode}")- finally:- console._browser.call(lambda: console._page.unroute_all(behavior="ignoreErrors"))- console.close()---def test_route_error_home_action_reloads_the_document(console):- console.goto("/inference?page=broken")- console.sees("Invalid link")- console._browser.call(console._page.evaluate, "window.failedDocument = true")- console._browser.call(lambda: console._page.get_by_role("link", name="Go to home").click())- console.sees("Copy onboarding prompt")- console.wait_until("() => location.pathname === '/' && !window.failedDocument")- console.save_evidence("route-error-home-recovery")---def test_cancelled_plan_checkout_returns_to_account_settings(- console, console_url, settings, stripe_api, rest_for, account_key-):- settings.STRIPE_PRO_PRICE_ID = "price_journey"- settings.FRONTEND_URL = console_url- rest_for(account_key).request("POST", "/api/billing/checkout/")- cancel_url = stripe_api.sessions[-1]["cancel_url"]- console.goto(cancel_url)- console.save_evidence("plan-checkout-cancel-return")- console.sees("Settings")- console.sees("Buy Pro")--[email protected]("linked_to_stripe", [False, True])-def test_account_settings_only_offer_renewal_controls_for_managed_plans(- console, account, linked_to_stripe-):- user, _ = account- Subscription.objects.create(- user=user,- status="active",- stripe_subscription_id="sub_console" if linked_to_stripe else "",- end_date=timezone.now() + timedelta(days=30),- )- console.goto("/settings")- console.sees("Plan")- console.sees("Pro")- console.save_evidence(f"plan-renewal-controls-{linked_to_stripe}")- assert console._browser.call(- lambda: console._page.get_by_role("button", name="Cancel plan", exact=True).count()- ) == int(linked_to_stripe)---def test_usage_history_keeps_small_charges_visible(console, account):- user, _ = account- BillingTelemetry.objects.create(user=user, service="inference", amount="-0.0000312")- console.goto("/settings")- console.sees("Usage history")- console.sees("0.00312")- console._browser.call(- lambda: console._page.get_by_label("0.00312 credits", exact=True).wait_for()- )- console.save_evidence("usage-small-charge")---def test_dataset_pagination_waits_for_the_requested_rows(- console, workshop, cli, sample_agent, tmp_path-):- project = workshop.project()["id"]- dataset = upload(cli, sample_agent, tickets(tmp_path, n=25))- console.goto(f"/datasets/{dataset}?projectId={project}")- console.sees("1–10 of 25 rows")- pending = []- console._browser.call(- console._page.route, "**/rows/?*offset=10*", lambda route: pending.append(route)- )- try:- console.press("Go to next page")- console.sees("Loading page 2")- assert console._browser.call(- lambda: console._page.get_by_role("button", name="Go to next page").is_disabled()- )- assert pending- console._browser.call(lambda: pending.pop().continue_())- console.sees("11–20 of 25 rows")- console.sees("Refund order 10 please", exact=False)- console.save_evidence("dataset-pagination-next-page")- finally:- for route in pending:- console._browser.call(route.continue_)- console._browser.call(console._page.unroute, "**/rows/?*offset=10*")---def test_dataset_navigation_keeps_rows_with_their_source(- console, workshop, cli, sample_agent, tmp_path, worker-):- project = workshop.project()["id"]- first_path = tickets(tmp_path, n=25).rename(tmp_path / "large-source.jsonl")- first = upload(cli, sample_agent, first_path)- second_path = tickets(tmp_path, n=3).rename(tmp_path / "small-source.jsonl")- second = upload(cli, sample_agent, second_path)- drain(worker)- console.goto(f"/datasets/{first}?projectId={project}")- console.sees("1–10 of 25 rows")- console._browser.call(- lambda: console._page.get_by_role("link", name="Datasets", exact=True).first.click()- )- console.click("small-source.jsonl")- console.wait_until(f"() => location.pathname === '/datasets/{second}'")- console.sees("3 rows × 2")- console.wait_until("() => !document.body.innerText.includes('of 25 rows')")- console.sees("Refund order 2 please", exact=False)- console.save_evidence("dataset-navigation-matching-source")---def test_dataset_pagination_starts_at_the_first_row(console, workshop, cli, sample_agent, tmp_path):- project = workshop.project()["id"]- dataset = upload(cli, sample_agent, tickets(tmp_path, n=225))- console.goto(f"/datasets/{dataset}?projectId={project}")- console.sees("1–10 of 225 rows")- console._browser.call(lambda: console._page.get_by_role("combobox").click())- console._browser.call(- lambda: console._page.get_by_role("option", name="100", exact=True).click()- )- console.sees("1–100 of 225 rows")- console._browser.call(- lambda: console._page.get_by_role(- "button", name="Inspect row 99", exact=True- ).scroll_into_view_if_needed()- )- console.save_evidence("dataset-pagination-before-next")- console.press("Go to next page")- console.sees("101–200 of 225 rows")- console._browser.call(- lambda: console._page.get_by_role("button", name="Inspect row 100", exact=True).wait_for()- )- console.save_evidence("dataset-pagination-first-row")- console.wait_until("""() => {- const row = document.querySelector('button[aria-label="Inspect row 100"]');- const rect = row.getBoundingClientRect();- return rect.top >= 0 && rect.bottom <= innerHeight;- }""")---def test_evaluation_dataset_picker_waits_for_its_options(- console, workshop, cli, sample_agent, tmp_path, fake_llm-):- fake_llm.catalog_payload = [{"id": "qwen/qwen3-8b", "name": "Qwen: Qwen3 8B"}]- project = workshop.project()["id"]- upload(cli, sample_agent, tickets(tmp_path), "--intent", "eval")- pending = []-- def hold_eval_datasets(route):- if "intent=eval" in route.request.url:- pending.append(route)- else:- route.continue_()-- console._browser.call(console._page.route, "**/datasets/?*", hold_eval_datasets)- try:- console.goto(f"/evaluations?projectId={project}")- console.press("New evaluation")- console._browser.call(- lambda: console._page.get_by_role("button", name="Eval dataset", exact=True).click()- )- assert pending- console.sees("Loading options")- console.save_evidence("evaluation-dataset-picker-pending")- console._browser.call(lambda: pending.pop().continue_())- console._browser.call(- lambda: console._page.get_by_role("radio", name="tickets.jsonl", exact=True).click()- )- console._browser.call(- lambda: (- console._page.get_by_role("button", name="Eval dataset", exact=True)- .get_by_text("tickets.jsonl", exact=True)- .wait_for()- )- )- console.save_evidence("evaluation-dataset-picker-selected")- console._browser.call(- lambda: console._page.get_by_role(- "button", name="Model being tested", exact=True- ).click()- )- model_picker_id = console._browser.call(- lambda: console._page.get_by_role(- "button", name="Model being tested", exact=True- ).get_attribute("aria-controls")- )- console._browser.call(- lambda: (- console._page.locator(f'[id="{model_picker_id}"]')- .get_by_role("textbox", name="Search…", exact=True)- .fill("qwen")- )- )- console._browser.call(- lambda: console._page.get_by_role("radio", name="Qwen3 8B", exact=True).click()- )- console._browser.call(- lambda: (- console._page.get_by_role("button", name="Model being tested", exact=True)- .get_by_text("Qwen3 8B", exact=True)- .wait_for()- )- )- console.save_evidence("evaluation-model-search-selected")- finally:- for route in pending:- console._browser.call(route.continue_)- console._browser.call(console._page.unroute, "**/datasets/?*")--[email protected]("clear_action", ["Clear search", "Clear filters"])-def test_inference_search_clear_restores_models(console, workshop, clear_action):- project = workshop.project()["id"]- dataset = Dataset.objects.create(project_id=project, name="Search fixture")- job = FinetuningJob.objects.create(- project_id=project,- dataset=dataset,- base_model="Qwen/Qwen3-8B",- status="succeeded",- output_model_name="ft-search-result",- )- DeployedModel.objects.create(- project_id=project, finetuning_job=job, model_id="ft-search-result", status="ready"- )- console.goto(f"/inference?projectId={project}&inf_search=missing-model")- console.sees("No results")- console.press(clear_action)- console.sees("ft-search-result")- console.wait_until("() => !new URLSearchParams(location.search).get('inf_search')")- console.save_evidence(f"inference-{clear_action.lower().replace(' ', '-')}")---def test_embedded_onboarding_copies_setup_and_switches_to_data(console, console_url, live_api):- console._browser.call(- console._page.context.grant_permissions, ["clipboard-read", "clipboard-write"]- )- console.press("Copy onboarding prompt")- console.sees("Prompt copied")- prompt = console._browser.call(console._page.evaluate, "navigator.clipboard.readText()")- assert prompt == (- f"Set me up on Overmind\n\nusing the API at {live_api.url.rstrip('/')}: "- f"{console_url.rstrip('/')}/setup.md"- )- console.wait_until("""() => {- const panel = document.querySelector('section[aria-label="Get started"]');- return panel.querySelector('a[href$="/setup.md"]') &&- [...panel.querySelectorAll('img')].every(img => img.complete && img.naturalWidth > 0);- }""")- console.save_evidence("embedded-onboarding-desktop")- console._browser.call(console._page.set_viewport_size, {"width": 390, "height": 844})- console.wait_until("""() => {- const panel = document.querySelector('section[aria-label="Get started"]');- return panel.scrollWidth <= panel.clientWidth && panel.getBoundingClientRect().right <= innerWidth;- }""")- console.save_evidence("embedded-onboarding-mobile")- console._browser.call(lambda: console._page.get_by_role("tab", name="Data", exact=True).click())- console.sees("Create dataset")- console.wait_until("() => !document.querySelector('[role=dialog]')")- console._browser.call(- lambda: console._page.get_by_role("tab", name="Agent", exact=True).click()- )- console.sees("Copy onboarding prompt")- console.healthy()---def test_activity_outcomes_and_setup_progress_survive_console_reload(- console, workshop, worker, rest_for-):- project = workshop.project()["id"]- workshop.call("list_datasets")- activity = workshop.read("overmind://activity")- assert {item["kind"] for item in activity["results"]} >= {- "agent_connected",- "repository_synced",- "capabilities_available",- }- before = activity["count"]- for _ in range(2):- workshop.call("list_datasets")- assert workshop.read("overmind://activity")["count"] == before-- console.goto(f"/?projectId={project}")- console.press("unread notification")- console.sees("connected to Overmind", exact=False)- workshop.call(- "create_eval_matrix_row",- {"name": "Visible activity check", "type": "llm", "source": "The answer is grounded."},- )- console.sees("added", exact=False)- console.sees("Visible activity check")- console.press("Mark read")- settle(worker, lambda: workshop.read("overmind://activity")["unseen_count"] == 0)-- console.goto(f"/?projectId={project}")- console.press("Notifications")- console.sees("Visible activity check")- console.click("Visible activity check")- console.wait_until("() => location.pathname.startsWith('/evaluations')")- console.press("Notifications")- console.wait_until("() => !document.body.textContent.includes('Setup progress')")- onboarding_run = str(uuid.uuid4())- progress = workshop.call(- "report_onboarding_progress", {"run_id": onboarding_run, "completed_steps": 2}- )- reporter = progress["milestones"][2]["actor_name"]- assert reporter- console.goto(f"/?projectId={project}")- console.sees("Onboarding · Inspect repository")- console.sees("2 of 10")- console._browser.call(- lambda: (- console._page.get_by_label("Onboarding status", exact=True)- .get_by_text(reporter, exact=True)- .wait_for()- )- )- workshop.call("report_onboarding_progress", {"run_id": onboarding_run, "completed_steps": 9})- console.sees("Onboarding · Instrument capabilities")- rest_for(workshop.api_key).request(- "POST",- "/api/v1/sync",- json={- "project_id": project,- "version": "1",- "capabilities": [- {- "slug": "onboarding-capability",- "name": "Onboarding capability",- "entrypoint_fn": "support.run",- }- ],- },- )- console.wait_until("""() => {- return [...document.querySelectorAll('h3')].some(node => node.textContent.includes('Onboarding capability')) && document.querySelector('[role=progressbar]')?.getAttribute('aria-valuenow') === '9' && !document.body.textContent.includes('Copy onboarding prompt');- }""")- console.save_evidence("activity-and-onboarding")- console._browser.call(console._page.set_viewport_size, {"width": 390, "height": 844})- console.wait_until("""() => {- const strip = document.querySelector('[aria-label="Onboarding status"]');- if (!strip) return false;- const rect = strip.getBoundingClientRect();- return rect.left >= 0 && rect.right <= innerWidth && strip.scrollWidth <= strip.clientWidth;- }""")- console.save_evidence("onboarding-mobile")- workshop.call("report_onboarding_progress", {"run_id": onboarding_run, "completed_steps": 10})- console.wait_until(- "() => !document.querySelector('[aria-label=\"Onboarding status\"]') && [...document.querySelectorAll('h3')].some(node => node.textContent.includes('Onboarding capability'))"- )- console.save_evidence("onboarding-complete-capabilities")---def test_agent_changes_update_visible_assets_without_reload(console, workshop):- project = workshop.project()["id"]- console.goto(f"/datasets?projectId={project}")- console.sees("Datasets", exact=False)- console._browser.call(console._page.evaluate, "window.activityDocument = 'unchanged'")- dataset = workshop.call(- "start_dataset",- {"name": "Live agent source", "brief": "Review live agent changes", "intent": "explore"},- )["dataset"]["id"]- console.sees("Live agent source")- console.wait_until(- "() => [...document.querySelectorAll('.activity-highlight')].some(row => row.textContent.includes('Live agent source'))"- )- workshop.call("update_dataset", {"dataset": dataset, "name": "Renamed live source"})- console.sees("Renamed live source")- console.wait_until(- "() => !document.body.textContent.includes('Live agent source') && window.activityDocument === 'unchanged'"- )- console.save_evidence("agent-live-asset-update")- console._browser.call(lambda: console._page.context.set_offline(True))- workshop.call("update_dataset", {"dataset": dataset, "name": "Reconnected live source"})- console._browser.call(lambda: console._page.context.set_offline(False))- console.sees("Reconnected live source")- console.wait_until("() => window.activityDocument === 'unchanged'")- console.press("unread notification")- console.sees("Reconnected live source", exact=False)- console.save_evidence("agent-live-notifications")---def test_dataset_inventory_follows_upload_bytes_and_publication(- console, workshop, rest_for, worker-):- project = workshop.project()["id"]- dataset = workshop.call(- "start_dataset", {"name": "Live upload", "brief": "Inspect uploaded rows"}- )["dataset"]["id"]- rest = rest_for(workshop.api_key)- console.goto(f"/datasets?projectId={project}")- console.sees("Waiting for source")- data = b'[{"value":1},{"value":2}]'- receipt = rest.request(- "POST",- "/api/dataset-transfers/",- json={- "project": project,- "dataset": dataset,- "request_key": "live-upload",- "filename": "rows.json",- "size": len(data),- "sha256": hashlib.sha256(data).hexdigest(),- },- )- console.sees("Uploading", exact=False)- rest.request(- "PUT",- f"/api/dataset-transfers/{receipt['id']}/chunk/?offset=0",- data=data[:10],- headers={"Content-Type": "application/octet-stream"},- )- console.wait_until(- "() => Number(document.querySelector('[role=progressbar]')?.getAttribute('aria-valuenow')) > 0"- )- console.save_evidence("dataset-upload-progress")- rest.request(- "PUT",- f"/api/dataset-transfers/{receipt['id']}/chunk/?offset=10",- data=data[10:],- headers={"Content-Type": "application/octet-stream"},- )- 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')"- )- console.save_evidence("dataset-upload-ready")---def test_evaluations_share_runs_navigation_and_probability_metrics(console, workshop):- project = workshop.project()["id"]- dataset = Dataset.objects.create(- project_id=project, name="Evaluation navigation fixture", intent="eval"- )- cell = Cell.objects.create(- dataset=dataset, state="ok", position=0, title="Final suite", rows=10- )- Cell.objects.create(dataset=dataset, state="ok", position=1, title="Later data", rows=999)- calibration_dataset = Dataset.objects.create(- project_id=project, name="Calibration navigation fixture", intent="eval"- )- calibration_cell = Cell.objects.create(- dataset=calibration_dataset, state="ok", position=0, title="Calibration suite", rows=3- )- EvalRun.objects.create(- project_id=project, dataset=dataset, name="Response evaluation fixture", status="completed"- )- metric = {"mean": 1.8, "decisions": 7, "groups": 5}- coverage = {- "expected": 10,- "scored": 7,- "missing_predictions": 1,- "invalid_predictions": 1,- "incompatible_inputs": 1,- "metrics": {"cross_entropy": metric},- }- plan = NativeEvaluationPlan.objects.create(- project_id=project,- final_cell=cell,- calibration_cell=calibration_cell,- name="Probability evaluation fixture",- state="completed",- config={- "baseline": "base",- "suites": {- "final": {"cell": str(cell.pk), "rows": 10},- "calibration": {"cell": str(calibration_cell.pk), "rows": 3},- },- "participants": [- {"key": "base", "name": "Base", "model": "Qwen/Qwen3-0.6B", "kind": "external"},- {- "key": "trained",- "name": "Trained",- "model": "Qwen/Qwen3-0.6B",- "kind": "external",- },- ],- },- calls={"score": {"state": "completed", "observed_at": timezone.now().isoformat()}},- results={- "comparisons": {- "trained": {- "raw": {- "baseline": {"benchmarks": {"Soft targets": coverage}},- "candidate": {"benchmarks": {"Soft targets": coverage}},- "benchmarks": {- "Soft targets": {- "metrics": {- "cross_entropy": {- "candidate_minus_baseline": -0.1,- "decisions": 7,- "groups": 5,- }- }- }- },- }- }- }- },- )- console.goto(f"/evaluations?projectId={project}&view=decisions")- console.sees("Response evaluation fixture")- console.sees("Probability evaluation fixture")- console.wait_until(- """() => ![...document.querySelectorAll('[role=tab]')].some(el => el.textContent === 'Decisions')"""- )- console.click("Response evaluation fixture")- console.sees("Re-run")- console.sees("Optimise")- console.goto(f"/evaluations?projectId={project}")- console.click("Probability evaluation fixture")- console.sees("Evaluation navigation fixture")- console.sees("Calibration navigation fixture")- console.wait_until(f"""() => {{- const details = document.querySelector('[aria-label="Run details"]');- return details && details.innerText.includes('Models')- && details.innerText.includes('Baseline')- && details.innerText.includes('10 rows')- && details.innerText.includes('3 rows')- && details.innerText.includes('Created')- && details.innerText.includes('Completed')- && !details.innerText.includes('999')- && !details.innerText.includes('Judge')- && [...details.querySelectorAll('a')].some(a =>- a.href.includes('/datasets/{dataset.id}') && a.href.includes('cell={cell.id}'));- }}""")- console.sees("Cross entropy")- console.sees("1.8000")- console.sees("7 / 10")- console._browser.call(- lambda: console._page.get_by_role("button", name="Trained: 7 / 10 scored").focus()- )- console.sees("1 missing · 1 invalid · 1 incompatible")- console.wait_until(f"() => location.pathname.endsWith('/runs/{plan.id}')")- console.wait_until("""() => document.querySelectorAll('table:not([aria-busy=true])').length === 1- && document.querySelector('[aria-label="Benchmark datapoints"]')- && !document.body.innerText.includes('Download all metrics')- && !document.body.innerText.includes('Frozen inputs, model identities and execution receipts')- && !document.body.innerText.includes('Calibration, class and slice diagnostics')- && !document.body.innerText.includes('Recorded costs and unreported components')- && !document.body.innerText.includes('Measure workload')- && getComputedStyle(document.querySelector('h1')).fontFamily.includes('Mondwest')- && getComputedStyle(document.querySelector('h2')).fontFamily.includes('Geist Pixel')""")- console.save_evidence("evaluation-probability-metrics")- console.goto(f"/evaluations?projectId={project}")- console.press("New evaluation")- console.click("Model probabilities")- console.sees("Final suite", exact=False)- console.sees("Calibration suite", exact=False)- console.sees("Baseline", exact=False)- console.sees("Save draft")- console.wait_until(- """() => getComputedStyle(document.querySelector('[role=dialog] h2')).fontFamily.includes('Geist Pixel')"""- )- assert not console.page_errors- assert not console.server_errors---def test_the_console_shows_the_synced_agent_and_its_traces(- console, cli, mcp_for, sample_agent, live_api, support_desk_llm, worker-):- cli.scan(sample_agent)- cli.sync(sample_agent)- project = mcp_for(cli.project_key(sample_agent)).project()["id"]- sample_agent.run("Refund order 42 please", api_url=live_api.url, llm_url=support_desk_llm)- drain(worker)-- console.goto(f"/capabilities?projectId={project}")- for truth in sample_agent.truth["capabilities"].values():- console.sees(truth["name"])-- console.goto(f"/observability?projectId={project}")- console.click("Signals")- console.sees("Signal checks")- console.click("Sessions")- console.click("Traces")- console.sees("handle_ticket")---def test_a_file_uploaded_in_the_console_becomes_a_usable_dataset(- console, cli, mcp_for, sample_agent, worker, tmp_path-):- cli.scan(sample_agent)- cli.sync(sample_agent)- mcp = mcp_for(cli.project_key(sample_agent))- project = mcp.project()["id"]-- console.goto(f"/datasets?projectId={project}")- console.command("New dataset")- 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.press("Create dataset")-- def landed():- for dataset in mcp.call("list_datasets", {})["datasets"]:- if dataset["name"] == "Console upload":- inspected = mcp.call("inspect_dataset", {"dataset": dataset["id"]})- return inspected if inspected["active"] else None- return None-- inspected = settle(worker, landed)- assert inspected["active"]["rows"] == 3- assert inspected["intent"] == "eval"---def test_a_console_brief_survives_its_first_cli_attachment(- console, workshop, cli, sample_agent, worker, tmp_path-):- project = workshop.project()["id"]- brief = "Classify refund requests; retain uncertain labels for review."- console.goto(f"/datasets?projectId={project}")- console.command("New dataset")- console.fill("#dataset-name", "Brief before data")- console.fill("#dataset-brief", brief)- console.press("Create dataset")-- def draft():- return next(- (- row- for row in workshop.call("list_datasets", {})["datasets"]- if row["name"] == "Brief before data"- ),- None,- )-- dataset = settle(worker, draft)["id"]- before = workshop.call("inspect_dataset", {"dataset": dataset})- assert before["brief"] == brief and before["active"] is None- assert upload(cli, sample_agent, tickets(tmp_path), "--dataset", dataset) == dataset- drain(worker)- after = workshop.call("inspect_dataset", {"dataset": dataset})- assert after["brief"] == brief- assert after["active"]["rows"] == 3- assert after["intent"] == before["intent"]- console.goto(f"/datasets/{dataset}?projectId={project}")- console.sees("Brief before data")- console.sees("Refund order 0 please", exact=False)---def test_decision_data_selects_native_training_controls(- console, workshop, cli, sample_agent, worker, tmp_path, rest_for-):- project = workshop.project()["id"]- path = tmp_path / "decision.jsonl"- path.write_text(- "".join(- json.dumps(- {- "decision": {- "state": f"Refund request {i}",- "question": "Approve refund?",- "kind": "noul",- "options": ["No", "Yes"],- "target_probabilities": [0.25, 0.75],- "target_semantics": "annotator_distribution",- }- }- )- + "\n"- for i in range(12)- )- )- dataset = upload(cli, sample_agent, path, "--intent", "train")- drain(worker)- recommendation = rest_for(cli.project_key(sample_agent)).request(- "POST", "/api/finetuning-jobs/recommend/", json={"dataset_id": dataset}- )- readiness = workshop.call("check_finetune_readiness", {"dataset": dataset})- assert recommendation["task_type"] == readiness["task_type"] == "unknown"- assert recommendation["task_type_source"] == readiness["task_type_source"] == "unknown"- assert recommendation["dataset"]["rows"] == 12- assert recommendation["benchmark_snapshot"]["generated_at"] is None- assert recommendation["candidates"] == readiness["recommendations"] == []- assert readiness["dataset"]["validation"]["valid"] and readiness["n_candidates"] > 0- DatasetContext.objects.update_or_create(- dataset_id=dataset,- defaults={- "project_id": project,- "task_type": "classification",- "task_type_source": "semantic",- "extracted_at": timezone.now(),- },- )- recommendation = rest_for(cli.project_key(sample_agent)).request(- "POST", "/api/finetuning-jobs/recommend/", json={"dataset_id": dataset}- )- readiness = workshop.call("check_finetune_readiness", {"dataset": dataset})- assert recommendation["task_type"] == readiness["task_type"] == "classification"- assert readiness["training_contract"]["inference_contract"] == "decision"- assert "Qwen/Qwen3-0.6B" in {model for tier in readiness["catalog"].values() for model in tier}- assert "google/gemma-4-31B-it" not in {- model for tier in readiness["catalog"].values() for model in tier- }- console.goto(f"/training?projectId={project}&train=true&datasetId={dataset}")- console.sees("Choose training data, model and evaluations.")- console.wait_until("""() => document.querySelector(- '[aria-label="Run pre-training baseline evaluation"]')?.getAttribute('data-state') === 'checked'""")- console.sees("Measure base-model performance before training.")- console.sees("Native probability training · Modal LoRA")- console.sees("Training mode")- console.sees("Decision", exact=True)- console.sees("Classification", exact=True)- console.sees("No benchmark data", exact=False)- console.wait_until("""() => !document.body.innerText.includes("Can't be trained on yet")- && !document.body.innerText.includes("Validating")""")- assert not FinetuningJob.objects.filter(project_id=project).exists()---def test_api_key_remains_private_in_session_replay(console, workshop, replay_recorder):- project = workshop.project()["id"]- console.goto(f"/projects/{project}?projectId={project}")- console.press("New API key")- console._browser.call(lambda: console._page.add_script_tag(path=str(replay_recorder)))- console._browser.call(- console._page.evaluate,- """() => {- window.replayEvents = [];- window.stopReplay = ReplayRecorder.record({- emit: event => window.replayEvents.push(event),- blockClass: 'ph-no-capture', maskTextClass: 'ph-mask', maskAllInputs: true- });- }""",- )- console.press("Create API key")- console.sees("Your new API key:")- console.wait_until("() => window.replayEvents.some(event => event.type === 3)")- leaked = console._browser.call(- console._page.evaluate,- """() => {- ReplayRecorder.record.takeFullSnapshot();- const key = document.querySelector('[role="dialog"] code').textContent;- const leaked = JSON.stringify(window.replayEvents).includes(key);- window.stopReplay();- return leaked;- }""",- )- console.press("Done")- console.wait_until("() => !document.querySelector('[role=\"dialog\"]')")- console.save_evidence("api-key-replay-privacy")- assert leaked is False, "Session replay captured the API key"---def test_native_monitoring_evidence_remains_readable_after_cancellation(console, workshop):- project = workshop.project()["id"]- group = uuid.uuid4()- job = FinetuningJob.objects.create(- project_id=project,- dataset=Dataset.objects.create(project_id=project, name="Decision receipts"),- base_model="Qwen/Qwen3-0.6B",- status="running",- group_id=group,- hyperparameters={"objective": "decision_cross_entropy"},- progress={"activity": [{"ts": 1, "message": "Booting and verifying"}]},- )- examples = [- {- "row": 0,- "input": "Refund order 42",- "reference": [0.25, 0.75],- "output": [0.2, 0.8],- "status": "completed",- }- ]- training_monitoring.ingest(- job,- {- "checks": [- {- "key": "1:development:4",- "attempt": 1,- "stream": "development",- "step": 4,- "state": "completed",- "policy_fingerprint": "a" * 64,- "sample_fingerprint": "b" * 64,- "coverage": {"scored": 4, "expected": 4},- "metrics": {- "eval_loss": 0.625,- "hard_label_accuracy": 0.75,- "distribution_decisions": 4,- "mean_decisions": 0,- "cross_entropy": 0.625,- "brier": 0.125,- },- "artifact": {"sha256": fingerprint(examples), "examples": examples},- }- ]- },- )- console.goto(f"/training?projectId={project}&groupId={group}&jobId={job.pk}")- console.sees("Development loss")- console.sees("0.6250")- console.sees("Running — Booting and verifying")- check = job.validation_runs.get()- evidence = workshop.call(- "inspect_training_progress", {"job": str(job.pk), "check": str(check.pk)}- )- assert evidence["progress"]["items"] == examples- console.press("Cancel")- console.sees("Requests cancellation. Completed checks and saved checkpoints remain available.")- console.press("Cancel Job")- console.sees("Cancelled")- console.wait_until("() => !document.body.innerText.includes('Booting and verifying')")- job.refresh_from_db()- assert job.status == "cancelled"- console.goto(f"/training?projectId={project}&groupId={group}&jobId={job.pk}")- console.sees("Development loss")- console.sees("0.6250")- assert (- workshop.call("inspect_training_progress", {"job": str(job.pk), "check": str(check.pk)})[- "progress"- ]["items"]- == examples- )---def test_project_surfaces_render_without_browser_or_server_errors(console, workshop):- project = workshop.project()["id"]- for route, text in [- ("datasets", "Datasets"),- ("training", "Train model"),- ("evaluations", "Evaluations"),- ("inference", "Inference"),- ("optimiser", "Optimiser"),- ]:- console.goto(f"/{route}?projectId={project}")- console.sees(text)- console.healthy()- console.save_evidence(f"project-surface-{route}")---def test_decision_deployment_without_training_data_never_invents_an_example(console, workshop):- project = workshop.project()["id"]- deployed = DeployedModel.objects.create(- project_id=project,- model_id="ft-titanic-decision",- base_model_id="Qwen/Qwen3.5-0.8B",- status="ready",- inference_contract="decision",- max_model_len=4096,- gpu_type="H100",- quantization="bf16",- )- console.goto(f"/inference/{deployed.pk}?projectId={project}")- console.sees(deployed.model_id)- console.press("Serverless API snippet")- console.sees("TypeSafe systemone. Point the SDK base URL at this API.")- console.sees(- "A complete example input is unavailable for this model’s pinned training version."- )- console.wait_until(- "() => !document.querySelector('[role=dialog]').innerText.includes('/chat/completions')"- )- console.wait_until(- "() => !document.querySelector('[role=dialog]').innerText.includes('Use live alias')"- )- console.wait_until(- "() => getComputedStyle(document.querySelector('[role=dialog]')).opacity === '1'"- )- console.healthy()- console.save_evidence("decision-inference-snippet")---def test_data_onboarding_uploads_once_and_hands_off_training_preparation(console, tmp_path):- console.goto("/projects")- console.press("New project")- console._browser.call(- lambda: console._page.get_by_label("Project name", exact=True).fill(- "Training onboarding fixture"- )- )- console.upload('input[type="file"]', tickets(tmp_path))- console.sees("3 rows")- console.wait_until(- "() => document.querySelector('[role=dialog]').getAnimations().every(a => a.playState !== 'running')"- )- console.save_evidence("data-onboarding-upload")- console.press("Create dataset")- console.sees("Prepare your training data")- dataset = Dataset.objects.get(name="Training onboarding fixture")- assert dataset.intent == "train"- assert dataset.brief == (- "Explore the uploaded data and determine how best to prepare it for training."- )- assert dataset.capability_id is None- console.wait_until(f"() => location.pathname.includes('/datasets/{dataset.id}')")- console._browser.call(- lambda: console._page.evaluate("""() => {- window.copiedOnboardingPrompt = '';- navigator.clipboard.write = async items => {- window.copiedOnboardingPrompt = await (await items[0].getType('text/plain')).text();- };- navigator.clipboard.writeText = async text => { window.copiedOnboardingPrompt = text; };- }""")- )- console.press("Copy onboarding prompt")- console.wait_until("() => window.copiedOnboardingPrompt.length > 0")- prompt = console._browser.call(lambda: console._page.evaluate("window.copiedOnboardingPrompt"))- assert prompt.startswith(- f"Set me up on Overmind with my uploaded data\n(project_id: {dataset.project_id},\ndataset_id: {dataset.id})"- )- assert prompt.endswith("/setup.md")- assert "api-key" not in prompt.lower()- console.save_evidence("data-onboarding-handoff")- console._browser.call(lambda: console._page.set_viewport_size({"width": 390, "height": 844}))- console.wait_until(- "() => document.querySelector('[role=dialog]').getAnimations().every(a => a.playState !== 'running')"- )- bounds = console._browser.call(- lambda: console._page.evaluate("""() => {- const d = document.querySelector('[role=dialog]'); const r = d.getBoundingClientRect();- return {left:r.left, right:r.right, viewport:innerWidth, width:getComputedStyle(d).width, maxWidth:getComputedStyle(d).maxWidth, translate:getComputedStyle(d).translate, transform:getComputedStyle(d).transform};- }""")- )- assert bounds["left"] >= 0 and bounds["right"] <= bounds["viewport"], bounds- console.save_evidence("data-onboarding-handoff-mobile")- console._browser.call(- lambda: (- console._page.get_by_role("dialog")- .get_by_role("button", name="Close", exact=True)- .last.click()- )- )- console.wait_until("() => !location.search.includes('prepare=')")- console.sees("Training onboarding fixture")- console.healthy()---def test_empty_dataset_inventory_onboards_into_the_selected_project(console, workshop, tmp_path):- project = workshop.project()["id"]- console.goto(f"/datasets?projectId={project}")- console.sees("Get started with data")- console.upload('input[type="file"]', tickets(tmp_path))- console.sees("3 rows")- console.save_evidence("dataset-empty-onboarding")- console.press("Create dataset")- console.sees("Prepare your training data")- dataset = Dataset.objects.get(project_id=project)- console.wait_until(f"() => location.pathname.includes('/datasets/{dataset.id}')")- console.goto(f"/datasets?projectId={project}&ds_search=no-matching-dataset")- console.wait_until("() => !document.body.textContent.includes('Get started with data')")- console.healthy()---def test_dataset_role_filter_uses_recorded_outputs(console, workshop):- project = workshop.project()["id"]- source = Dataset.objects.create(project_id=project, name="Raw evidence", intent="explore")- source_cell = Cell.objects.create(dataset=source, position=0, state="ok", fingerprint="a" * 64)- raw = Dataset.objects.create(project_id=project, name="Unused source", intent="explore")- Cell.objects.create(dataset=raw, position=0, state="ok", fingerprint="c" * 64)- output = Dataset.objects.create(project_id=project, name="Shared output", intent="explore")- output_cell = Cell.objects.create(dataset=output, position=1, state="ok", fingerprint="b" * 64)- Dataset.objects.create(project_id=project, name="Training by name only", intent="train")- plan = DataPartitionPlan.objects.create(- project_id=project,- name="Recorded roles",- request_key="inventory-roles",- source_cell=source_cell,- source_fingerprint=source_cell.fingerprint,- state="completed",- )- for role in ("train", "calibration", "final", "development"):- DataPartitionMember.objects.create(plan=plan, role=role, cell=output_cell)- console.goto(f"/datasets?projectId={project}")- console.sees("Raw evidence")- console.wait_until("() => !document.body.textContent.includes('Shared output')")- for label in ("Training", "Calibration", "Evaluation", "Development"):- console.choose('[aria-label="Filter by role"]', label)- console.sees("Raw evidence")- console.wait_until(- "() => !document.body.textContent.includes('Training by name only') && !document.body.textContent.includes('Unused source')"- )- console.save_evidence("dataset-multiple-roles")- console.choose('[aria-label="Filter by role"]', "Source")- console.sees("Unused source")- console.wait_until("() => !document.body.textContent.includes('Shared output')")- console.choose('[aria-label="Filter by role"]', "Unassigned")- console.sees("Training by name only")- console.wait_until(- "() => !document.body.textContent.includes('Shared output') && !document.body.textContent.includes('Raw evidence')"- )- console.save_evidence("dataset-unassigned-role")- console.goto(f"/datasets/{output.pk}?projectId={project}")- console.sees("Shared output", exact=False)---def test_activity_connects_pipeline_sequence(console, workshop):- project = workshop.project()["id"]- dataset = Dataset.objects.create(project_id=project, name="Connected work")- source = Cell.objects.create(dataset=dataset, position=0, state="ok", fingerprint="a" * 64)- pipeline = DatasetPipeline.objects.create(- project_id=project, name="Features", request_key="features"- )- for key, kind, action in (- ("upload", "source_uploaded", "Uploaded source"),- ("import", "source_ready", "Source ready"),- ("save", "asset_changed", "Saved a transformation for"),- ):- activity_service.record(- key=key,- project_id=project,- kind=kind,- action=action,- assets=[activity_service.asset("dataset", dataset.pk, dataset.name)],- )- activity_service.record(- key="unrelated-edit",- project_id=project,- kind="asset_changed",- action="Updated dataset",- assets=[activity_service.asset("dataset", dataset.pk, dataset.name)],- )- for index in range(2):- run = DatasetPipelineRun.objects.create(- dataset=dataset,- source=source,- pipeline=pipeline,- request_key=f"sequence-{index}",- state="completed",- )- activity_service.record(- key=f"sequence-{index}",- project_id=project,- kind="task_requested",- action="Requested a transformation of",- actor_kind="codex",- actor_name="Codex",- task_kind="dataset_pipeline",- task_id=run.pk,- assets=[activity_service.asset("dataset", dataset.pk, dataset.name)],- )- records = workshop.read("overmind://activity")["results"]- linked = [item for item in records if item["sequence_key"]]- assert len(linked) == 5- assert len({item["sequence_key"] for item in linked}) == 1- assert linked[0]["sequence_key"]- assert all(not item["sequence_key"] for item in records if item["action"] == "Updated dataset")- console.goto(f"/datasets?projectId={project}")- console.press("unread notification")- console.wait_until("() => document.querySelectorAll('[data-sequence-key]').length === 5")- console.save_evidence("connected-pipeline-events")---def test_dataset_preparation_persists_between_jobs_until_agent_finishes(- console, workshop, cli, sample_agent, worker, tmp_path-):- project = workshop.project()["id"]- dataset = workshop.call(- "start_dataset",- {"name": "Continuous preparation", "brief": "Prepare support rows", "intent": "train"},- )["dataset"]["id"]- console.goto(f"/datasets?projectId={project}")- console.sees("Continuous preparation")- args = {"dataset": dataset, "request_key": "continuous-preparation"}- started = workshop.call("start_dataset_preparation", args)["preparation_workflow"]- assert (- workshop.call("start_dataset_preparation", args)["preparation_workflow"]["id"]- == started["id"]- )- console.sees("Preparing")- workflow = {"dataset": dataset, "preparation_id": started["id"]}- assert workshop.call_result(- "update_dataset_preparation", {**workflow, "state": "completed"}- ).isError- assert workshop.call_result(- "start_dataset_preparation", {**args, "request_key": "another"}- ).isError- upload(cli, sample_agent, tickets(tmp_path), "--dataset", dataset)- drain(worker)- source = workshop.call("inspect_dataset", {"dataset": dataset})["active"]- console.sees("Preparing")- result = workshop.call(- "import_dataset_version",- {- "dataset": dataset,- "source_cell": source["id"],- "source_fingerprint": source["fingerprint"],- "name": "Prepared support",- "request_key": "continuous-import",- "provenance": "Journey creates source-bound support messages",- "imported_rows": [- {- "source_row": i,- "messages": [- {"role": "user", "content": f"Refund order {i}"},- {"role": "assistant", "content": "Your refund is ready."},- ],- }- for i in range(3)- ],- },- )- drain(worker)- receipt = workshop.call("get_job", {"kind": "dataset_pipeline", "id": result["job"]["id"]})- assert receipt["status"] == "completed", receipt- console.sees("Preparing")- current = workshop.call("inspect_dataset_workbench", {"dataset": dataset})[- "preparation_workflow"- ]- assert current["state"] == "preparing"- events = workshop.read("overmind://activity")["results"]- preparation_events = [e for e in events if e["kind"] == "dataset_preparation"]- assert len(preparation_events) == 1- event_id = preparation_events[0]["id"]- assert not [e for e in events if e["task_kind"] == "dataset_pipeline"]- workshop.call("update_dataset_preparation", {**workflow, "state": "paused"})- console.sees("Preparation paused")- workshop.call("update_dataset_preparation", {**workflow, "state": "preparing"})- console.sees("Preparing")- console.press("unread notification")- console.wait_until(- f"() => document.querySelector('[data-activity-id=\"{event_id}\"]')?.dataset.activityStatus === 'running'"- )- console.wait_until(- "() => document.getAnimations().every(a => a.effect?.getTiming().iterations === Infinity || a.playState !== 'running')"- )- console.save_evidence("dataset-preparation-active")- output = workshop.call("inspect_dataset", {"dataset": dataset})["active"]["id"]- completion = {**workflow, "state": "completed", "outputs": [output]}- workshop.call("update_dataset_preparation", completion)- workshop.call("update_dataset_preparation", completion)- console.wait_until(- f"() => document.querySelector('[data-activity-id=\"{event_id}\"]')?.dataset.activityStatus === 'completed'"- )- console.sees("Ready")- console.save_evidence("dataset-preparation-completed")- assert workshop.call_result(- "update_dataset_preparation", {**workflow, "state": "preparing"}- ).isError- console.healthy()---def test_console_ends_an_open_preparation_and_idle_preparations_expire(console, workshop):- project = workshop.project()["id"]- datasets = [- workshop.call(- "start_dataset", {"name": name, "brief": "Prepare support rows", "intent": "train"}- )["dataset"]["id"]- for name in ("Abandoned preparation", "Idle preparation", "Recently active preparation")- ]- for dataset in datasets:- workshop.call(- "start_dataset_preparation", {"dataset": dataset, "request_key": f"open-{dataset}"}- )- console.goto(f"/datasets/{datasets[0]}?projectId={project}")- console.sees("Preparing")- console.press("End preparation")- console.wait_until("() => !document.body.textContent.includes('End preparation')")- ended = workshop.call("inspect_dataset_workbench", {"dataset": datasets[0]})- assert ended["preparation_workflow"]["state"] == "cancelled"-- idle = DatasetPreparation.objects.get(dataset_id=datasets[1])- active = DatasetPreparation.objects.get(dataset_id=datasets[2])- stale = timezone.now() - timedelta(hours=25)- DatasetPreparation.objects.filter(pk__in=[idle.pk, active.pk]).update(updated_at=stale)- Activity.objects.filter(key=f"preparation:{idle.pk}").update(updated_at=stale)- assert reap_stuck_runs()["preparations_expired"] == 1- kept = workshop.call("inspect_dataset_workbench", {"dataset": datasets[2]})- assert kept["preparation_workflow"]["state"] == "preparing"- expired = workshop.call("inspect_dataset_workbench", {"dataset": datasets[1]})- assert expired["preparation_workflow"]["state"] == "cancelled"- restarted = workshop.call(- "start_dataset_preparation", {"dataset": datasets[1], "request_key": "after-expiry"}- )- assert restarted["preparation_workflow"]["state"] == "preparing"- console.healthy()---def test_evaluation_scope_link_settles_on_trajectory_and_supports_repeat_clicks(console, workshop):- project = workshop.project()["id"]- console.goto(f"/evaluations?projectId={project}&view=matrix")- link = console._page.locator('a[href*="trajectoryNode="]').first- console._browser.call(link.wait_for)- href = console._browser.call(link.get_attribute, "href")- console._browser.call(link.click)- focused = """() => {- const target = new URL(location.href).searchParams.get('trajectoryNode');- const node = [...document.querySelectorAll('.react-flow__node.selected')].find(n => n.dataset.id === target);- const canvas = document.querySelector('[aria-label="Capability trajectory map"]');- if (!node || !canvas) return false;- const n = node.getBoundingClientRect(), c = canvas.getBoundingClientRect();- return n.width >= 180 && n.left >= c.left && n.right <= c.right &&- n.top >= Math.max(c.top, 64) && n.bottom <= Math.min(c.bottom, innerHeight);- }"""- console.wait_until(focused)- console._browser.call(console._page.locator(f'a[href="{href}"]').first.click)- console.wait_until(focused)- stable = console._browser.call(- console._page.evaluate,- """async () => {- const positions = [];- for (let i = 0; i < 60; i++) {- await new Promise(requestAnimationFrame);- const r = document.querySelector('.react-flow__node.selected').getBoundingClientRect();- positions.push([r.x, r.y, r.width]);- }- const last = positions.slice(-10);- return last.every(p => p.every((v, i) => Math.abs(v - last[0][i]) < 1));- }""",- )- assert stable- console.save_evidence("evaluation-scope-focus")- console.healthy()---def test_dedicated_startup_updates_and_keeps_configuration_after_stop(console, workshop):- project = workshop.project()["id"]- deployed = DeployedModel.objects.create(- project_id=project,- model_id="ft-dedicated-startup",- status="ready",- base_model_id="meta-llama/Llama-3.2-3B-Instruct",- gpu_type="H100",- )- row = DedicatedDeployment.objects.create(- project_id=project,- deployed_model=deployed,- gpu_type="H100",- status="warming",- min_replicas=2,- max_replicas=3,- rate_usd_per_gpu_hour=4,- credits_per_gpu_hour=400,- probe_call_id="fc-console-startup",- )- run = OperationalRun.objects.create(- project_id=project,- kind="dedicated_deployment",- reference=str(row.pk),- attempt=row.probe_call_id,- snapshot={"stage": "loading_weights"},- provider_state={- "available": True,- "current": {"message": "Loading model weights"},- "logs": [- {- "stage": "loading_weights",- "message": "Loading model weights",- "at": timezone.now().isoformat(),- "worker": "ta-console",- "completed": 1,- "total": 2,- "unit": "tensors",- }- ],- },- )- console.goto(f"/inference/{deployed.pk}?projectId={project}")- console.sees("Loading model weights")- console.wait_until("() => !document.body.innerText.includes('Startup logs')")- console.wait_until("""() => {- const bar = document.querySelector('[role=progressbar][aria-label="Startup stages"]');- const title = document.querySelector('[aria-label="Dedicated endpoint"] h2');- const controls = document.querySelector('[aria-label="GPU controls"]');- if (!bar || bar.children.length < 2) return false;- const b = bar.getBoundingClientRect(), t = title.getBoundingClientRect(), c = controls.getBoundingClientRect();- return b.left > t.right && b.right < c.left && Math.abs(b.y - t.y) < 12;- }""")- console.save_evidence("dedicated-startup-header")- run.snapshot = {"stage": "capturing_graphs"}- run.provider_state["current"] = {"message": "Capturing CUDA graphs"}- run.save()- console.sees("Capturing CUDA graphs")- DedicatedDeployment.objects.filter(pk=row.pk).update(status="online", running_replicas=2)- console.sees("Online")- console.wait_until(- """() => !document.querySelector('[role=progressbar][aria-label="Startup stages"]') && !document.body.innerText.includes('Startup logs')"""- )- console.save_evidence("dedicated-online")- DedicatedDeployment.objects.filter(pk=row.pk).update(status="offline", running_replicas=0)- console.sees("Offline")- console.sees("0 running · 2–3 configured")- console.press("Dedicated API snippet")- console.sees("Call this model")- console.wait_until(- "() => document.querySelector('[role=dialog]').innerText.includes('dedicated/ft-dedicated-startup')"- )- console.save_evidence("dedicated-offline-snippet")- console.press("Close")- console.press("Configure GPU")- console.sees("Dedicated GPU")- console.wait_until("""() => {- const dialog = document.querySelector('[role=dialog]');- return dialog && dialog.querySelector('#dedicated-min-replicas')?.value === '2';- }""")- console.save_evidence("dedicated-configuration-dialog")- console.healthy()diff --git a/tests/journeys/console/test_model_handoff.py b/tests/journeys/console/test_model_handoff.pydeleted file mode 100644index c3abe9ab..00000000--- a/tests/journeys/console/test_model_handoff.py+++ /dev/null@@ -1,42 +0,0 @@-import uuid--from overbae.models import Dataset, DeployedModel, FinetuningJob---def test_standalone_trained_model_copies_its_setup_prompt(console, rest_for, account_key, mcp_for):- project = rest_for(account_key).request(- "POST", "/api/projects/", json={"name": "Standalone model", "slug": "standalone-model"}- )["id"]- group = uuid.uuid4()- job = FinetuningJob.objects.create(- project_id=project,- dataset=Dataset.objects.create(project_id=project, name="Standalone training data"),- base_model="Qwen/Qwen2.5-14B-Instruct",- status="succeeded",- group_id=group,- output_model_name="ft-standalone-browser",- )- model = DeployedModel.objects.create(- project_id=project,- finetuning_job=job,- model_id="ft-standalone-browser",- status="ready",- max_model_len=8192,- )- console._browser.call(- console._page.context.grant_permissions, ["clipboard-read", "clipboard-write"]- )- console._browser.call(console._page.evaluate, "navigator.clipboard.writeText('')")- console.goto(f"/training?projectId={project}&groupId={group}&jobId={job.id}")- console.press("Copy a prompt switching to ft-standalone-browser")- console.sees("Prompt copied")- console.save_evidence("standalone-model-setup-prompt")- prompt = console._browser.call(console._page.evaluate, "navigator.clipboard.readText()")- assert model.model_id in prompt- result = mcp_for(account_key).call(- "get_model_swap_prompt", {"project_id": project, "finetune": str(job.id)}- )- assert model.model_id in result["prompt"]- assert result["pin"] is True- assert result["capability_id"] is None- assert len(result["resource_links"]) == 1diff --git a/tests/journeys/console/test_native_benchmark_monitor.py b/tests/journeys/console/test_native_benchmark_monitor.pydeleted file mode 100644index 08a35fe8..00000000--- a/tests/journeys/console/test_native_benchmark_monitor.py+++ /dev/null@@ -1,720 +0,0 @@-import hashlib-import json-import math-import time-from urllib.parse import urlencode--import pytest-from factories import make_project--from overbae.models import Dataset, NativeEvaluationPlan-from overbae.services import native_evaluation-from overbae.services.datasets import land-from overbae.services.decision_benchmark_scoring import records--from ..conftest import RUNS-from ..stack import settle--[email protected]("participant_count", [1, 3, 6])-def test_native_benchmark_progress_samples_and_completed_backfill(- console, account, rest_for, mcp_for, fake_modal, worker, settings, tmp_path, participant_count-):- settings.MEDIA_ROOT = tmp_path- user, key = account- project = make_project("Titanic comparison", member=user)- dataset = Dataset.objects.create(- project=project, name="Frozen passenger final suite", intent="eval"- )- data = [- {- "input": {- "decision": {- "state": f"Passenger {index}; age 32; class 2",- "question": "Will this passenger survive?",- "kind": "choice",- "options": ["Survived", "Did not survive"],- }- },- "expected_output": {- "probabilities": [0.7, 0.3] if index == 1 else ([0, 1] if index % 2 else [1, 0])- },- "benchmark": "Survival",- "group": str(index),- }- for index in range(27)- ]- data.append(- {- "input": {- "decision": {- "state": "Passenger 27",- "question": "Estimate the score",- "kind": "score",- "options": ["Low", "High"],- }- },- "expected_output": {"mean": 7, "values": [0, 10]},- "benchmark": "Ordinal score",- }- )- land.land_rows(dataset, data)- dataset.refresh_from_db()- cell = dataset.active_cell- arms = [- {- "key": arm,- "name": name,- "kind": "foundation",- "model": model,- }- for arm, name, model in (- ("small", "Qwen 3.5 0.8B", "Qwen/Qwen3.5-0.8B"),- ("medium", "Qwen 3.5 2B", "Qwen/Qwen3.5-2B"),- ("large", "Qwen 3.5 4B", "Qwen/Qwen3.5-4B"),- ("input", "Titanic survival decision model foundation checkpoint", "Qwen/Qwen3-0.6B"),- ("qwen3", "Qwen 3 1.7B foundation", "Qwen/Qwen3-1.7B"),- ("llama", "Llama 3.2 1B Instruct", "meta-llama/Llama-3.2-1B-Instruct"),- )[:participant_count]- ]- plan = NativeEvaluationPlan.objects.create(- project=project,- final_cell=cell,- name="Titanic live benchmark",- state="queued",- config={- "participants": arms,- "baseline": "small",- "suites": {- "final": {- "cell": str(cell.pk),- "dataset": str(dataset.pk),- "fingerprint": cell.fingerprint,- "rows": cell.rows,- }- },- "runtime": native_evaluation.runtime(),- "seed": 123,- "bootstrap_samples": 2,- "logarithm_floor": 1e-12,- "contamination_limits": "Fixture inputs only",- "inference": {},- },- )- native_evaluation.advance(plan.pk, stage="verify_inputs")- plan.refresh_from_db()- source = native_evaluation.directory(plan, "final")- inputs = list(records(source / "inputs.jsonl"))- assert len(inputs) == 28- input_sha = hashlib.sha256((source / "inputs.jsonl").read_bytes()).hexdigest()- calls = {}- roots = {}- manifests = {}- payloads = {}- for arm in arms:- name = arm["key"]- stage = f"final_{name}"- _, _, _, group = native_evaluation.provider_stage(plan, stage)- call = fake_modal.adopt(f"fc-monitor-{name}", "predict")- calls[name] = call- roots[name] = f"/decision-evaluations/{plan.pk}-final" + (- "" if group == "prepare" else f"-{group}"- )- plan.calls[f"final_{group}"] = {- "state": "completed",- "receipt": {- "artifact_identity": name,- "input_sha256": input_sha,- "ready_decisions": len(inputs),- },- }- plan.calls[stage] = {"state": "running", "id": call.object_id}- payloads[name] = [- {- "key": row["key"],- "input_sha256": row["input_sha256"],- "kind": row["decision"]["kind"],- "model_identity": name,- "probabilities": [0.8, 0.2],- "log_probabilities": [math.log(0.8), math.log(0.2)],- }- for row in inputs- ]- for index in range(2, 27):- probabilities = (- [0.5, 0.5]- if name == "small" and index == 2- else [0.1, 0.9]- if name == "medium"- else [0.501, 0.499]- if name == "large"- else [0.8, 0.2]- )- payloads[name][index].update(- probabilities=probabilities,- log_probabilities=[math.log(value) for value in probabilities],- )- manifests[name] = {- "call_id": call.object_id,- "artifact_identity": name,- "input_sha256": input_sha,- "runtime_fingerprint": plan.config["runtime"]["training"],- "expected": len(inputs),- "completed": 0,- "stage": "loading_model",- "source_at": time.time(),- "last_progress_at": time.time(),- "chunks": [],- }- fake_modal.files[f"{roots[name]}/progress/{call.object_id}/manifest.json"] = json.dumps(- manifests[name]- ).encode()- plan.save()- for arm in arms:- native_evaluation.advance(plan.pk, stage=f"final_{arm['key']}")-- rest = rest_for(key)- mcp = mcp_for(key)- endpoint = f"/api/native-evaluations/{plan.pk}/monitor/"- initial = rest.request("GET", endpoint)- assert initial["count"] == 28- assert all(arm["scored"] == 0 for arm in initial["arms"])- assert initial["samples"][0]["key"] == "0"- console.goto(f"/evaluations/runs/{plan.pk}?projectId={project.pk}&format=decision")- console.sees("Loading model")- console.sees("0 / 28")-- def publish(arm, rows, *, corrupt=False):- manifest = manifests[arm]- index = len(manifest["chunks"])- body = "".join(json.dumps(row) + "\n" for row in rows).encode()- manifest["chunks"].append({"sha256": hashlib.sha256(body).hexdigest(), "rows": len(rows)})- manifest.update(- completed=manifest["completed"] + len(rows),- stage="predicting",- source_at=time.time(),- last_progress_at=time.time(),- )- root = f"{roots[arm]}/progress/{calls[arm].object_id}"- fake_modal.files[f"{root}/{index}.jsonl"] = b"corrupt" if corrupt else body- fake_modal.files[root + "/manifest.json"] = json.dumps(manifest).encode()- native_evaluation.advance(plan.pk, stage=f"final_{arm}")- return root, body-- publish("small", payloads["small"][:2])- partial = rest.request("GET", endpoint)- assert partial["arms"][0]["scored"] == 2, [- (s["key"], s["error"], s["predictions"].get("small", {}).get("error"))- for s in partial["samples"][:2]- ]- assert partial["arms"][0]["benchmarks"][1]["raw"]["accuracy"]["decisions"] == 1- assert "medium" not in partial["samples"][0]["predictions"]- assert rest.request("GET", endpoint + "?outcome=missing&participant=small")["count"] == 26- assert rest.request("GET", endpoint + "?outcome=missing")["count"] == (- 28 if participant_count > 1 else 26- )- native_evaluation.advance(plan.pk, stage="final_small")- assert rest.request("GET", endpoint)["arms"][0]["scored"] == 2- observed = mcp.call(- "inspect_native_evaluation",- {"project_id": str(project.pk), "evaluation": str(plan.pk), "key": "0", "limit": 1},- )["monitoring"]- assert observed["provisional"] and observed["samples"][0]["input"]["options"] == [- "Survived",- "Did not survive",- ]- assert observed["samples"][0]["predictions"]["small"]["raw"]["probabilities"] == [0.8, 0.2]- console.sees("2 / 28")- console._browser.call(console._page.set_viewport_size, {"width": 1440, "height": 1100})- console.wait_until("""() => {- const table = document.querySelector('[aria-label="Benchmark datapoints"] [role=grid]');- const rows = [...table.querySelectorAll('tbody tr')];- const heights = rows.map(row => row.getBoundingClientRect().height);- return rows.length === 25 && rows.filter(row => row.tabIndex === 0).length === 1- && Math.max(...heights) <= 40- && Math.max(...heights) - Math.min(...heights) <= 1;- }""")- console.wait_until("""() => {- const rows = document.querySelectorAll('[aria-label="Benchmark datapoints"] tbody tr');- return rows[0].querySelector('[aria-label="Correct: Survived. Probability 80.0%"] [data-slot=badge]')- ?.classList.contains('text-success')- && rows[1].querySelector('[aria-label="Reference: Soft target"]')- && rows[1].querySelector('[aria-label="Prediction: Survived. Probability 80.0%"] [data-slot=badge]')- ?.classList.contains('text-muted-foreground')- && !rows[1].querySelector('.text-success, .text-destructive');- }""")- console._browser.call(- lambda: console._page.get_by_role(- "region", name="Benchmark datapoints"- ).scroll_into_view_if_needed()- )- console.save_evidence(f"native-datapoints-{participant_count}-desktop")- console._browser.call(- lambda: console._page.get_by_role("region", name="Benchmark datapoints").screenshot(- path=str(RUNS / f"native-datapoints-{participant_count}-table-desktop.png")- )- )- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Benchmark datapoints")- .get_by_role("grid")- .locator("tbody tr")- .first.press("ArrowDown")- )- )- console.wait_until("""() => document.activeElement?.getAttribute('data-row-index') === '1'""")- console._browser.call(lambda: console._page.keyboard.press("Enter"))- console.sees("Datapoint 1")- console.sees("70.0%")- console.wait_until("""() => document.querySelector('[aria-label="Benchmark datapoints"] tr[aria-current="true"]')- ?.getAttribute('data-row-index') === '1'""")- console._browser.call(lambda: console._page.keyboard.press("Escape"))- console.wait_until("""() => document.activeElement?.getAttribute('data-row-index') === '1'""")- console.save_evidence(f"native-benchmark-{participant_count}-running-desktop")- console._browser.call(console._page.set_viewport_size, {"width": 390, "height": 844})- console.wait_until("() => document.documentElement.scrollWidth <= innerWidth")- console.save_evidence(f"native-benchmark-{participant_count}-running-mobile")- console._browser.call(- lambda: console._page.get_by_role(- "region", name="Benchmark datapoints"- ).scroll_into_view_if_needed()- )- console.save_evidence(f"native-datapoints-{participant_count}-mobile")- console._browser.call(- lambda: console._page.get_by_role("region", name="Benchmark datapoints").screenshot(- path=str(RUNS / f"native-datapoints-{participant_count}-table-mobile.png")- )- )- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Benchmark datapoints")- .locator('[data-slot="table-container"]')- .evaluate("(el) => { el.scrollLeft = el.scrollWidth; }")- )- )- console.wait_until("""() => {- const scroll = document.querySelector('[aria-label="Benchmark datapoints"] [data-slot="table-container"]');- const last = scroll.querySelector('thead th:nth-last-child(2)').getBoundingClientRect();- return last.right <= scroll.getBoundingClientRect().right + 1;- }""")- console._browser.call(console._page.set_viewport_size, {"width": 1440, "height": 1100})- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Benchmark datapoints")- .get_by_role("grid")- .locator("tbody tr")- .first.press("Enter")- )- )- console.sees("Datapoint 0")- console.sees("80.0%")- console.wait_until(- """() => !document.querySelector('[role=dialog] [role=combobox], [role=dialog] [role=tablist]')"""- )- console.wait_until(- f"""() => document.querySelectorAll('[aria-label="Model outputs"] > section').length === {participant_count}"""- )- console.wait_until("""() => [...document.querySelectorAll('[aria-label="Output for Qwen 3.5 0.8B"] tbody tr')]- .map(row => [...row.cells].map(cell => cell.querySelector('div > span')?.textContent ?? cell.textContent).join('|')).join(';')- === 'Survived|80.0%|100.0%;Did not survive|20.0%|0.0%'""")- console.wait_until("""() => {- const row = document.querySelector('[aria-label="Output for Qwen 3.5 0.8B"] tbody tr');- return row.textContent.includes('Target') && row.textContent.includes('Predicted');- }""")- if participant_count > 1:- console.sees("Waiting for this model's prediction.")- console.wait_until("""() => [...document.querySelectorAll('[aria-label="Output for Qwen 3.5 2B"] tbody tr')]- .map(row => [...row.cells].map(cell => cell.querySelector('div > span')?.textContent ?? cell.textContent).join('|')).join(';')- === 'Survived|—|100.0%;Did not survive|—|0.0%'""")- console.wait_until("""() => performance.getEntriesByType('resource')- .filter(entry => entry.name.includes('/monitor/') && entry.name.includes('key=0')).length >= 2""")- console.wait_until("""() => document.querySelector('[role=dialog]').getAnimations({subtree: true})- .every(animation => animation.playState === 'finished')""")- console.save_evidence(f"native-benchmark-{participant_count}-sample-desktop")- if participant_count > 1:- root, body = publish("medium", payloads["medium"][:1], corrupt=True)- broken = rest.request("GET", endpoint)- assert broken["calls"][1]["progress_error"]- assert broken["arms"][1]["scored"] == 0- fake_modal.files[root + "/0.jsonl"] = body- native_evaluation.advance(plan.pk, stage="final_medium")- assert rest.request("GET", endpoint)["arms"][1]["scored"] == 1- console.wait_until("""() => document.querySelector('[aria-label="Output for Qwen 3.5 2B"] tbody tr td:nth-child(2)')- ?.textContent === '80.0%'""")- console.wait_until("""() => document.querySelector('[aria-label="Output for Qwen 3.5 4B"]').textContent- .includes("Waiting for this model's prediction.")""")- if participant_count == 6:- input_top = console._browser.call(- lambda: console._page.get_by_role("region", name="Evaluation input").bounding_box()["y"]- )- console._browser.call(- lambda: console._page.get_by_role("region", name="Model outputs", exact=True).press(- "End"- )- )- console.wait_until("""() => {- const outputs = document.querySelector('[aria-label="Model outputs"]');- return outputs.scrollTop > 0 && outputs.lastElementChild.getBoundingClientRect().bottom- <= outputs.getBoundingClientRect().bottom + 1;- }""")- console.wait_until(f"""() => Math.abs(document.querySelector('[aria-label="Evaluation input"]')- .getBoundingClientRect().top - {input_top}) < 1""")- console.save_evidence("native-benchmark-6-sample-desktop-last-model")- console._browser.call(- lambda: console._page.get_by_role("region", name="Model outputs", exact=True).press(- "Home"- )- )- console.wait_until(- """() => document.querySelector('[aria-label="Model outputs"]').scrollTop === 0"""- )- console._browser.call(console._page.set_viewport_size, {"width": 390, "height": 844})- console.wait_until("""() => {- const rect = document.querySelector('[role=dialog]').getBoundingClientRect();- return rect.left >= 0 && rect.right <= innerWidth && rect.width <= innerWidth * .76;- }""")- console.wait_until("""() => {- const input = document.querySelector('[aria-label="Evaluation input"]').getBoundingClientRect();- const output = document.querySelector('[aria-label="Output and evaluation"]').getBoundingClientRect();- return output.top >= input.bottom;- }""")- console.wait_until("""() => {- const scroll = document.querySelector('[aria-label="Option probabilities"]').parentElement;- return scroll.scrollWidth <= scroll.clientWidth;- }""")- console.save_evidence(f"native-benchmark-{participant_count}-sample-mobile")- console._browser.call(- lambda: console._page.get_by_label(- "Option probabilities"- ).first.scroll_into_view_if_needed()- )- console.save_evidence(f"native-benchmark-{participant_count}-sample-mobile-output")- if participant_count > 1:- console._browser.call(- lambda: console._page.get_by_role(- "region", name=f"Output for {arms[-1]['name']}", exact=True- ).scroll_into_view_if_needed()- )- console.wait_until("""() => {- const dialog = document.querySelector('[role=dialog]').getBoundingClientRect();- const last = document.querySelector('[aria-label="Model outputs"]').lastElementChild.getBoundingClientRect();- return last.top >= dialog.top && last.bottom <= dialog.bottom;- }""")- console.save_evidence(f"native-benchmark-{participant_count}-sample-mobile-last-model")- console._browser.call(lambda: console._page.keyboard.press("Escape"))-- publish("small", payloads["small"][2:])- with pytest.raises(AssertionError, match="400"):- rest.request("GET", endpoint + "?role=calibration")- foreign = make_project("Other project")- with pytest.raises(AssertionError, match="resource_not_found"):- mcp.call(- "inspect_native_evaluation",- {"project_id": str(project.pk), "evaluation": str(foreign.pk)},- )-- for arm in arms:- name = arm["key"]- body = "".join(json.dumps(row) + "\n" for row in payloads[name]).encode()- fake_modal.files[roots[name] + "/base.jsonl"] = body- calls[name].result = {- "artifact_identity": name,- "input_sha256": input_sha,- "runtime_fingerprint": plan.config["runtime"]["training"],- "predictions_sha256": hashlib.sha256(body).hexdigest(),- "decisions": len(inputs),- }- calls[name].state = "done"- native_evaluation.advance(plan.pk, stage=f"final_{name}")- native_evaluation.advance(plan.pk, stage="score")- plan.refresh_from_db()- assert plan.state == "completed", plan.error- finished = rest.request("GET", endpoint + "?key=27")- assert not finished["provisional"]- assert all(arm["scored"] == 28 for arm in finished["arms"])- ordinal = finished["samples"][0]- assert ordinal["reference"] == {"mean": 7, "values": [0, 10]}- assert "cross_entropy" not in ordinal["predictions"]["small"]["metrics"]- assert ordinal["predictions"]["small"]["metrics"]["expected_score"] == 2- assert [- row["key"] for row in rest.request("GET", endpoint + "?offset=25&limit=10")["samples"]- ] == ["25", "26", "27"]- before = list(fake_modal.spawns())- (source / "monitor.sqlite").unlink()- (source / "monitor.json").unlink()- assert rest.request("GET", endpoint)["state"] == "pending"- rebuilt = settle(worker, lambda: rest.request("GET", endpoint)["arms"])- assert rebuilt[0]["scored"] == 28- assert fake_modal.spawns() == before- for query in ("?participant=unknown", "?outcome=unknown", "?key=0&search=Passenger"):- with pytest.raises(AssertionError, match="400"):- rest.request("GET", endpoint + query)- for search in ("%", "_", "' OR 1=1 --"):- assert rest.request("GET", endpoint + "?" + urlencode({"search": search}))["count"] == 0- searched = rest.request(- "GET", endpoint + "?" + urlencode({"search": "PASSENGER 2", "limit": 2, "offset": 2})- )- assert searched["count"] == 9- assert [row["key"] for row in searched["samples"]] == ["21", "22"]- assert rest.request("GET", endpoint + "?search=survival")["count"] == 27- incorrect = rest.request("GET", endpoint + "?outcome=incorrect&participant=small")- assert incorrect["count"] == 12- assert all(- row["predictions"]["small"]["metrics"]["accuracy"] == 0 for row in incorrect["samples"]- )- assert incorrect["arms"] == rest.request("GET", endpoint)["arms"]- assert rest.request("GET", endpoint + "?outcome=correct&participant=small")["count"] == 14- assert rest.request("GET", endpoint + "?outcome=incorrect")["count"] == (- 25 if participant_count > 1 else 12- )- assert rest.request("GET", endpoint + "?outcome=missing")["count"] == 0- assert rest.request("GET", endpoint + "?outcome=unscored")["count"] == 0- filtered = mcp.call(- "inspect_native_evaluation",- {- "project_id": str(project.pk),- "evaluation": str(plan.pk),- "search": "Passenger 2",- "outcome": "incorrect",- "participant": "small",- "limit": 2,- },- )["monitoring"]- assert filtered["count"] == 3- assert [row["key"] for row in filtered["samples"]] == ["21", "23"]- assert fake_modal.spawns() == before- console.goto(f"/evaluations/runs/{plan.pk}?projectId={project.pk}&format=decision")- console.sees("Model comparison")- console._browser.call(console._page.set_viewport_size, {"width": 1440, "height": 1100})- console._browser.call(- lambda: console._page.get_by_role("region", name="Model comparison").screenshot(- path=str(RUNS / f"native-model-comparison-{participant_count}-desktop.png")- )- )- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Model comparison")- .get_by_role("button", name="Sort by Model")- .click()- )- )- console.wait_until(- """() => document.querySelector('[aria-label="Model comparison"] th').getAttribute('aria-sort') === 'ascending'"""- )- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Model comparison")- .get_by_role("button", name="Sort by Model")- .click()- )- )- console.wait_until(- """() => document.querySelector('[aria-label="Model comparison"] th').getAttribute('aria-sort') === 'descending'"""- )- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Model comparison")- .get_by_role("button", name="Sort by Model")- .click()- )- )- console.wait_until(- """() => document.querySelector('[aria-label="Model comparison"] th').getAttribute('aria-sort') === 'none'"""- )- console._browser.call(console._page.set_viewport_size, {"width": 390, "height": 844})- console.wait_until("() => document.documentElement.scrollWidth <= innerWidth")- console._browser.call(- lambda: console._page.get_by_role("region", name="Model comparison").screenshot(- path=str(RUNS / f"native-model-comparison-{participant_count}-mobile.png")- )- )- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Model comparison")- .locator('[data-slot="table-container"]')- .evaluate("(el) => { el.scrollLeft = el.scrollWidth; }")- )- )- console.wait_until("""() => {- const scroll = document.querySelector('[aria-label="Model comparison"] [data-slot="table-container"]');- return scroll.querySelector('thead th:nth-last-child(2)').getBoundingClientRect().right <= scroll.getBoundingClientRect().right + 1;- }""")- console._browser.call(- lambda: console._page.get_by_role("region", name="Model comparison").screenshot(- path=str(RUNS / f"native-model-comparison-{participant_count}-mobile-metrics.png")- )- )- console._browser.call(console._page.set_viewport_size, {"width": 1440, "height": 1100})- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Benchmark datapoints")- .get_by_role("grid")- .wait_for()- )- )- console.wait_until("""() => {- const rows = document.querySelectorAll('[aria-label="Benchmark datapoints"] tbody tr');- return rows[2].querySelector('[aria-label="Correct: Survived. Probability 50.0%. Tied maximum"]')- && rows[3].querySelector('[aria-label="Reference: Did not survive"]')- && rows[3].querySelector('[aria-label="Incorrect: Survived. Probability 80.0%"] [data-slot=badge]')- ?.classList.contains('text-destructive');- }""")- if participant_count > 1:- console.wait_until("""() => {- const row = document.querySelectorAll('[aria-label="Benchmark datapoints"] tbody tr')[2];- return row.querySelector('[aria-label="Incorrect: Did not survive. Probability 90.0%"] [data-slot=badge]')- ?.classList.contains('text-destructive')- && row.querySelector('[aria-label="Correct: Survived. Probability 50.1%"] [data-slot=badge]')- ?.classList.contains('text-success');- }""")- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Benchmark datapoints")- .get_by_label("Reference: Soft target", exact=True)- .hover()- )- )- console.sees("70.0%")- console.sees("30.0%")- console._browser.call(lambda: console._page.mouse.move(0, 0))- console._browser.call(- lambda: console._page.get_by_role("region", name="Benchmark datapoints").screenshot(- path=str(RUNS / f"native-datapoints-{participant_count}-completed-desktop.png")- )- )- console._browser.call(console._page.set_viewport_size, {"width": 390, "height": 844})- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Benchmark datapoints")- .get_by_role("group", name="Correct: Survived. Probability 80.0%", exact=True)- .first.scroll_into_view_if_needed()- )- )- console.wait_until("() => document.documentElement.scrollWidth <= innerWidth")- console._browser.call(- lambda: console._page.get_by_role("region", name="Benchmark datapoints").screenshot(- path=str(- RUNS / f"native-datapoints-{participant_count}-completed-mobile-predictions.png"- )- )- )- console._browser.call(console._page.set_viewport_size, {"width": 1440, "height": 1100})-- def resize_input():- header = console._page.get_by_role("region", name="Benchmark datapoints").get_by_role(- "columnheader", name="Input", exact=True- )- handle = header.locator('[class*="cursor-col-resize"]')- handle.scroll_into_view_if_needed()- rect = handle.bounding_box()- console._page.mouse.move(rect["x"] + rect["width"] / 2, rect["y"] + rect["height"] / 2)- console._page.mouse.down()- console._page.mouse.move(rect["x"] + rect["width"] / 2 + 40, rect["y"] + rect["height"] / 2)- console._page.mouse.up()-- console._browser.call(resize_input)- console.wait_until(- f"""() => JSON.parse(localStorage.getItem('native-datapoints:{plan.pk}:columns')).input > 320"""- )- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Benchmark datapoints")- .get_by_role("button", name="Go to next page")- .click()- )- )- console.sees("26–28 of 28 rows")- console.wait_until("""() => {- const rows = document.querySelectorAll('[aria-label="Benchmark datapoints"] tbody tr');- const ordinal = rows[rows.length - 1];- return ordinal.querySelector('[aria-label="Reference: Mean 7"]')- && !ordinal.querySelector('.text-success, .text-destructive');- }""")- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Benchmark datapoints")- .get_by_role("grid")- .locator("tbody tr")- .last.click()- )- )- console.sees("Datapoint 27")- console.sees("Reference mean", exact=False)- console.wait_until(f"""() => [...document.querySelectorAll('[aria-label="Model outputs"] > section')]- .filter(section => section.textContent.includes('Reference mean 7') && section.textContent.includes('Predicted mean 2.0000'))- .length === {participant_count}""")- console.wait_until("""() => document.querySelector('[role=dialog]').getAnimations({subtree: true})- .every(animation => animation.playState === 'finished')""")- console.save_evidence(f"native-benchmark-{participant_count}-sample-completed-desktop")- console._browser.call(lambda: console._page.keyboard.press("Escape"))- console._browser.call(- lambda: console._page.get_by_role("searchbox", name="Search datapoints").fill(- "Passenger 27"- )- )- console.sees("1–1 of 1 row")- console._browser.call(- lambda: (- console._page.get_by_role("region", name="Benchmark datapoints")- .get_by_role("grid")- .locator("tbody tr")- .first.press("Enter")- )- )- console.sees("Datapoint 27")- console._browser.call(lambda: console._page.keyboard.press("Escape"))- console.press("Clear search")- console.sees("1–25 of 28 rows")- console._browser.call(- lambda: console._page.get_by_role("combobox", name="Filter by model").click()- )- console._browser.call(- lambda: console._page.get_by_role("option", name="Qwen 3.5 0.8B", exact=True).click()- )- console._browser.call(- lambda: console._page.get_by_role("combobox", name="Filter by outcome").click()- )- console._browser.call(- lambda: console._page.get_by_role("option", name="Incorrect", exact=True).click()- )- console.sees("1–12 of 12 rows")- console.wait_until("""() => {- const table = document.querySelector('[aria-label="Benchmark datapoints"] [role=grid]');- return table.querySelectorAll('tbody tr').length === 12- && [...table.querySelectorAll('tbody tr')].every(row => row.querySelector('[aria-label^="Incorrect:"]'))- && [...table.querySelectorAll('thead th')].filter(th => th.textContent.includes('Qwen')).length === 1;- }""")- console.save_evidence(f"native-datapoint-filters-{participant_count}-desktop")- console._browser.call(console._page.set_viewport_size, {"width": 390, "height": 844})- console._browser.call(- lambda: console._page.get_by_role(- "searchbox", name="Search datapoints"- ).scroll_into_view_if_needed()- )- console.wait_until("() => document.documentElement.scrollWidth <= innerWidth")- console.save_evidence(f"native-datapoint-filters-{participant_count}-mobile")- console._browser.call(- lambda: console._page.get_by_role("searchbox", name="Search datapoints").fill("Passenger 2")- )- console.sees("1–3 of 3 rows")- console._browser.call(- lambda: console._page.get_by_role("searchbox", name="Search datapoints").fill(- "no matching passenger"- )- )- console.sees("No results")- console.press("Clear filters")- console.sees("1–25 of 28 rows")- console._browser.call(- lambda: console._page.get_by_role("combobox", name="Filter by outcome").click()- )- console._browser.call(- lambda: console._page.get_by_role("option", name="Missing output", exact=True).click()- )- console.sees("No results")- console.press("Clear filters")- console.sees("1–25 of 28 rows")- console.wait_until(- "() => ![...document.querySelectorAll('button')].some(el => /Pause new work|Start evaluation|Delete/.test(el.textContent))"- )- console.healthy()diff --git a/tests/journeys/console/test_partial_evaluation.py b/tests/journeys/console/test_partial_evaluation.pydeleted file mode 100644index 3c48b5db..00000000--- a/tests/journeys/console/test_partial_evaluation.py+++ /dev/null@@ -1,130 +0,0 @@-import json-from datetime import timedelta-from unittest.mock import patch--import httpx-from django.utils import timezone-from factories import make_project--from overbae.models import Dataset, NativeEvaluationPlan-from overbae.services import native_evaluation-from overbae.services.datasets import land-from overbae.tasks.native_evaluation import advance_plan---def test_exhausted_evaluation_reports_partial_coverage_across_console_rest_mcp(- console, account, rest_for, mcp_for, scripted, monkeypatch, settings, tmp_path-):- settings.MEDIA_ROOT = tmp_path- monkeypatch.setenv("OPENROUTER_API_KEY", "fixture-key")- monkeypatch.setenv("JEV_REQUESTS_PER_MINUTE", "10000000")- monkeypatch.setenv("JEV_TOKENS_PER_SECOND", "10000000")- user, key = account- project = make_project("Partial evaluation", member=user)- dataset = Dataset.objects.create(project=project, name="Frozen final", intent="eval")- land.land_rows(- dataset,- [- {- "input": {- "decision": {- "state": f"Evidence {i}",- "question": "Choose",- "kind": "choice",- "options": ["a", "b"],- }- },- "expected_output": {"probabilities": [1, 0]},- }- for i in range(2)- ],- )- dataset.refresh_from_db()-- def response(call):- if call.json["state"] == "Evidence 0":- return httpx.ReadTimeout("response lost")- return (- 200,- {"content-type": "application/json"},- json.dumps(- {- "id": "fixture",- "provider": "TypeSafe",- "model": "typesafe/jev-1.13-20260917",- "usage": {"cost": 0.002},- "answers": {- "decision": {- "type": "choice",- "choice": "0",- "probabilities": {"0": 0.9, "1": 0.1},- }- },- }- ).encode(),- )-- provider = scripted("https://openrouter.ai/api/v1/systemone").then(response)- mcp = mcp_for(key)- created = mcp.call(- "create_native_evaluation",- {- "project_id": str(project.pk),- "name": "Available results",- "request_key": "partial",- "final_cell": str(dataset.active_cell.pk),- "baseline": "external",- "participants": [- {- "key": "external",- "name": "External",- "kind": "external",- "model": "typesafe/jev-1.13",- "served_model": "typesafe/jev-1.13-20260917",- }- ],- "bootstrap_samples": 2,- "inference": {"concurrency": 1},- },- )- identifier = created["workflow"]["id"]- with patch.object(advance_plan, "delay"):- mcp.call(- "launch_native_evaluation", {"project_id": str(project.pk), "evaluation": identifier}- )- native_evaluation.advance(identifier, stage="verify_inputs")- for _ in range(3):- native_evaluation.advance(identifier, stage="final_external")- plan = NativeEvaluationPlan.objects.get(pk=identifier)- plan.calls["final_external"]["retry_at"] = (- timezone.now() - timedelta(seconds=1)- ).isoformat()- plan.save()- native_evaluation.advance(identifier, stage="score")- job = mcp.call(- "get_job", {"project_id": str(project.pk), "kind": "native_evaluation", "id": identifier}- )- assert job["status"] == "completed"- completion = job["progress"]["results"]["completion"]- assert completion["status"] == "completed_with_issues"- assert completion["coverage"]["final"]["external"]["scored"] == 1- assert completion["coverage"]["final"]["external"]["missing_predictions"] == 1- rest = rest_for(key)- assert (- rest.request("GET", f"/api/native-evaluations/{identifier}/")["results"]["completion"]- == completion- )- assert (- rest.request("GET", f"/api/native-evaluations/{identifier}/report/?format=json")[- "completion"- ]- == completion- )- assert len(provider.calls) == 4- console.goto(f"/evaluations/runs/{identifier}?projectId={project.pk}&format=decision")- console.sees("Completed with issues")- console.sees("External: 1 / 2 scored · 1 missing · 0 invalid · 0 incompatible")- console.save_evidence("partial-evaluation-desktop")- console._browser.call(console._page.set_viewport_size, {"width": 390, "height": 844})- console.wait_until("() => document.documentElement.scrollWidth <= innerWidth")- console.save_evidence("partial-evaluation-mobile")diff --git a/tests/journeys/console/test_trace_errors.py b/tests/journeys/console/test_trace_errors.pydeleted file mode 100644index 6205648f..00000000--- a/tests/journeys/console/test_trace_errors.py+++ /dev/null@@ -1,117 +0,0 @@-import uuid--from django.utils import timezone-from factories import make_span--from overbae.models import Project---def test_trace_errors_expose_captured_context_and_failed_children(console, workshop):- project = Project.objects.get(pk=workshop.project()["id"])- now = int(timezone.now().timestamp() * 1_000_000_000)- trace_id = uuid.uuid4().hex- root = make_span(- project,- trace_id=trace_id,- name="Recovered navigation",- start_ns=now,- end_time_ns=now + 3_000_000_000,- duration_ns=3_000_000_000,- eval_attributes={"score": None, "trajectory": {"score": None}},- )- message = "The requested model is unavailable"- stack = "Traceback (most recent call last):\n request()\nNotFoundError: unavailable"- make_span(- project,- trace_id=trace_id,- parent_span_id=root.span_id,- name="Provider request",- status_code=2,- start_ns=now + 1_000_000,- end_time_ns=now + 1_000_000_000,- duration_ns=999_000_000,- attributes={- "error.type": "not_found_error",- "http.response.status_code": 404,- "anthropic.request.id": "req_browser_fixture",- },- events=[- {- "name": "exception",- "attributes": {- "exception.type": "NotFoundError",- "exception.message": message,- "exception.stacktrace": stack,- },- }- ],- eval_attributes={"score": None},- )- console.goto(f"/observability/{trace_id}?projectId={project.pk}&view=roots&timeRange=all")- console.sees("1 failed span")- console._browser.call(lambda: console._page.get_by_role("tab", name="Tree", exact=True).click())- console._browser.call(lambda: console._page.keyboard.press("/"))- console.wait_until(- "() => document.activeElement?.getAttribute('aria-label') === 'Search spans'"- )- console.fill('input[aria-label="Search spans"]', "Provider")- console._browser.call(lambda: console._page.keyboard.press("/"))- assert (- console._browser.call(- lambda: console._page.get_by_role("searchbox", name="Search spans").input_value()- )- == "Provider/"- )- console.press("Clear search")- console.click("Provider request")- console.sees(message, exact=False)- console.click("Technical details")- console.sees("req_browser_fixture")- console.click("Stack trace")- console.sees(stack)- console._browser.call(- lambda: console._page.context.grant_permissions(["clipboard-read", "clipboard-write"])- )- console.press("Copy error details")- copied = console._browser.call(lambda: console._page.evaluate("navigator.clipboard.readText()"))- assert message in copied and stack in copied and "req_browser_fixture" in copied- console.save_evidence("trace-error-captured-details")-- for label, attrs in [- (- "Attribute-only failure",- {"error.type": "not_found_error", "http.response.status_code": 404},- ),- ("Failure without details", {}),- ]:- trace_id = uuid.uuid4().hex- make_span(- project,- trace_id=trace_id,- name=label,- status_code=2,- start_ns=now,- attributes=attrs,- eval_attributes={"score": None, "trajectory": {"score": None}},- )- console.goto(f"/observability?projectId={project.pk}&view=roots&timeRange=all")- console.click(label)- console.sees("No error message captured")- console.save_evidence(f"trace-error-{label.lower().replace(' ', '-')}")- trace_id = uuid.uuid4().hex- long_message = "Navigation failed: " + "The previous frame was detached. " * 50- make_span(- project,- trace_id=trace_id,- name="Long captured error",- status_code=2,- start_ns=now,- attributes={"error.message": long_message},- eval_attributes={"score": None, "trajectory": {"score": None}},- )- console.goto(f"/observability/{trace_id}?projectId={project.pk}&view=roots&timeRange=all")- console.click("Full message")- console.sees(long_message, exact=False)- console.wait_until("() => document.documentElement.scrollWidth <= innerWidth")- console.save_evidence("trace-error-long-message")- console.healthy()diff --git a/tests/journeys/console/test_trace_inspection.py b/tests/journeys/console/test_trace_inspection.pydeleted file mode 100644index ada74c53..00000000--- a/tests/journeys/console/test_trace_inspection.py+++ /dev/null@@ -1,166 +0,0 @@-import uuid--from django.utils import timezone-from factories import make_span--from overbae.models import Project--from ..stack import drain---def test_trace_scores_reveal_the_recorded_reason_and_span_context(console, workshop, worker):- project = Project.objects.get(pk=workshop.project()["id"])- trace_id = uuid.uuid4().hex- now = int(timezone.now().timestamp() * 1_000_000_000)- root = make_span(- project,- trace_id=trace_id,- name="Answer with sources",- start_ns=now,- attributes={"input": "Which cities are served?", "output": "San Francisco and Chicago."},- eval_attributes={- "score": 0.5,- "metrics": {- "Cites sources": {- "type": "llm",- "expectation": "Every city is supported by a source.",- "score": 0.5,- "verdict": "partial",- "reason": "Chicago has no supporting citation.",- },- "Tool selection": {- "type": "deterministic",- "score": None,- "verdict": "abstain",- "reason": "No tool calls were captured.",- },- "Provider check": {"type": "llm", "score": None, "error": "Judge unavailable"},- },- "trajectory": {- "score": 0.5,- "span_count": 2,- "passed": False,- "metrics": {- "outcome": {- "score": 0.5,- "expectation": "The agent achieves the intent.",- "reason": "The final answer is incomplete.",- }- },- },- },- )- make_span(- project,- trace_id=trace_id,- parent_span_id=root.span_id,- name="Uncaptured answer",- start_ns=now + 1_000,- eval_attributes={- "score": 0,- "metrics": {"Empty result": {"type": "deterministic", "score": 0}},- },- )- drain(worker)- console.goto(f"/observability/{trace_id}?projectId={project.pk}&timeRange=all")- console._browser.call(lambda: console._page.get_by_role("tab", name="Scores (4)").click())- console._browser.call(- lambda: console._page.get_by_role("button", name="Inspect score: Cites sources").press(- "Enter"- )- )- console.sees("Chicago has no supporting citation.")- console.sees("Every city is supported by a source.")- console.sees("San Francisco and Chicago.")- console.sees("Which cities are served?")- console.save_evidence("trace-score-evidence")- console.press("Inspect score: Cites sources")- console._browser.call(- lambda: console._page.get_by_text("Chicago has no supporting citation.").wait_for(- state="hidden"- )- )- console.press("Inspect score: Trajectory")- console.sees("The final answer is incomplete.")- console.press("Inspect score: Tool selection")- console.sees("No tool calls were captured.")- console.press("Inspect score: Provider check")- console.sees("Judge unavailable")- console.press("Expand Trace spans")- console.press("Uncaptured answer")- console._browser.call(lambda: console._page.get_by_role("tab", name="Scores (1)").click())- console.press("Inspect score: Empty result")- console.sees("0%")- console.sees("No explanation recorded")- console.sees("Not captured")- console.healthy()---def test_trace_payloads_and_events_expand_without_losing_content(console, workshop, worker):- project = Project.objects.get(pk=workshop.project()["id"])- trace_id = uuid.uuid4().hex- now = int(timezone.now().timestamp() * 1_000_000_000)- long_text = "Keep the full instruction.\n" * 80 + "Final instruction marker"- stack = (- "Traceback (most recent call last):\n"- + " provider_request()\n" * 60- + "Final stack marker"- )- make_span(- project,- trace_id=trace_id,- name="Inspect structured evidence",- start_ns=now,- attributes={- "input": [{"role": "system", "content": long_text}],- "output": {"answer": False, "count": 0, "results": [{"city": "Chicago"}]},- },- events=[{"name": "provider.debug", "attributes": {"stacktrace": stack, "escaped": False}}],- eval_attributes={"score": None},- )- drain(worker)- console._browser.call(- lambda: console._page.add_init_script("localStorage.setItem('vite-ui-theme', 'light')")- )- console.goto(f"/observability/{trace_id}?projectId={project.pk}&timeRange=all")- console.press("Collapse Input")- console._browser.call(- lambda: console._page.get_by_text("Final instruction marker", exact=False).wait_for(- state="hidden"- )- )- console.press("Expand Input")- console.press("Expand System content")- console.sees(long_text)- assert console._browser.call(- lambda: console._page.get_by_role("button", name="Collapse System content").evaluate(- "button => button.getBoundingClientRect().bottom <= "- "document.getElementById(button.getAttribute('aria-controls')).getBoundingClientRect().top"- )- )- console.press("Collapse System content")- console.press("Expand System content")- console.sees("false")- console.sees("0")- console.sees('"Chicago"')- console._browser.call(- lambda: console._page.get_by_role("combobox", name="View format").nth(1).click()- )- console._browser.call(- lambda: console._page.get_by_role("option", name="Formatted", exact=True).click()- )- console.sees("Chicago")- assert (- console._browser.call(lambda: console._page.get_by_text("Item 1", exact=True).count()) == 0- )- console._browser.call(lambda: console._page.get_by_role("tab", name="Events (1)").click())- console.press("Expand stacktrace")- console.sees("Final stack marker")- console.press("Collapse provider.debug")- console._browser.call(- lambda: console._page.get_by_text("Final stack marker").wait_for(state="hidden")- )- console.press("Expand provider.debug")- console.press("Expand stacktrace")- console.save_evidence("trace-expandable-event")- console.healthy()diff --git a/tests/journeys/console/test_trace_workshop.py b/tests/journeys/console/test_trace_workshop.pydeleted file mode 100644index 102981b7..00000000--- a/tests/journeys/console/test_trace_workshop.py+++ /dev/null@@ -1,147 +0,0 @@-import pytest--from overbae.models import Dataset-from overbae.services.datasets import land--from ..stack import drain, settle--[email protected]("selection", ["selected", "all"])-def test_selected_traces_open_the_landed_workshop_source(- console, workshop, sample_agent, live_api, support_desk_llm, worker, selection-):- project = workshop.project()["id"]- sample_agent.run(- "Refund order 42 please",- "Where is order 42?",- api_url=live_api.url,- llm_url=support_desk_llm,- )- drain(worker)- console.goto(f"/observability?projectId={project}")- console.click("Traces")- console.sees("handle_ticket")- console._browser.call(- lambda: console._page.get_by_role("checkbox", name="Select row", exact=True).first.click()- )- if selection == "all":- console.press("Select all 2")- console.press("Add to dataset")- console.fill("#dataset-name", "Selected trace source")- assert console._browser.call(lambda: console._page.locator("#dataset-purpose").count()) == 0- assert console._browser.call(lambda: console._page.locator("#dataset-brief").count()) == 0- capability = workshop.capability("answer") if selection == "all" else None- if capability:- console.choose("#dataset-capability", capability["name"])- else:- console.sees("None")- console.wait_until(- """() => {- const dialog = document.querySelector('[role=dialog]');- return dialog && getComputedStyle(dialog).opacity === '1'- && !document.querySelector('[role=listbox]');- }"""- )- console.save_evidence(f"trace-create-{selection}")- if selection == "selected":- console._browser.call(- lambda: console._page.set_viewport_size({"width": 390, "height": 844})- )- console.wait_until(- """() => {- const dialog = document.querySelector('[role=dialog]').getBoundingClientRect();- return dialog.left >= 0 && dialog.right <= innerWidth;- }"""- )- console.save_evidence("trace-create-mobile")- console._browser.call(- lambda: console._page.set_viewport_size({"width": 1280, "height": 720})- )-- def create():- with console._page.expect_response(- lambda response: (- response.request.method == "POST"- and response.url.rstrip("/").endswith("/api/datasets")- )- ) as response:- console._page.get_by_role("button", name="Create dataset", exact=True).click()- return response.value.status, response.value.json()-- status, result = console._browser.call(create)- assert status == 201, result-- def landed():- datasets = workshop.call("list_datasets", {"search": "Selected trace source"})["datasets"]- if not datasets:- return None- dataset = workshop.call("inspect_dataset", {"dataset": datasets[0]["id"]})- return dataset if dataset["active"] else None-- dataset = settle(worker, landed)- count = 2 if selection == "all" else 1- assert dataset["active"]["rows"] == count- assert dataset["source_kind"] == "traces"- console.wait_until(- f"() => location.pathname === '/datasets/{dataset['id']}' "- "&& !!document.querySelector('article [data-cell-frame]')"- )- console.sees(f"{count} rows", exact=False)- assert dataset["intent"] == "pending"- assert dataset["brief"] == ""- assert (- dataset["capability"] is None- if capability is None- else dataset["capability"]["id"] == capability["id"]- )- console.sees("Intent pending", exact=False)- console.press("Prepare with agent")- prompt = console._browser.call(- lambda: console._page.get_by_role("textbox", name="Preparation prompt").input_value()- )- assert dataset["id"] in prompt- assert project in prompt- assert dataset["active"]["id"] in prompt- assert dataset["active"]["fingerprint"] in prompt- assert live_api.url in prompt- console._browser.call(- lambda: console._page.context.grant_permissions(["clipboard-read", "clipboard-write"])- )- console.press("Copy preparation prompt")- console.sees("Prompt copied")- assert (- console._browser.call(lambda: console._page.evaluate("navigator.clipboard.readText()"))- == prompt- )- console._browser.call(lambda: console._page.set_viewport_size({"width": 390, "height": 844}))- console.wait_until(- """() => {- const dialog = document.querySelector('[role=dialog]').getBoundingClientRect();- return dialog.left >= 0 && dialog.right <= innerWidth;- }"""- )- console.save_evidence("trace-workshop-mobile")- console._browser.call(lambda: console._page.set_viewport_size({"width": 1280, "height": 720}))---def test_trace_landing_refreshes_the_canvas_without_live_events(- console, workshop, sample_agent, live_api, support_desk_llm, worker-):- project = workshop.project()["id"]- sample_agent.run("Refund order 42 please", api_url=live_api.url, llm_url=support_desk_llm)- drain(worker)- [trace] = workshop.call("query_traces", {})["traces"]- dataset = Dataset.objects.create(- project_id=project,- name="Trace landing without live events",- source_kind="traces",- state="landing",- )- console._browser.call(- lambda: console._page.route("**/api/datasets/*/events/", lambda route: route.abort())- )- console.goto(f"/datasets/{dataset.id}?projectId={project}")- console.sees("Reading source data")- land.land_traces(dataset, {"trace_ids": [trace["trace_id"]]})- console.wait_until("() => !!document.querySelector('article [data-cell-frame]')")- console.sees("1 rows", exact=False)diff --git a/tests/journeys/console/test_training_labels.py b/tests/journeys/console/test_training_labels.pydeleted file mode 100644index 935f2c95..00000000--- a/tests/journeys/console/test_training_labels.py+++ /dev/null@@ -1,322 +0,0 @@-import os-import subprocess-import sys-import uuid--from factories import make_project--from overbae.models import Cell, Dataset, DeployedModel, FinetuningJob-from overbae.services.datasets import land, paths, store, use--from ..conftest import RUNS---def test_training_labels_follow_the_pinned_cell_across_console_rest_and_mcp(- console, account, rest_for, mcp_for, settings, tmp_path-):- settings.MEDIA_ROOT = tmp_path- user, key = account- project = make_project("Prediction labels", member=user)- dataset = Dataset.objects.create(project=project, name="Titanic training", intent="train")- decision = {- "state": 'Passenger\nName: O\'Brien; $(echo unsafe); `echo unsafe`; "quoted"',- "question": "Did this Titanic passenger survive?",- "kind": "choice",- "options": ["didn't survive", "survived"],- "target_probabilities": [1, 0],- }- land.land_rows(dataset, [{"decision": decision}] * 625)- dataset.refresh_from_db()- cell = dataset.active_cell- use.freeze(cell)- group = uuid.uuid4()- jobs = [- FinetuningJob.objects.create(- project=project,- dataset=dataset,- cell=cell,- group_id=group,- base_model=f"Qwen/Qwen3.5-{size}",- name=f"Titanic {size}",- status="succeeded",- hyperparameters={"objective": "decision_cross_entropy"},- )- for size in ("0.8B", "2B", "4B")- ]- newer = Cell.objects.create(- dataset=dataset, position=1, title="Later labels", state="ok", rows=1- )- path = paths.cell_path(dataset.pk, newer.pk)- store.write_rows(path, [{"decision": {**decision, "options": ["New no", "New yes"]}}])- Cell.objects.filter(pk=newer.pk).update(fingerprint=store.file_sha256(path))- Dataset.objects.filter(pk=dataset.pk).update(active_id=newer.pk)- dataset.refresh_from_db()- assert dataset.active_cell.pk != cell.pk- rest, mcp = rest_for(key), mcp_for(key)- endpoint = f"/api/finetuning-jobs/{jobs[0].pk}/"- summary = rest.request("GET", endpoint)["record"]["prediction_labels"]- assert summary == {- "state": "available",- "cell": str(cell.pk),- "fingerprint": cell.fingerprint,- "total_sets": 1,- "label_sets": [- {- "question": decision["question"],- "kind": "choice",- "options": decision["options"],- "option_values": None,- "example_state": decision["state"],- }- ],- }- result = mcp.call(- "get_job",- {"project_id": str(project.pk), "kind": "finetune_job", "id": str(jobs[0].pk)},- )- resource = mcp.read(result["resource_links"][0]["uri"])- assert resource["record"]["prediction_labels"] == summary- assert rest.request("GET", endpoint)["record"]["prediction_labels"] == summary-- console._browser.call(console._page.set_viewport_size, {"width": 1440, "height": 1100})- route = f"/training?projectId={project.pk}&groupId={group}"- console.goto(route)- console.sees("Prediction labels")-- def check_labels():- region = console._page.get_by_role("group", name="Prediction labels", exact=True)- region.wait_for()- assert region.count() == 1- popup = console._page.get_by_role("dialog", name="Prediction labels", exact=True)- if not popup.is_visible():- region.get_by_role("button", name="2 labels", exact=True).click()- popup.wait_for()- assert popup.get_by_role("listitem").all_text_contents() == decision["options"]- assert "New yes" not in popup.inner_text()- assert region.get_by_role("button", name="2 labels", exact=True).count() == 1- assert region.locator("dt").inner_text() == "Prediction labels"- assert region.evaluate("el => el.parentElement.tagName") == "DL"- assert region.locator("h3").count() == 0- labels = popup.get_by_role("listitem")- for item in labels.all():- assert item.evaluate("el => el.scrollWidth <= el.clientWidth")-- console._browser.call(check_labels)-- console.save_evidence("training-prediction-labels-desktop")- console._browser.call(console._page.set_viewport_size, {"width": 390, "height": 844})- console._browser.call(check_labels)- console.save_evidence("training-prediction-labels-mobile")- console.goto(f"{route}&jobId={jobs[1].pk}")- console._browser.call(check_labels)-- FinetuningJob.objects.filter(pk=jobs[0].pk).update(group_id=None)- console.goto(f"/training?projectId={project.pk}&groupId={jobs[0].pk}&jobId={jobs[0].pk}")- console._browser.call(check_labels)- console.save_evidence("training-prediction-labels-single-mobile")- FinetuningJob.objects.filter(pk=jobs[0].pk).update(group_id=group)-- deployed = DeployedModel.objects.create(- project=project,- finetuning_job=jobs[0],- model_id="ft-titanic-example",- inference_contract="decision",- status="ready",- )- console._browser.call(console._page.set_viewport_size, {"width": 1440, "height": 1100})- console.goto(f"/inference/{deployed.pk}?projectId={project.pk}")- console.press("Serverless API snippet")- console.sees("Uses an example from this model’s training version.", exact=False)-- def inspect_snippets():- page = console._page- page.evaluate("""() => {- navigator.clipboard.writeText = async text => { window.copiedSnippet = text; };- }""")- snippets = {}- for language in ("cURL", "Python (TypeSafe SDK)"):- region = page.get_by_role("region", name=f"{language} API example")- code = region.locator("code")- source = code.inner_text()- assert decision["question"] in source- assert "New yes" not in source- assert "target_probabilities" not in source- assert "monospace" in code.evaluate("el => getComputedStyle(el).fontFamily")- assert code.evaluate("""el => {- const ctx = document.createElement('canvas').getContext('2d');- ctx.font = `12px ${getComputedStyle(el).fontFamily}`;- return ctx.measureText('iiii').width === ctx.measureText('WWWW').width;- }""")- assert code.locator("span").count() > 0- page.get_by_role("button", name=f"Copy {language}", exact=True).click()- page.wait_for_function("expected => window.copiedSnippet === expected", arg=source)- snippets[language] = source- return snippets-- snippets = console._browser.call(inspect_snippets)- console.save_evidence("model-api-examples-desktop")- console._browser.call(console._page.set_viewport_size, {"width": 390, "height": 844})- console.wait_until("() => document.documentElement.scrollWidth <= innerWidth")- console.wait_until("""() => {- const rect = document.querySelector('[role=dialog]').getBoundingClientRect();- return rect.left >= 0 && rect.right <= innerWidth;- }""")- console.save_evidence("model-api-examples-mobile")- subprocess.run(["sh", "-n"], input=snippets["cURL"], text=True, check=True)- (tmp_path / "typesafe_sdk.py").write_text("""-import os-class Choice:- def __init__(self, **kwargs):- self.kwargs = kwargs-class _Answer:- choice = "survived"- probabilities = {"didn't survive": 0.2, "survived": 0.8}-class _Response:- choices = {"decision": _Answer()}-class TypeSafeClient:- def __init__(self, *, api_key, base_url, model, timeout, compression):- assert api_key == "example-key"- assert base_url.endswith("/api")- assert model == os.environ["EXPECTED_MODEL"]- assert compression is False- def __enter__(self):- return self- def __exit__(self, *args):- return False- def system_one(self, *, state, questions):- assert state == os.environ["EXPECTED_STATE"]- assert questions["decision"].kwargs["instructions"] == os.environ["EXPECTED_QUESTION"]- return _Response()-""")- sample = tmp_path / "example.py"- sample.write_text(snippets["Python (TypeSafe SDK)"])- executed = subprocess.run(- [sys.executable, str(sample)],- text=True,- capture_output=True,- check=True,- env={- **os.environ,- "PYTHONPATH": str(tmp_path),- "OVERMIND_API_KEY": "example-key",- "EXPECTED_MODEL": deployed.model_id,- "EXPECTED_STATE": decision["state"],- "EXPECTED_QUESTION": decision["question"],- },- )- assert "survived" in executed.stdout-- varied = Dataset.objects.create(project=project, name="Ordinal labels", intent="train")- long_label = "A" * 150- land.land_rows(- varied,- [- {- "decision": {- **decision,- "question": f"Score question {index}",- "state": "X" * 2500 if index == 0 else decision["state"],- "kind": "score",- "options": [long_label, "High"],- "target_probabilities": [0.3, 0.7],- }- }- for index in range(9)- ]- + [- {- "decision": {- "state": "Ordinal example",- "question": "Mean score",- "kind": "score",- "options": ["Low", "High"],- "target_mean": 7,- "option_values": [0, 10],- "target_semantics": "ordinal_mean",- }- }- ],- )- varied.refresh_from_db()- FinetuningJob.objects.filter(pk=jobs[1].pk).update(cell=varied.active_cell, dataset=varied)- ordinal = rest.request("GET", f"/api/finetuning-jobs/{jobs[1].pk}/")["record"][- "prediction_labels"- ]- assert ordinal["total_sets"] == 10- assert len(ordinal["label_sets"]) == 8- assert ordinal["label_sets"][0]["option_values"] == [0, 10]- assert ordinal["label_sets"][1]["example_state"] is None- assert ordinal["label_sets"][1]["options"] == [long_label, "High"]- varied_model = DeployedModel.objects.create(- project=project,- finetuning_job=jobs[1],- model_id="ft-varied-example",- inference_contract="decision",- status="ready",- )- console.goto(f"/inference/{varied_model.pk}?projectId={project.pk}")- console.press("Serverless API snippet")- console.sees("Showing 8 of 10 decision examples.", exact=False)- console._browser.call(- lambda: console._page.get_by_role("combobox", name="Decision example").click()- )- console._browser.call(- lambda: console._page.get_by_role("option", name="Score question 0", exact=True).click()- )- console.sees(- "A complete example input is unavailable for this model’s pinned training version."- )- console._browser.call(- lambda: console._page.get_by_role("combobox", name="Decision example").click()- )- console._browser.call(- lambda: console._page.get_by_role("option", name="Score question 1", exact=True).click()- )- console._browser.call(- lambda: console._page.get_by_role(- "region", name="Python (TypeSafe SDK) API example"- ).wait_for()- )- console.goto(route)- console._browser.call(- lambda: (- console._page.get_by_role("group", name="Prediction labels", exact=True)- .get_by_role("button", name="10 label sets", exact=True)- .click()- )- )- console.sees("Showing 8 of 10 label sets")- console.sees(long_label)- console.sees("Ordinal labels")- console._browser.call(- lambda: console._page.get_by_role(- "dialog", name="Prediction labels", exact=True- ).screenshot(path=str(RUNS / "training-prediction-labels-varied-mobile.png"))- )- console.wait_until("() => document.documentElement.scrollWidth <= innerWidth")-- FinetuningJob.objects.filter(pk=jobs[0].pk).update(- requested_configuration={"selection": {"train_fingerprint": "f" * 64}}- )- assert rest.request("GET", endpoint)["record"]["prediction_labels"]["state"] == "unavailable"- FinetuningJob.objects.filter(pk=jobs[0].pk).update(cell=None)- assert rest.request("GET", endpoint)["record"]["prediction_labels"]["state"] == "unavailable"- console.goto(f"{route}&jobId={jobs[0].pk}")- console._browser.call(- lambda: (- console._page.get_by_role("group", name="Prediction labels")- .get_by_text("Unavailable", exact=True)- .wait_for()- )- )- FinetuningJob.objects.filter(pk=jobs[0].pk).update(- hyperparameters={"objective": "assistant_cross_entropy"}- )- assert rest.request("GET", endpoint)["record"]["prediction_labels"] is None- console.goto(f"{route}&jobId={jobs[0].pk}")- console.sees("Titanic 0.8B")- console._browser.call(- lambda: console._page.get_by_role("group", name="Prediction labels", exact=True).wait_for(- state="detached"- )- )diff --git a/tests/journeys/otlp.py b/tests/journeys/otlp.pynew file mode 100644index 00000000..eb2605db--- /dev/null+++ b/tests/journeys/otlp.py@@ -0,0 +1,102 @@+import json+import uuid++import requests+from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest+from opentelemetry.proto.common.v1.common_pb2 import AnyValue, KeyValue+from opentelemetry.proto.trace.v1.trace_pb2 import ResourceSpans, ScopeSpans, Span, Status++EXPECTATION = "The reply quotes the order id and its status."+RUN_SIGNALS = "overbae.tasks.innermind.run_signals"+SWEEP_SPANS = "overbae.tasks.innermind.sweep_unscored_spans"+SWEEP_TRAJECTORIES = "overbae.tasks.innermind.score_trajectories"+# Past the span sweep's grace period, so every beat re-drives what is still unscored.+SWEEP_WAIT = 120+++def _attrs(**values) -> list[KeyValue]:+ return [+ KeyValue(key=key.replace("__", "."), value=AnyValue(string_value=str(value)))+ for key, value in values.items()+ ]+++class Trace:+ """One OTLP trace: a workflow root that answers a ticket and its tool calls."""++ def __init__(self, capability_id: str, reply: str, tools: list[bool]):+ self.trace_id = uuid.uuid4().bytes+ self.root_id = uuid.uuid4().bytes[:8]+ self.capability_id = capability_id+ self.reply = reply+ self.tools = []+ for ok in tools:+ self.add_tool(ok)++ def add_tool(self, ok: bool) -> None:+ self.tools.append((uuid.uuid4().bytes[:8], ok))++ @property+ def hex(self) -> str:+ return self.trace_id.hex()++ def request(self, *, root: bool = True, tools: bool = True) -> ExportTraceServiceRequest:+ root_span = Span(+ trace_id=self.trace_id,+ span_id=self.root_id,+ name="handle_ticket",+ start_time_unix_nano=1_000,+ end_time_unix_nano=90_000,+ attributes=_attrs(+ overmind__capability__id=self.capability_id,+ overmind__span_type="workflow",+ overmind__input="Refund order 42 please",+ overmind__output=self.reply,+ overmind__expectations=json.dumps([EXPECTATION]),+ ),+ )+ tool_spans = [+ Span(+ trace_id=self.trace_id,+ span_id=span_id,+ parent_span_id=self.root_id,+ name="lookup_order",+ start_time_unix_nano=2_000 + i * 10_000,+ end_time_unix_nano=9_000 + i * 10_000,+ status=Status(code=Status.STATUS_CODE_OK if ok else Status.STATUS_CODE_ERROR),+ attributes=_attrs(+ overmind__capability__id=self.capability_id,+ overmind__span_type="tool_call",+ gen_ai__tool__name="lookup_order",+ overmind__input=f'{{"order_id": "42", "attempt": {i}}}',+ overmind__output="delivered" if ok else "",+ ),+ )+ for i, (span_id, ok) in enumerate(self.tools)+ ]+ spans = [*([root_span] if root else []), *(tool_spans if tools else [])]+ return ExportTraceServiceRequest(+ resource_spans=[ResourceSpans(scope_spans=[ScopeSpans(spans=spans)])]+ )++ def send(self, api_url: str, key: str, *, root: bool = True, tools: bool = True) -> None:+ response = requests.post(+ f"{api_url}/api/v1/traces",+ data=self.request(root=root, tools=tools).SerializeToString(),+ headers={"Content-Type": "application/x-protobuf", "X-Api-Key": key},+ timeout=30,+ )+ assert response.status_code == 200, response.text+++def score_history(rest, project_id: str, trace: Trace) -> list[dict]:+ return rest.request(+ "GET",+ "/api/eval-scores/",+ params={"project": project_id, "trace_id": trace.hex, "page_size": 100},+ )["results"]+++def trace_spans(rest, project_id: str, trace: Trace) -> dict[str, dict]:+ detail = rest.request("GET", f"/api/traces/{trace.hex}/", params={"project": project_id})+ return {span["span_id"]: span for span in detail["spans"]}diff --git a/tests/journeys/stack.py b/tests/journeys/stack.pyindex af224778..ade492eb 100644--- a/tests/journeys/stack.py+++ b/tests/journeys/stack.py@@ -5,12 +5,17 @@ import threadingimport timefrom contextlib import contextmanagerfrom dataclasses import dataclass, field+from datetime import UTC, datetime+from pathlib import Pathimport uvicornfrom celery.contrib.testing.worker import start_workerfrom celery.signals import before_task_publish, task_postrun+from celery.worker.state import revokedfrom django.conf import settings+RUNS = Path(__file__).parent / ".runs" / datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")+class LiveAPI:def __init__(self) -> None:@@ -90,12 +95,21 @@ class TaskLedger:def failed(self) -> dict[str, str]:with self._lock:+ known = {**self.scheduled, **self.published}return {- task_id: self.published.get(task_id, "")+ task_id: known.get(task_id, "")for task_id, state in self.finished.items()if state not in ("SUCCESS", "IGNORED")}+ def revoke_scheduled(self) -> None:+ # A countdown task outlives its test and would run against the next test's rows.+ with self._lock:+ waiting = [task_id for task_id in self.scheduled if task_id not in self.finished]+ for task_id in waiting:+ del self.scheduled[task_id]+ revoked.update(waiting)+@contextmanagerdef celery_worker():@@ -127,6 +141,22 @@ def drain(ledger: TaskLedger, timeout: float = 120) -> None:time.sleep(0.05)+def drain_scoring(ledger: TaskLedger, timeout: float = 120) -> None:+ """Drain, then run scoring admission while live scoring work waits. A dispatch that+ finds another one admitting admits nothing and leaves the work to the periodic tick,+ which no beat runs in journeys."""+ from overbae.celery import app+ from overbae.models import LiveScoringWork++ drain(ledger, timeout)+ for _ in range(10):+ if not LiveScoringWork.objects.filter(state="waiting").exists():+ return+ app.send_task("overbae.tasks.innermind.dispatch_live_scoring")+ drain(ledger, timeout)+ raise TimeoutError("Live scoring work still waits after 10 admissions")++def settle(ledger: TaskLedger, condition, timeout: float = 60):"""Drain until ``condition()`` holds. A browser action returns before its requestcommits, so the work it publishes may not exist yet when a single drain runs."""diff --git a/tests/journeys/test_agent_instructions.py b/tests/journeys/test_agent_instructions.pyindex e1fbd79d..bfd4ddd2 100644--- a/tests/journeys/test_agent_instructions.py+++ b/tests/journeys/test_agent_instructions.py@@ -12,6 +12,8 @@ from overbae.services.mcp.context import MCPContext, bind_contextfrom overbae.services.mcp.prompts import PROMPTS, get_promptfrom overbae.services.mcp.resources import read_resource, resource_list+pytestmark = pytest.mark.covers("mcp-surface")+COMMAND = re.compile(r"`(overmind [^`]+)`")PLACEHOLDER = re.compile(r"^(?:[A-Z][A-Z_]*|<[^>]+>|\{[^}]+\})$")diff --git a/tests/journeys/test_boot.py b/tests/journeys/test_boot.pyindex 58e54681..4d4e842d 100644--- a/tests/journeys/test_boot.py+++ b/tests/journeys/test_boot.py@@ -9,6 +9,8 @@ import pytestimport requestsfrom django.conf import settings+pytestmark = pytest.mark.covers("boot")+ROOT = Path(__file__).resolve().parents[2]FILLED = {diff --git a/tests/journeys/test_data.py b/tests/journeys/test_data.pynew file mode 100644index 00000000..fca5623e--- /dev/null+++ b/tests/journeys/test_data.py@@ -0,0 +1,484 @@+import hashlib+import json+from pathlib import Path++import pytest++from overbae.models import Dataset+from overbae.services.datasets import land++from .datasets import evaluate, tickets, upload+from .stack import drain, settle++pytestmark = pytest.mark.covers("data")++TICKET = "Refund order 42 please, mail me at [email protected]"+SCANNED = Path(__file__).parents[1] / "fixtures/documents/scanned.pdf"+++def test_data(+ console,+ workshop,+ cli,+ sample_agent,+ rest_for,+ live_api,+ support_desk_llm,+ fake_llm,+ worker,+ tmp_path,+):+ hand_uploaded_data_to_the_coding_agent(console, tmp_path)++ project = workshop.project()["id"]+ rest = rest_for(workshop.api_key)+ use_freezes_an_uploaded_eval_source(console, workshop, project, worker, tmp_path)+ show_upload_bytes_until_publication(console, workshop, rest, project, worker)+ keep_the_brief_when_the_cli_attaches_data(+ console, workshop, cli, sample_agent, project, worker, tmp_path+ )++ sample_agent.run(TICKET, api_url=live_api.url, llm_url=support_desk_llm)+ drain(worker)+ land_selected_traces_as_rows(workshop, fake_llm, worker)+ open_traces_selected_in_the_console(console, workshop, project, live_api, worker)++ read_a_scanned_document_once_per_page(workshop, cli, sample_agent, worker)+ publish_version_bound_analytics(workshop, cli, sample_agent, rest, worker, tmp_path)+ keep_one_preparation_until_the_agent_finishes(+ console, workshop, cli, sample_agent, project, worker, tmp_path+ )+++def hand_uploaded_data_to_the_coding_agent(console, tmp_path):+ console.goto("/projects")+ console.press("New project")+ console._browser.call(+ lambda: console._page.get_by_label("Project name", exact=True).fill("Data first")+ )+ console.upload('input[type="file"]', tickets(tmp_path))+ console.sees("3 rows")+ console.press("Create dataset")+ console.sees("Prepare your training data")+ dataset = Dataset.objects.get(name="Data first")+ assert dataset.intent == "train"+ assert dataset.brief == (+ "Explore the uploaded data and determine how best to prepare it for training."+ )+ assert dataset.capability_id is None+ console.wait_until(f"() => location.pathname.includes('/datasets/{dataset.id}')")+ console._browser.call(+ lambda: console._page.evaluate("""() => {+ window.copiedOnboardingPrompt = '';+ navigator.clipboard.write = async items => {+ window.copiedOnboardingPrompt = await (await items[0].getType('text/plain')).text();+ };+ navigator.clipboard.writeText = async text => { window.copiedOnboardingPrompt = text; };+ }""")+ )+ console.press("Copy onboarding prompt")+ console.wait_until("() => window.copiedOnboardingPrompt.length > 0")+ prompt = console._browser.call(lambda: console._page.evaluate("window.copiedOnboardingPrompt"))+ assert prompt.startswith(+ f"Set me up on Overmind with my uploaded data\n(project_id: {dataset.project_id},\ndataset_id: {dataset.id})"+ )+ assert prompt.endswith("/setup.md")+ assert "api-key" not in prompt.lower()+ console.save_evidence("data-onboarding-handoff")+ console._browser.call(+ lambda: (+ console._page.get_by_role("dialog")+ .get_by_role("button", name="Close", exact=True)+ .last.click()+ )+ )+ console.wait_until("() => !location.search.includes('prepare=')")+++def use_freezes_an_uploaded_eval_source(console, workshop, project, worker, tmp_path):+ console.goto(f"/datasets?projectId={project}")+ console.command("New dataset")+ 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.press("Create dataset")++ def landed():+ for dataset in workshop.call("list_datasets", {})["datasets"]:+ if dataset["name"] == "Console upload":+ inspected = workshop.call("inspect_dataset", {"dataset": dataset["id"]})+ return inspected if inspected["active"] else None+ return None++ inspected = settle(worker, landed)+ dataset = inspected["id"]+ assert inspected["active"]["rows"] == 3+ assert inspected["intent"] == "eval"+ assert inspected["active"]["fits"]["ok"] is True++ ready = workshop.call("check_evaluation_readiness", {"dataset": dataset})+ assert ready["dataset"]["cell"]["fingerprint"] == inspected["active"]["fingerprint"]+ run = evaluate(workshop, dataset)+ drain(worker)+ assert run["cell"]["version"] == "1.0"+ assert run["cell"]["fingerprint"] == inspected["active"]["fingerprint"]+ [candidate] = run["runs"]+ assert workshop.read(candidate["resource"]["uri"])["status"] == "completed"+ frozen = next(+ c+ for c in workshop.call("inspect_dataset", {"dataset": dataset})["cells"]+ if c["id"] == run["cell"]["id"]+ )+ assert frozen["frozen"] is True+ assert frozen["version"] == "1.0"+++def show_upload_bytes_until_publication(console, workshop, rest, project, worker):+ dataset = workshop.call(+ "start_dataset", {"name": "Live upload", "brief": "Inspect uploaded rows"}+ )["dataset"]["id"]+ console.goto(f"/datasets?projectId={project}")+ console.sees("Waiting for source")+ data = b'[{"value":1},{"value":2}]'+ receipt = rest.request(+ "POST",+ "/api/dataset-transfers/",+ json={+ "project": project,+ "dataset": dataset,+ "request_key": "live-upload",+ "filename": "rows.json",+ "size": len(data),+ "sha256": hashlib.sha256(data).hexdigest(),+ },+ )+ console.sees("Uploading", exact=False)+ rest.request(+ "PUT",+ f"/api/dataset-transfers/{receipt['id']}/chunk/?offset=0",+ data=data[:10],+ headers={"Content-Type": "application/octet-stream"},+ )+ console.wait_until(+ "() => Number(document.querySelector('[role=progressbar]')?.getAttribute('aria-valuenow')) > 0"+ )+ rest.request(+ "PUT",+ f"/api/dataset-transfers/{receipt['id']}/chunk/?offset=10",+ data=data[10:],+ headers={"Content-Type": "application/octet-stream"},+ )+ 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')"+ )+++def keep_the_brief_when_the_cli_attaches_data(+ console, workshop, cli, sample_agent, project, worker, tmp_path+):+ brief = "Classify refund requests; retain uncertain labels for review."+ console.goto(f"/datasets?projectId={project}")+ console.command("New dataset")+ console.fill("#dataset-name", "Brief before data")+ console.fill("#dataset-brief", brief)+ console.press("Create dataset")++ def draft():+ return next(+ (+ row+ for row in workshop.call("list_datasets", {})["datasets"]+ if row["name"] == "Brief before data"+ ),+ None,+ )++ dataset = settle(worker, draft)["id"]+ before = workshop.call("inspect_dataset", {"dataset": dataset})+ assert before["brief"] == brief and before["active"] is None+ assert upload(cli, sample_agent, tickets(tmp_path), "--dataset", dataset) == dataset+ drain(worker)+ after = workshop.call("inspect_dataset", {"dataset": dataset})+ assert after["brief"] == brief+ assert after["active"]["rows"] == 3+ assert after["intent"] == before["intent"]+ console.goto(f"/datasets/{dataset}?projectId={project}")+ console.sees("Brief before data")+ console.sees("Refund order 0 please", exact=False)+++def land_selected_traces_as_rows(workshop, fake_llm, worker):+ triage = workshop.capability("triage")+ [execution] = workshop.call(+ "query_traces",+ {"capability": "triage", "all_spans": True, "span_type": "entry_point", "name": "triage"},+ )["traces"]+ created = workshop.call(+ "create_dataset_from_traces",+ {+ "name": "triage",+ "intent": "eval",+ "capability": triage["id"],+ "trace_ids": [execution["trace_id"]],+ },+ )+ drain(worker)+ [row] = workshop.call(+ "query_dataset", {"dataset": created["dataset"]["id"], "sql": "select * from t"}+ )["rows"]+ assert TICKET in json.dumps(row)+ assert row["capability_id"] == triage["id"]+ assert row["input"]["ticket"] == TICKET+ expected_score = execution["trajectory_score"]+ if expected_score is None:+ expected_score = execution["eval_score"]+ assert row["score"] == expected_score+ assert row["prompt_tokens"] + row["completion_tokens"] == sum(+ request.total_tokens+ for request in fake_llm.requests+ if request.system.startswith("You triage")+ )+ assert [m["content"] for m in row["messages"] if m["role"] == "user"] == [TICKET]+ assert row["output"] == "refund"+ assert row["tools"] is None+ assert row["messages"][-1]["content"] == "refund"+++def open_traces_selected_in_the_console(console, workshop, project, live_api, worker):+ console.goto(f"/observability?projectId={project}")+ console.click("Traces")+ console.sees("handle_ticket")+ console._browser.call(+ lambda: console._page.get_by_role("checkbox", name="Select row", exact=True).first.click()+ )+ console.press("Add to dataset")+ console.fill("#dataset-name", "Selected trace source")+ console.sees("None")++ def create():+ with console._page.expect_response(+ lambda response: (+ response.request.method == "POST"+ and response.url.rstrip("/").endswith("/api/datasets")+ )+ ) as response:+ console._page.get_by_role("button", name="Create dataset", exact=True).click()+ return response.value.status, response.value.json()++ status, result = console._browser.call(create)+ assert status == 201, result++ def landed():+ datasets = workshop.call("list_datasets", {"search": "Selected trace source"})["datasets"]+ if not datasets:+ return None+ dataset = workshop.call("inspect_dataset", {"dataset": datasets[0]["id"]})+ return dataset if dataset["active"] else None++ dataset = settle(worker, landed)+ assert dataset["active"]["rows"] == 1+ assert dataset["source_kind"] == "traces"+ assert dataset["intent"] == "pending"+ assert dataset["capability"] is None+ console.wait_until(+ f"() => location.pathname === '/datasets/{dataset['id']}' "+ "&& !!document.querySelector('article [data-cell-frame]')"+ )+ console.sees("Intent pending", exact=False)+ console.press("Prepare with agent")+ prompt = console._browser.call(+ lambda: console._page.get_by_role("textbox", name="Preparation prompt").input_value()+ )+ for fact in (dataset["id"], project, dataset["active"]["fingerprint"], live_api.url):+ assert fact in prompt+ console.save_evidence("trace-workshop-prepare")++ [trace] = workshop.call("query_traces", {})["traces"]+ without_events = Dataset.objects.create(+ project_id=project,+ name="Trace landing without live events",+ source_kind="traces",+ state="landing",+ )+ console._browser.call(+ lambda: console._page.route("**/api/datasets/*/events/", lambda route: route.abort())+ )+ console.goto(f"/datasets/{without_events.id}?projectId={project}")+ console.sees("Reading source data")+ land.land_traces(without_events, {"trace_ids": [trace["trace_id"]]})+ console.wait_until("() => !!document.querySelector('article [data-cell-frame]')")+ console._browser.call(lambda: console._page.unroute("**/api/datasets/*/events/"))+++def read_a_scanned_document_once_per_page(workshop, cli, sample_agent, worker):+ datasets = []+ for number in range(2):+ draft = workshop.call(+ "start_dataset",+ {+ "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"]})+ uploaded = json.loads(+ cli.run(+ "dataset",+ "upload",+ str(SCANNED),+ "--dataset",+ draft,+ "--json",+ cwd=sample_agent.repo,+ )+ )+ assert uploaded["id"] == draft+ drain(worker)+ detail = workshop.call("inspect_dataset", {"dataset": draft})+ assert detail["ocr_languages"] == ["eng"]+ ocr = detail["sources"][0]["extraction"]["ocr"]+ assert ocr["pages_reused"] == number+ assert ocr["languages"] == ["eng"]+ assert ocr["requested_languages"] == ["eng"]+ datasets.append(draft)+ invalid = workshop.call_result(+ "update_dataset", {"dataset": datasets[0], "ocr_languages": ["not-installed"]}+ )+ assert invalid.isError+++def publish_version_bound_analytics(workshop, cli, sample_agent, rest, worker, tmp_path):+ source_file = tmp_path / "imbalanced.jsonl"+ source_file.write_text(+ "".join(json.dumps({"amount": i, "fraud": int(i == 1000)}) + "\n" for i in range(1001))+ )+ dataset = upload(cli, sample_agent, source_file, "--intent", "train")+ drain(worker)+ source = workshop.call("inspect_dataset", {"dataset": dataset})["active"]+ result = workshop.call(+ "import_dataset_version",+ {+ "dataset": dataset,+ "source_cell": source["id"],+ "source_fingerprint": source["fingerprint"],+ "name": "Fraud decisions",+ "request_key": "analytics-transform",+ "provenance": "Test fixture encodes the supplied fraud label without changing rows.",+ "imported_rows": [+ {+ "source_row": i,+ "decision": {+ "state": json.dumps({"amount": i}),+ "question": "Fraud?",+ "kind": "choice",+ "options": ["No", "Yes"],+ "target_probabilities": [int(i != 1000), int(i == 1000)],+ "target_semantics": "categorical_gold",+ },+ }+ for i in range(1001)+ ],+ },+ )+ drain(worker)+ receipt = workshop.call("get_job", {"kind": "dataset_pipeline", "id": result["job"]["id"]})+ assert receipt["status"] == "completed", receipt+ detail = workshop.call("inspect_dataset", {"dataset": dataset})+ cell = next(cell for cell in detail["cells"] if cell["id"] == detail["active"]["id"])+ report = cell["analytics"]+ assert report["fingerprint"] == cell["fingerprint"]+ assert report["cell"] == cell["id"]+ assert report["families"][0]["counts"] == [1000, 1]+ assert report["rows_scanned"] == 1001+ assert (+ next(c for c in report["checks"] if c["id"] == "targets.class_balance")["status"]+ == "warning"+ )+ assert receipt["progress"]["analytics"]["fingerprint"] == report["fingerprint"]+ rest_cell = next(+ c+ for c in rest.request("GET", f"/api/datasets/{dataset}/")["cells"]+ if c["id"] == cell["id"]+ )+ assert rest_cell["analytics"] == report+++def keep_one_preparation_until_the_agent_finishes(+ console, workshop, cli, sample_agent, project, worker, tmp_path+):+ dataset = workshop.call(+ "start_dataset",+ {"name": "Continuous preparation", "brief": "Prepare support rows", "intent": "train"},+ )["dataset"]["id"]+ console.goto(f"/datasets?projectId={project}")+ console.sees("Continuous preparation")+ args = {"dataset": dataset, "request_key": "continuous-preparation"}+ started = workshop.call("start_dataset_preparation", args)["preparation_workflow"]+ assert (+ workshop.call("start_dataset_preparation", args)["preparation_workflow"]["id"]+ == started["id"]+ )+ console.sees("Preparing")+ workflow = {"dataset": dataset, "preparation_id": started["id"]}+ assert workshop.call_result(+ "update_dataset_preparation", {**workflow, "state": "completed"}+ ).isError+ assert workshop.call_result(+ "start_dataset_preparation", {**args, "request_key": "another"}+ ).isError+ upload(cli, sample_agent, tickets(tmp_path), "--dataset", dataset)+ drain(worker)+ source = workshop.call("inspect_dataset", {"dataset": dataset})["active"]+ result = workshop.call(+ "import_dataset_version",+ {+ "dataset": dataset,+ "source_cell": source["id"],+ "source_fingerprint": source["fingerprint"],+ "name": "Prepared support",+ "request_key": "continuous-import",+ "provenance": "Journey creates source-bound support messages",+ "imported_rows": [+ {+ "source_row": i,+ "messages": [+ {"role": "user", "content": f"Refund order {i}"},+ {"role": "assistant", "content": "Your refund is ready."},+ ],+ }+ for i in range(3)+ ],+ },+ )+ drain(worker)+ receipt = workshop.call("get_job", {"kind": "dataset_pipeline", "id": result["job"]["id"]})+ assert receipt["status"] == "completed", receipt+ console.sees("Preparing")+ current = workshop.call("inspect_dataset_workbench", {"dataset": dataset})+ assert current["preparation_workflow"]["state"] == "preparing"+ events = workshop.read("overmind://activity")["results"]+ preparation_events = [e for e in events if e["kind"] == "dataset_preparation"]+ assert len(preparation_events) == 1+ event_id = preparation_events[0]["id"]+ assert not [e for e in events if e["task_id"] == result["job"]["id"]]+ workshop.call("update_dataset_preparation", {**workflow, "state": "paused"})+ console.sees("Preparation paused")+ workshop.call("update_dataset_preparation", {**workflow, "state": "preparing"})+ console.sees("Preparing")+ output = workshop.call("inspect_dataset", {"dataset": dataset})["active"]["id"]+ completion = {**workflow, "state": "completed", "outputs": [output]}+ workshop.call("update_dataset_preparation", completion)+ workshop.call("update_dataset_preparation", completion)+ console.press("unread notification")+ console.wait_until(+ f"() => document.querySelector('[data-activity-id=\"{event_id}\"]')?.dataset.activityStatus === 'completed'"+ )+ console.sees("Ready")+ assert workshop.call_result(+ "update_dataset_preparation", {**workflow, "state": "preparing"}+ ).isErrordiff --git a/tests/journeys/test_data_workshop.py b/tests/journeys/test_data_workshop.pydeleted file mode 100644index a34e2c37..00000000--- a/tests/journeys/test_data_workshop.py+++ /dev/null@@ -1,269 +0,0 @@-import json--import pytest--from .datasets import evaluate, tickets, upload-from .stack import drain---def test_cli_batch_lands_once_and_mcp_retains_all_sources(- workshop, cli, sample_agent, worker, tmp_path-):- paths = [tmp_path / "first.jsonl", tmp_path / "second.jsonl"]- for index, path in enumerate(paths):- path.write_text(json.dumps({"value": index}) + "\n")- arguments = ["dataset", "upload", *(str(path) for path in paths), "--json"]- uploaded = json.loads(cli.run(*arguments, cwd=sample_agent.repo))- drain(worker)- replay = json.loads(cli.run(*arguments, cwd=sample_agent.repo))- assert replay["id"] == uploaded["id"]- assert replay["transfer"]["id"] == uploaded["transfer"]["id"]- inspected = workshop.call("inspect_dataset", {"dataset": uploaded["id"]})- assert inspected["active"]["rows"] == 2- assert inspected["cell_page"]["total"] == 1- assert [source["filename"] for source in inspected["sources"]] == [path.name for path in paths]- rows = workshop.call(- "query_dataset",- {"dataset": uploaded["id"], "sql": "SELECT value FROM t ORDER BY source_row"},- )["rows"]- assert rows == [{"value": 0}, {"value": 1}]---def test_an_uploaded_eval_source_is_usable_and_use_freezes_its_version(- workshop, cli, sample_agent, worker, tmp_path-):- answer = workshop.capability("answer")- dataset = upload(- cli, sample_agent, tickets(tmp_path), "--intent", "eval", "--capability", answer["id"]- )- drain(worker)- prepared = workshop.call("inspect_dataset", {"dataset": dataset})["active"]- assert prepared["fits"]["ok"] is True-- ready = workshop.call("check_evaluation_readiness", {"dataset": dataset})- assert ready["dataset"]["cell"]["fingerprint"] == prepared["fingerprint"]-- run = evaluate(workshop, dataset)- drain(worker)- assert run["cell"]["version"] == "1.0"- assert run["cell"]["fingerprint"] == prepared["fingerprint"]- [candidate] = run["runs"]- assert workshop.read(candidate["resource"]["uri"])["status"] == "completed"-- frozen = next(- c- for c in workshop.call("inspect_dataset", {"dataset": dataset})["cells"]- if c["id"] == run["cell"]["id"]- )- assert frozen["frozen"] is True- assert frozen["version"] == "1.0"---def test_an_unreadable_file_is_refused_before_it_becomes_a_dataset(- workshop, cli, sample_agent, tmp_path-):- broken = tmp_path / "broken.jsonl"- broken.write_bytes(b"\x00\x01garbage{not json\n")- with pytest.raises(AssertionError, match="transfer_conflict"):- upload(cli, sample_agent, broken, "--intent", "eval")-- assert workshop.call("list_datasets", {"search": "broken"})["datasets"] == []---def test_trace_landing_preserves_source_text_for_explicit_transformation(- workshop, sample_agent, live_api, support_desk_llm, worker-):- ticket = "Refund order 42 please, mail me at [email protected]"- sample_agent.run(- ticket,- api_url=live_api.url,- llm_url=support_desk_llm,- )- drain(worker)- [execution] = workshop.call("query_traces", {"capability": "answer"})["traces"]- created = workshop.call(- "create_dataset_from_traces",- {"name": "with pii", "trace_ids": [execution["trace_id"]], "intent": "eval"},- )- drain(worker)- rows = workshop.call(- "query_dataset", {"dataset": created["dataset"]["id"], "sql": "select * from t"}- )["rows"]- assert ticket in json.dumps(rows)--[email protected]("surface", ["mcp", "rest"])[email protected]("slug", ["triage", "answer"])[email protected]("capture", [False, True])[email protected]("selection", ["ids", "filter"])-def test_trace_rows_carry_the_capability_they_were_selected_for(- workshop,- sample_agent,- live_api,- support_desk_llm,- worker,- cli,- rest_for,- surface,- slug,- capture,- selection,- fake_llm,-):- ticket = "Refund order 42 please"- if capture:- agent = sample_agent.repo / "support_desk" / "agent.py"- source = agent.read_text()- for name in ("triage", "answer"):- source = source.replace(- f"def {name}(", f'@overmind.observe(ignore=["client"])\ndef {name}('- )- agent.write_text(source)- sample_agent.run(ticket, api_url=live_api.url, llm_url=support_desk_llm)- drain(worker)- capability = workshop.capability(slug)- [execution] = workshop.call(- "query_traces",- {"capability": slug, "all_spans": True, "span_type": "entry_point", "name": slug},- )["traces"]- arguments = {"name": slug, "intent": "eval", "capability": capability["id"]}- source = {"trace_ids": [execution["trace_id"]]}- if selection == "filter":- source = {"filters": {"capability": capability["id"]}}- arguments.pop("capability")- if surface == "mcp":- created = workshop.call("create_dataset_from_traces", {**arguments, **source})- dataset = created["dataset"]["id"]- else:- dataset = rest_for(cli.project_key(sample_agent)).request(- "POST",- "/api/datasets/",- json={**arguments, "project": workshop.project()["id"], "source": {"traces": source}},- )["id"]- drain(worker)- [row] = workshop.call(- "query_dataset",- {"dataset": dataset, "sql": "select * from t"},- )["rows"]- assert row["capability_id"] == capability["id"]- assert row["input"]["ticket"] == ticket, row- expected_score = execution["trajectory_score"]- if expected_score is None:- expected_score = execution["eval_score"]- assert row["score"] == expected_score- prefix = "You triage" if slug == "triage" else "You are a support agent."- assert row["prompt_tokens"] + row["completion_tokens"] == sum(- request.total_tokens for request in fake_llm.requests if request.system.startswith(prefix)- )- messages = row["messages"]- assert [m["content"] for m in messages if m["role"] == "user"] == [- ticket if slug == "triage" else f"[refund] {ticket}"- ]- if slug == "triage":- assert row["output"] == "refund"- assert row["tools"] is None- assert messages[-1]["content"] == "refund"- else:- assert row["input"]["category"] == "refund"- assert row["output"] == "Your refund is on its way. The order was delivered."- assert row["tools"][0]["function"]["name"] == "lookup_order"- assert any(m["role"] == "tool" for m in messages)---def test_repeated_capability_invocations_refuse_to_publish_a_mixed_example(- workshop, sample_agent, live_api, support_desk_llm, worker-):- agent = sample_agent.repo / "support_desk" / "agent.py"- agent.write_text(- agent.read_text().replace(- "return answer(client, ticket, triage(client, ticket))",- 'triage(client, "A different ticket")\n return answer(client, ticket, triage(client, ticket))',- )- )- sample_agent.run("Refund order 42 please", api_url=live_api.url, llm_url=support_desk_llm)- drain(worker)- [trace] = workshop.call("query_traces", {})["traces"]- created = workshop.call(- "create_dataset_from_traces",- {- "name": "Repeated triage",- "trace_ids": [trace["trace_id"]],- "capability": workshop.capability("triage")["id"],- },- )- drain(worker)- dataset = workshop.call("inspect_dataset", {"dataset": created["dataset"]["id"]})- assert dataset["state"] == "error"- assert "2 separate invocations" in dataset["error"]- assert dataset["cells"] == []---def test_a_source_capability_filter_is_preserved_when_the_destination_differs(- workshop, sample_agent, live_api, support_desk_llm, worker-):- sample_agent.run("Refund order 42 please", api_url=live_api.url, llm_url=support_desk_llm)- drain(worker)- triage = workshop.capability("triage")- answer = workshop.capability("answer")- created = workshop.call(- "create_dataset_from_traces",- {- "name": "Triage source for answer",- "filters": {"capability": triage["id"]},- "capability": answer["id"],- },- )- drain(worker)- dataset_id = created["dataset"]["id"]- [row] = workshop.call(- "query_dataset",- {- "dataset": dataset_id,- "sql": "select capability_id, messages from t",- },- )["rows"]- assert row["capability_id"] == triage["id"]- assert row["messages"][-1]["content"] == "refund"- assert (- workshop.call("inspect_dataset", {"dataset": dataset_id})["capability"]["id"]- == answer["id"]- )--[email protected]("languages", [[], ["eng"]])-def test_mcp_ocr_language_choice_survives_cli_upload_and_reuses_pages(- workshop, cli, sample_agent, worker, languages-):- from pathlib import Path-- path = Path(__file__).parents[1] / "fixtures/documents/scanned.pdf"- datasets = []- for number in range(2):- draft = workshop.call(- "start_dataset",- {- "brief": "Keep document evidence for OCR verification.",- "name": f"OCR source {number}",- "intent": "explore",- },- )["dataset"]["id"]- workshop.call("update_dataset", {"dataset": draft, "ocr_languages": languages})- uploaded = json.loads(- cli.run(- "dataset", "upload", str(path), "--dataset", draft, "--json", cwd=sample_agent.repo- )- )- assert uploaded["id"] == draft- drain(worker)- detail = workshop.call("inspect_dataset", {"dataset": draft})- assert detail["ocr_languages"] == languages- assert detail["sources"][0]["extraction"]["ocr"]["pages_reused"] == number- assert detail["sources"][0]["extraction"]["ocr"]["languages"] == ["eng"]- assert detail["sources"][0]["extraction"]["ocr"]["requested_languages"] == languages- datasets.append(draft)- invalid = workshop.call_result(- "update_dataset", {"dataset": datasets[0], "ocr_languages": ["not-installed"]}- )- assert invalid.isError- workshop.call("update_dataset", {"dataset": datasets[0], "ocr_languages": []})- assert workshop.call("inspect_dataset", {"dataset": datasets[0]})["ocr_languages"] == []diff --git a/tests/journeys/test_decide.py b/tests/journeys/test_decide.pynew file mode 100644index 00000000..f6e12940--- /dev/null+++ b/tests/journeys/test_decide.py@@ -0,0 +1,195 @@+import json+import re++import pytest+import requests++from .datasets import until, upload+from .stack import drain++pytestmark = pytest.mark.covers("decide")++PREPARE = "overbae.tasks.training_preparation.reconcile"+TRAIN = "overbae.tasks.finetuning_reconciler.reconcile_finetuning_jobs"+DEPLOY = "overbae.tasks.inference_controller.reconcile_deployments"+EVALUATE = "overbae.tasks.native_evaluation.reconcile"+MODEL = "OvermindLab/qwen-3.5-0.8B-decision"+FOUNDATION = "Qwen/Qwen3.5-0.8B"+QUESTION = "Approve refund?"+++def _state(i: int) -> str:+ return f"Refund request {i}: order {i} arrived damaged."+++def _approves(state: str) -> bool:+ return int(re.search(r"Refund request (\d+)", state)[1]) % 3 != 0+++def _rows(path, n, *, evaluation: bool):+ rows = []+ for i in range(n):+ target = [0, 1] if _approves(_state(i)) else [1, 0]+ decision = {+ "state": _state(i),+ "question": QUESTION,+ "kind": "choice",+ "options": ["No", "Yes"],+ }+ if evaluation:+ rows.append(+ {"input": {"decision": decision}, "expected_output": {"probabilities": target}}+ )+ else:+ rows.append(+ {+ "decision": {+ **decision,+ "target_probabilities": target,+ "target_semantics": "categorical_gold",+ }+ }+ )+ path.write_text("".join(json.dumps(row) + "\n" for row in rows))+ return path+++def _answer(request: dict, trained: bool) -> list[float]:+ if not trained:+ return [0.5, 0.5]+ return [0.1, 0.9] if _approves(request["state"]) else [0.9, 0.1]+++def test_decide(+ workshop,+ cli,+ sample_agent,+ rest_for,+ live_api,+ worker,+ sft,+ serving,+ decisions,+ fake_modal,+ beat,+ console,+ tmp_path,+):+ decisions.answer = _answer+ project = workshop.project()["id"]+ rest = rest_for(workshop.api_key)+ train = upload(+ cli,+ sample_agent,+ _rows(tmp_path / "train.jsonl", 40, evaluation=False),+ "--intent",+ "train",+ )+ evals = upload(+ cli, sample_agent, _rows(tmp_path / "eval.jsonl", 12, evaluation=True), "--intent", "eval"+ )+ drain(worker)+ readiness = workshop.call("check_finetune_readiness", {"dataset": train})+ assert readiness["dataset"]["validation"]["valid"] is True+ assert readiness["dataset"]["validation"]["format"] == "decision"+ assert readiness["training_contract"]["inference_contract"] == "decision"++ started = workshop.call(+ "start_decision_job",+ {+ "request_key": "approve-refunds",+ "dataset": train,+ "eval_dataset": evals,+ "base_model": MODEL,+ },+ )+ job = started["training_run"]["id"]+ drain(worker)++ def finetune():+ return workshop.read(f"overmind://finetunes/{job}")++ until(beat, lambda: fake_modal.pending("prepare_"), PREPARE, TRAIN)+ fake_modal.release("prepare_")+ until(beat, lambda: fake_modal.pending("sft_"), PREPARE, TRAIN)+ fake_modal.release("sft_")+ until(beat, lambda: finetune()["deployed_model"], PREPARE, TRAIN, DEPLOY)+ deployment = finetune()["deployed_model"]+ until(+ beat,+ lambda: workshop.read(f"overmind://deployments/{deployment}")["status"] == "ready",+ TRAIN,+ DEPLOY,+ )+ until(beat, lambda: finetune()["status"] == "succeeded", TRAIN, DEPLOY)+ record = finetune()["record"]+ assert record["contract"]["inference_contract"] == "decision"+ assert record["artifact"]["reload_verification"]["decisions"] > 0+ labels = record["prediction_labels"]+ assert labels["state"] == "available"+ assert [s["options"] for s in labels["label_sets"]] == [["No", "Yes"]]++ final_cell = workshop.call("inspect_dataset", {"dataset": evals})["active"]["id"]+ comparison = workshop.call(+ "create_native_evaluation",+ {+ "name": "Refund approvals before and after training",+ "request_key": "approve-refunds-quality",+ "final_cell": final_cell,+ "baseline": "base",+ "bootstrap_samples": 2,+ "participants": [+ {"key": "base", "name": "Base model", "kind": "foundation", "model": FOUNDATION},+ {"key": "trained", "name": "Trained model", "kind": "trained", "job": job},+ ],+ },+ )+ evaluation = comparison["workflow"]["id"]+ workshop.call("launch_native_evaluation", {"evaluation": evaluation})++ def measured():+ return workshop.call("inspect_native_evaluation", {"evaluation": evaluation})++ until(beat, lambda: measured()["monitoring"]["evaluation_state"] == "completed", EVALUATE)+ arms = {arm["key"]: arm["benchmarks"][0] for arm in measured()["monitoring"]["arms"]}+ assert arms["base"]["scored"] == arms["trained"]["scored"] == 12+ before, after = arms["base"]["raw"], arms["trained"]["raw"]+ assert after["cross_entropy"]["mean"] < before["cross_entropy"]["mean"]+ assert after["accuracy"]["mean"] > before["accuracy"]["mean"]+ monitor = f"/api/native-evaluations/{evaluation}/monitor/"+ assert rest.request("GET", monitor)["count"] == 12+ assert rest.request("GET", monitor + "?outcome=incorrect&participant=base")["count"] == 8+ assert rest.request("GET", monitor + "?outcome=incorrect&participant=trained")["count"] == 0++ group = rest.request("GET", f"/api/finetuning-jobs/{job}/")["group_id"]+ console.goto(f"/training?projectId={project}&groupId={group}&jobId={job}")+ console.sees("Prediction labels")+ console.sees("2 labels")+ console.sees("Succeeded")+ console.goto(f"/evaluations/runs/{evaluation}?projectId={project}&format=decision")+ console.sees("Model comparison")+ console.sees("Trained model")+ console.sees("100.0%")+ console.save_evidence("decide-quality")++ model_id = workshop.read(f"overmind://deployments/{deployment}")["model_id"]+ answered = requests.post(+ f"{live_api.url}/api/v1/systemone",+ headers={"Authorization": f"Bearer {workshop.api_key}"},+ json={+ "model": model_id,+ "state": _state(4),+ "questions": {+ "approve": {+ "type": "choice",+ "instructions": QUESTION,+ "criteria": {"No": "", "Yes": ""},+ }+ },+ },+ timeout=30,+ )+ assert answered.status_code == 200, answered.text+ approve = answered.json()["answers"]["approve"]+ assert approve["choice"] == "Yes"+ assert approve["probabilities"] == {"No": 0.1, "Yes": 0.9}diff --git a/tests/journeys/test_agent_testing.py b/tests/journeys/test_evaluate.pysimilarity index 77%rename from tests/journeys/test_agent_testing.pyrename to tests/journeys/test_evaluate.pyindex a8a85ca6..e54bc90c 100644--- a/tests/journeys/test_agent_testing.py+++ b/tests/journeys/test_evaluate.py@@ -1,12 +1,14 @@+import pytest+from .datasets import JUDGE, tickets, uploadfrom .stack import drain+pytestmark = pytest.mark.covers("evaluate")+WEAK_REPLY = "Your refund is on its way."-def test_a_backtest_compares_every_candidate_with_the_recorded_baseline(- workshop, cli, sample_agent, worker, tmp_path, fake_llm-):+def test_evaluate(workshop, cli, sample_agent, worker, tmp_path, fake_llm, console):fake_llm.extra_models.append("fake/weak")fake_llm.on(lambda r: r.model == "fake/weak", WEAK_REPLY)answer = workshop.capability("answer")@@ -47,3 +49,12 @@ def test_a_backtest_compares_every_candidate_with_the_recorded_baseline(assert compared["candidate"]["overall"]["status"] == "unchanged"assert compared["weak"]["overall"]["status"] == "regressed"assert compared["weak"]["losses"] == 3++ project = workshop.project()["id"]+ console.goto(f"/evaluations?projectId={project}")+ for label in ("recorded", "candidate", "weak"):+ console.sees(f"backtest · {label}")+ console.click("backtest · weak")+ console.sees("Re-run")+ console.sees("Optimise")+ console.save_evidence("evaluate-weak-run")diff --git a/tests/journeys/test_http_api.py b/tests/journeys/test_http_api.pynew file mode 100644index 00000000..32ed29e0--- /dev/null+++ b/tests/journeys/test_http_api.py@@ -0,0 +1,18 @@+import pytest++pytestmark = pytest.mark.covers("http-api")+++def test_project_surfaces_render_without_browser_or_server_errors(console, workshop):+ project = workshop.project()["id"]+ for route, text in [+ ("datasets", "Datasets"),+ ("training", "Train model"),+ ("evaluations", "Evaluations"),+ ("inference", "Inference"),+ ("optimiser", "Optimiser"),+ ]:+ console.goto(f"/{route}?projectId={project}")+ console.sees(text)+ console.healthy()+ console.save_evidence(f"project-surface-{route}")diff --git a/tests/journeys/test_agent_model.py b/tests/journeys/test_identity.pysimilarity index 68%rename from tests/journeys/test_agent_model.pyrename to tests/journeys/test_identity.pyindex d5169e9b..bf506fa9 100644--- a/tests/journeys/test_agent_model.py+++ b/tests/journeys/test_identity.py@@ -1,5 +1,7 @@import pytest+pytestmark = pytest.mark.covers("identity")+@pytest.fixturedef synced(cli, mcp_for, sample_agent, worker):@@ -8,19 +10,6 @@ def synced(cli, mcp_for, sample_agent, worker):return mcp_for(cli.project_key(sample_agent))-def test_a_scanned_agent_syncs_its_capabilities_and_checkout(synced, sample_agent):- snapshot = synced.project()["repository_snapshot"]- assert snapshot["commit"] == sample_agent.commit()- assert snapshot["dirty"] is False- assert snapshot["scanned_at"]-- for slug, truth in sample_agent.truth["capabilities"].items():- capability = synced.capability(slug)- assert capability["name"] == truth["name"]- assert capability["model"] == truth["model"]- assert capability["status"] == "current"--def test_a_capability_the_scan_misses_leaves_the_agent_and_returns_in_place(synced, cli, sample_agent):diff --git a/tests/journeys/test_inference_client.py b/tests/journeys/test_inference_client.pydeleted file mode 100644index f770b3b2..00000000--- a/tests/journeys/test_inference_client.py+++ /dev/null@@ -1,52 +0,0 @@-import pytest-from overmind.client import Client, OvermindInferenceError--from overbae.models import DeployedModel, Project---def client(cli, mcp_for, sample_agent, live_api):- cli.scan(sample_agent)- cli.sync(sample_agent)- key = cli.project_key(sample_agent)- project = Project.objects.get(pk=mcp_for(key).project()["id"])- DeployedModel.objects.create(- project=project,- model_id="ft-sdk-journey",- status=DeployedModel.Status.READY,- base_model_id="Qwen/Qwen3-1.7B",- max_model_len=16384,- )- return Client(api_key=key, base_url=live_api.url)---MESSAGES = [{"role": "user", "content": "Where is order 42?"}]---def test_the_sdk_client_reaches_served_and_frontier_models_through_the_gateway(- client, fake_llm, scripted-):- fake_llm.on(lambda r: "inference.test" in r.url, "Order 42 shipped today.")- fake_llm.on(lambda r: "openrouter.ai" in r.url, "Order 42 is in transit.")-- served = client.chat.completions.create(model="ft-sdk-journey", messages=MESSAGES)- assert served.choices[0].message.content == "Order 42 shipped today."- assert served.usage.total_tokens > 0-- streamed = client.chat.completions.create(- model="ft-sdk-journey", messages=MESSAGES, stream=True- )- assert "".join(c.choices[0].delta.content or "" for c in streamed) == "Order 42 shipped today."-- frontier = client.chat.completions.create(model="openai/gpt-5-mini", messages=MESSAGES)- assert frontier.choices[0].message.content == "Order 42 is in transit."-- listed = {model.id for model in client.models.list().data}- assert "ft-sdk-journey" in listed- assert client.models.get("ft-sdk-journey").id == "ft-sdk-journey"- with pytest.raises(OvermindInferenceError, match="HTTP 404"):- client.models.get("ft-nobody")-- scripted("http://inference.test").reply(json_body={"ok": True})- assert client.models.delete("ft-sdk-journey").deleted is True- assert DeployedModel.objects.get(model_id="ft-sdk-journey").status == "deleted"diff --git a/tests/journeys/test_interface_discovery.py b/tests/journeys/test_interface_discovery.pydeleted file mode 100644index a6438a4d..00000000--- a/tests/journeys/test_interface_discovery.py+++ /dev/null@@ -1,7 +0,0 @@-def test_account_discovery_agrees_with_the_connected_contract(account_key, mcp_for):- mcp = mcp_for(account_key)- discovery = mcp.discover()- interface = mcp.read("overmind://interface/current")- assert interface["contract_version"] == discovery["version"]- assert interface["tool_count"] == len(discovery["tools"])- assert "resume_dataset_import" in discovery["tools"]diff --git a/tests/journeys/test_kit_connectors.py b/tests/journeys/test_kit_connectors.pydeleted file mode 100644index 4bc57c79..00000000--- a/tests/journeys/test_kit_connectors.py+++ /dev/null@@ -1,83 +0,0 @@-import json-from datetime import UTC, datetime, timedelta--import pytest-from fakes.vendors import (- BraintrustAPI,- GalileoAPI,- LangfuseAPI,- LangSmithAPI,- support_desk_trace,-)--from overbae.models import ConnectorCredential--from .stack import drain--VENDORS = {- "langfuse": (LangfuseAPI, {"LANGFUSE_PUBLIC_KEY": "pk-fake", "LANGFUSE_SECRET_KEY": "sk-fake"}),- "langsmith": (LangSmithAPI, {"LANGSMITH_API_KEY": "ls-fake"}),- "braintrust": (BraintrustAPI, {"BRAINTRUST_API_KEY": "bt-fake"}),- "galileo": (GalileoAPI, {"GALILEO_API_KEY": "gl-fake"}),-}--[email protected]("vendor", sorted(VENDORS))-def test_a_recorded_vendor_trace_lands_as_one_rooted_tree(- vendor, cli, mcp_for, sample_agent, worker, fake_llm, monkeypatch-):- api_class, credentials = VENDORS[vendor]- api = api_class()- trace_id, steps = support_desk_trace(datetime.now(UTC) - timedelta(hours=1))- api.record(trace_id, steps)- fake_llm.network.vendors.append(api)- for env, value in credentials.items():- monkeypatch.setenv(env, value)-- cli.scan(sample_agent)- cli.sync(sample_agent)- mcp = mcp_for(cli.project_key(sample_agent))- answer = mcp.capability("answer")-- added = json.loads(- cli.run("connector", "add", vendor, "--base-url", api.host, "--json", cwd=sample_agent.repo)- )- connector = added["id"]- [source] = mcp.call(- "inspect_connectors", {"connector": connector, "include_source_projects": True}- )["connector"]["source_projects"]- triage = mcp.capability("triage")- mapping = {- "source": "observation_name",- "assignments": {"triage": triage["id"], "answer": answer["id"]},- }- proposed = mcp.call(- "configure_connector",- {- "connector": connector,- "source_project_id": source["id"],- "lookback_days": 7,- "capability_mapping": mapping,- },- )- assert proposed["mapping_pending"] is True- approved = mcp.call("configure_connector", {"connector": connector, "confirm_mapping": True})- assert approved["mapping_pending"] is False-- mcp.call("sync_connector", {"connector": connector})- drain(worker)-- roots = mcp.call("query_traces", {"limit": 10})["traces"]- landed = 0- for root in roots:- spans = mcp.read(f"overmind://traces/{root['trace_id']}")["spans"]- assert len([s for s in spans if s["parent_span_id"] is None]) == 1- landed += len(spans)- assert landed == len(steps)- bound = {root["name"]: root["capability"] for root in roots}- assert bound["triage"] == "triage"- assert bound["answer"] == "answer"- assert sum(root["total_tokens"] or 0 for root in roots) == sum(sum(s.tokens) for s in steps)- # The chunk schedules its own continuation. Leave it inactive so that call- # does not reach the next test's network fake.- ConnectorCredential.objects.filter(pk=connector).update(is_active=False)diff --git a/tests/journeys/test_credits.py b/tests/journeys/test_ledger.pysimilarity index 99%rename from tests/journeys/test_credits.pyrename to tests/journeys/test_ledger.pyindex 65b858fb..c45a1b63 100644--- a/tests/journeys/test_credits.py+++ b/tests/journeys/test_ledger.py@@ -9,6 +9,8 @@ import requestsfrom overbae.models import BillingTelemetry+pytestmark = pytest.mark.covers("ledger")+WEBHOOK_SECRET = "whsec_journey"MODEL = "openai/gpt-4.1-mini"diff --git a/tests/journeys/test_live_dataset_stream.py b/tests/journeys/test_live_dataset_stream.pyindex 6f6caffc..fc613821 100644--- a/tests/journeys/test_live_dataset_stream.py+++ b/tests/journeys/test_live_dataset_stream.py@@ -1,11 +1,14 @@from contextlib import ExitStackimport httpx+import pytestfrom django.db import connectionfrom .datasets import tickets, uploadfrom .stack import drain+pytestmark = [pytest.mark.load, pytest.mark.covers("capacity")]+def _client_connections() -> int:with connection.cursor() as cursor:diff --git a/tests/journeys/test_live_scoring.py b/tests/journeys/test_live_scoring.pydeleted file mode 100644index 1d8f80b5..00000000--- a/tests/journeys/test_live_scoring.py+++ /dev/null@@ -1,349 +0,0 @@-import json-import uuid--import pytest-import requests-from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest-from opentelemetry.proto.common.v1.common_pb2 import AnyValue, KeyValue-from opentelemetry.proto.trace.v1.trace_pb2 import ResourceSpans, ScopeSpans, Span, Status--from overbae.innermind.checks import render--from .conftest import GOOD_REPLY-from .stack import drain--EXPECTATION = "The reply quotes the order id and its status."-RUN_SIGNALS = "overbae.tasks.innermind.run_signals"-SWEEP_SPANS = "overbae.tasks.innermind.sweep_unscored_spans"-SWEEP_TRAJECTORIES = "overbae.tasks.innermind.score_trajectories"-# Past the span sweep's grace period, so every beat re-drives what is still unscored.-SWEEP_WAIT = 120---def project(cli, mcp_for, rest_for, sample_agent, worker, judges):- cli.scan(sample_agent)- cli.sync(sample_agent)- key = cli.project_key(sample_agent)- return mcp_for(key), rest_for(key), key---def _attrs(**values) -> list[KeyValue]:- return [- KeyValue(key=key.replace("__", "."), value=AnyValue(string_value=str(value)))- for key, value in values.items()- ]---class Trace:- """One OTLP trace: a workflow root that answers a ticket and its tool calls."""-- def __init__(self, capability_id: str, reply: str, tools: list[bool]):- self.trace_id = uuid.uuid4().bytes- self.root_id = uuid.uuid4().bytes[:8]- self.capability_id = capability_id- self.reply = reply- self.tools = []- for ok in tools:- self.add_tool(ok)-- def add_tool(self, ok: bool) -> None:- self.tools.append((uuid.uuid4().bytes[:8], ok))-- @property- def hex(self) -> str:- return self.trace_id.hex()-- def request(self, *, root: bool = True, tools: bool = True) -> ExportTraceServiceRequest:- root_span = Span(- trace_id=self.trace_id,- span_id=self.root_id,- name="handle_ticket",- start_time_unix_nano=1_000,- end_time_unix_nano=90_000,- attributes=_attrs(- overmind__capability__id=self.capability_id,- overmind__span_type="workflow",- overmind__input="Refund order 42 please",- overmind__output=self.reply,- overmind__expectations=json.dumps([EXPECTATION]),- ),- )- tool_spans = [- Span(- trace_id=self.trace_id,- span_id=span_id,- parent_span_id=self.root_id,- name="lookup_order",- start_time_unix_nano=2_000 + i * 10_000,- end_time_unix_nano=9_000 + i * 10_000,- status=Status(code=Status.STATUS_CODE_OK if ok else Status.STATUS_CODE_ERROR),- attributes=_attrs(- overmind__capability__id=self.capability_id,- overmind__span_type="tool_call",- gen_ai__tool__name="lookup_order",- overmind__input=f'{{"order_id": "42", "attempt": {i}}}',- overmind__output="delivered" if ok else "",- ),- )- for i, (span_id, ok) in enumerate(self.tools)- ]- spans = [*([root_span] if root else []), *(tool_spans if tools else [])]- return ExportTraceServiceRequest(- resource_spans=[ResourceSpans(scope_spans=[ScopeSpans(spans=spans)])]- )-- def send(self, api_url: str, key: str, *, root: bool = True, tools: bool = True) -> None:- response = requests.post(- f"{api_url}/api/v1/traces",- data=self.request(root=root, tools=tools).SerializeToString(),- headers={"Content-Type": "application/x-protobuf", "X-Api-Key": key},- timeout=30,- )- assert response.status_code == 200, response.text---def test_an_ingested_trace_is_scored_once_per_evidence_with_kept_history(- project, live_api, worker, fake_llm-):- mcp, rest, key = project- answer = mcp.capability("answer")- good = Trace(answer["id"], GOOD_REPLY, tools=[True])- bad = Trace(answer["id"], "Your refund is on its way.", tools=[True])- good.send(live_api.url, key)- bad.send(live_api.url, key)- drain(worker)-- roots = {- row["trace_id"]: row- for row in mcp.call("query_traces", {"capability": "answer", "limit": 10})["traces"]- }- assert roots[good.hex]["eval_score"] > roots[bad.hex]["eval_score"]- assert roots[good.hex]["trajectory_score"] > roots[bad.hex]["trajectory_score"]-- detail = rest.request(- "GET", f"/api/traces/{good.hex}/", params={"project": mcp.project()["id"]}- )- root = next(s for s in detail["spans"] if s["parent_span_id"] is None)- expectation = root["eval_attributes"]["metrics"][EXPECTATION]- assert expectation["verdict"] == "yes"- assert expectation["score"] == 1.0- assert root["eval_attributes"]["score"] == roots[good.hex]["eval_score"]-- def history(trace: Trace) -> list[dict]:- page = rest.request(- "GET",- "/api/eval-scores/",- params={"project": mcp.project()["id"], "trace_id": trace.hex, "page_size": 100},- )- return page["results"]-- first = history(good)- assert {row["source_type"] for row in first} == {"span", "trajectory"}-- judged = len(fake_llm.decisions)- good.send(live_api.url, key)- drain(worker)- assert history(good) == first- assert len(fake_llm.decisions) == judged-- good.reply = "Your refund is on its way."- good.send(live_api.url, key)- drain(worker)- assert len(history(good)) > len(first)-- health = mcp.call("inspect_capability_health", {"capability": "answer"})- assert health["scoring"]["scored"] >= 2- assert any(m["metric"] == EXPECTATION for m in health["scoring"]["metrics"])---def _history(rest, project_id: str, trace: Trace) -> list[dict]:- return rest.request(- "GET",- "/api/eval-scores/",- params={"project": project_id, "trace_id": trace.hex, "page_size": 100},- )["results"]---def _spans(rest, project_id: str, trace: Trace) -> dict[str, dict]:- detail = rest.request("GET", f"/api/traces/{trace.hex}/", params={"project": project_id})- return {span["span_id"]: span for span in detail["spans"]}---def test_spans_are_scored_as_they_land_without_waiting_for_the_root(- project, live_api, worker, fake_llm-):- mcp, rest, key = project- project_id = mcp.project()["id"]- trace = Trace(mcp.capability("answer")["id"], GOOD_REPLY, tools=[True, False])-- trace.send(live_api.url, key, root=False)- drain(worker)- tool_ids = [span_id.hex() for span_id, _ in trace.tools]- before = {- span_id: span["eval_attributes"]- for span_id, span in _spans(rest, project_id, trace).items()- }- assert set(before) == set(tool_ids)- assert all("score" in attributes for attributes in before.values())- assert _history(rest, project_id, trace)-- trace.send(live_api.url, key, tools=False)- drain(worker)- spans = _spans(rest, project_id, trace)- assert {span_id: spans[span_id]["eval_attributes"] for span_id in tool_ids} == before- root = spans[trace.root_id.hex()]["eval_attributes"]- assert root["trajectory"]["span_count"] == 3- trajectories = [- row for row in _history(rest, project_id, trace) if row["source_type"] == "trajectory"- ]- assert len(trajectories) == 1---def test_a_failing_judge_is_tried_three_times_then_scored_with_errors(- project, live_api, worker, fake_llm, beat, clock-):- mcp, rest, key = project- project_id = mcp.project()["id"]- fake_llm.fail(lambda request: request.url.rstrip("/").endswith("/systemone"))-- def judge_calls() -> int:- return sum(r.url.rstrip("/").endswith("/systemone") for r in fake_llm.requests)-- trace = Trace(mcp.capability("answer")["id"], GOOD_REPLY, tools=[True])- trace.send(live_api.url, key)- drain(worker)- per_pass = judge_calls()- assert per_pass > 0-- for _ in range(5):- clock.shift(SWEEP_WAIT)- beat(SWEEP_SPANS, SWEEP_TRAJECTORIES)- # Three span passes over the root's rows, then three trajectory passes of path_judge.- assert judge_calls() == 3 * per_pass + 3-- root = _spans(rest, project_id, trace)[trace.root_id.hex()]- attributes = root["eval_attributes"]- assert {m["error"] for m in attributes["metrics"].values() if m["type"] == "llm"} == {- "scoring failed after 3 attempts"- }- path_judge = attributes["trajectory"]["metrics"]["path_judge"]- assert path_judge["error"] == "scoring failed after 3 attempts"- assert {row["source_type"] for row in _history(rest, project_id, trace)} == {- "span",- "trajectory",- }-- clock.shift(SWEEP_WAIT)- beat(SWEEP_SPANS, SWEEP_TRAJECTORIES)- assert judge_calls() == 3 * per_pass + 3---def test_scored_spans_trajectories_and_drift_verdicts_are_never_judged_again(- project, live_api, worker, fake_llm, beat, clock-):- mcp, rest, key = project- project_id = mcp.project()["id"]- mcp.call("set_signal_subscription", {"signal_type": "plan_drift", "enabled": True})-- trace = Trace(mcp.capability("answer")["id"], GOOD_REPLY, tools=[True])- trace.send(live_api.url, key)- drain(worker)- beat(RUN_SIGNALS)- tool_id = trace.tools[0][0].hex()- # The judges meet an expectation only on the good reply, so the tool step drifts.- assert _spans(rest, project_id, trace)[tool_id]["eval_attributes"]["drift"] == 0.0-- judged = len(fake_llm.decisions)- clock.shift(SWEEP_WAIT)- beat(RUN_SIGNALS, SWEEP_SPANS, SWEEP_TRAJECTORIES)- assert len(fake_llm.decisions) == judged-- trace.add_tool(True)- trace.send(live_api.url, key)- drain(worker)- beat(RUN_SIGNALS)- spans = _spans(rest, project_id, trace)- assert spans[trace.tools[1][0].hex()]["eval_attributes"]["drift"] == 0.0- assert spans[trace.root_id.hex()]["eval_attributes"]["trajectory"]["span_count"] == 2- trajectories = [- row for row in _history(rest, project_id, trace) if row["source_type"] == "trajectory"- ]- assert len(trajectories) == 1-- judged = len(fake_llm.decisions)- clock.shift(SWEEP_WAIT)- beat(RUN_SIGNALS, SWEEP_SPANS, SWEEP_TRAJECTORIES)- assert len(fake_llm.decisions) == judged---def test_default_signals_raise_deduplicated_events_seen_on_every_surface(- project, live_api, worker, beat-):- mcp, rest, key = project- project_id = mcp.project()["id"]- answer = mcp.capability("answer")-- checks = mcp.call("list_signals", {})["signals"]- assert next(check for check in checks if check["signal_type"] == "tool_failure")["enabled"]-- failing = Trace(answer["id"], GOOD_REPLY, tools=[False, False, True])- failing.send(live_api.url, key)- drain(worker)- beat(RUN_SIGNALS)- beat(RUN_SIGNALS)-- events = rest.request(- "GET",- "/api/signal-events/",- params={"project": project_id, "unseen": "true", "signal_type": "tool_failure"},- )["results"]- assert [(e["signal_type"], e["trace_id"]) for e in events] == [("tool_failure", failing.hex)]- assert "lookup_order (2/3)" in events[0]["message"]-- listed = mcp.call("list_signals", {})- assert listed["unseen_events"] >= 1- over_mcp = mcp.read("overmind://signal-events")- assert events[0]["id"] in [e["id"] for e in over_mcp["events"]]- evidence = mcp.call("query_traces", {"signal_event": events[0]["id"]})- assert [trace["trace_id"] for trace in evidence["traces"]] == [failing.hex]-- rest.request("POST", "/api/signal-events/mark-seen/", json={"project": project_id})- assert mcp.call("list_signals", {})["unseen_events"] == 0---def test_json_checks_grade_the_outer_payload_even_when_strings_contain_fences(- project, live_api, worker-):- mcp, rest, key = project- capability = mcp.capability("answer")["id"]- definitions = [- ("outer keys", "json_required_keys", {"REQUIRED_KEYS": ["history"]}),- ("outer shape", "schema_field_conformance", {"FIELDS": {"history": {"type": "array"}}}),- ("outer JSON", "output_is_valid_json", {}),- ]- for name, check, params in definitions:- mcp.call(- "create_eval_matrix_row",- {- "capability": capability,- "name": name,- "type": "deterministic",- "source": render(check, params),- "span_name": "handle_ticket",- },- )- payload = json.dumps({"history": [], "answer": '```json\n{"value":1}\n```'})- for reply, expected in [- (payload, 1.0),- ("```json\n" + payload + "\n```", 1.0),- ('{"broken": ```json\n{"history":[]}\n```}', 0.0),- ]:- trace = Trace(capability, reply, tools=[])- trace.send(live_api.url, key)- drain(worker)- metrics = _spans(rest, mcp.project()["id"], trace)[trace.root_id.hex()]["eval_attributes"][- "metrics"- ]- for name, _, _ in definitions:- assert metrics[name]["score"] == expected, metrics[name]diff --git a/tests/journeys/test_observability.py b/tests/journeys/test_observability.pydeleted file mode 100644index a4e72449..00000000--- a/tests/journeys/test_observability.py+++ /dev/null@@ -1,71 +0,0 @@-import pytest--from .stack import drain--TICKETS = ("Refund order 42 please", "Where is order 42?")---def synced(cli, mcp_for, rest_for, sample_agent, worker):- cli.scan(sample_agent)- cli.sync(sample_agent)- key = cli.project_key(sample_agent)- return mcp_for(key), rest_for(key)---def test_traces_are_scored_on_arrival_and_every_surface_reads_the_same_scores(- synced, sample_agent, live_api, support_desk_llm, judges, worker-):- mcp, rest = synced- sample_agent.run(*TICKETS, api_url=live_api.url, llm_url=support_desk_llm)- drain(worker)-- over_mcp = {- row["trace_id"]: (row["eval_score"], row["trajectory_score"])- for row in mcp.call("query_traces", {"limit": 10})["traces"]- }- page = rest.request("GET", "/api/traces/", params={"project": mcp.project()["id"]})- over_rest = {- row["trace_id"]: (- row["eval_attributes"]["score"],- row["eval_attributes"]["trajectory"]["score"],- )- for row in page["results"]- }- assert len(over_mcp) == len(TICKETS)- assert over_rest == over_mcp- assert all(trajectory < 1 for _, trajectory in over_mcp.values())-- failures = mcp.call("query_failures", {"capability": "answer"})- assert {f["trace_id"] for f in failures["failures"]} == set(over_mcp)- assert mcp.call("inspect_capability_health", {})["scoring"]["trajectories"] == len(TICKETS)- health = mcp.call("inspect_capability_health", {"capability": "answer"})- assert health["scoring"]["pass_rate"] < 1---def test_a_silent_capability_is_named_with_the_fix_that_instruments_it(- synced, sample_agent, live_api, support_desk_llm, judges, worker-):- mcp, rest = synced- agent = sample_agent.repo / "support_desk" / "agent.py"- instrumented = '@overmind.run(capability="triage", capability_id=capability_id("triage"))\n'- agent.write_text(agent.read_text().replace(instrumented, ""))-- def coverage() -> dict[str, int]:- graph = rest.request("GET", "/api/agent/", params={"project": mcp.project()["id"]})- return {c["slug"]: c["trace_count"] for c in graph["capabilities"]}-- sample_agent.run(TICKETS[0], api_url=live_api.url, llm_url=support_desk_llm)- drain(worker)- assert coverage() == {"triage": 0, "answer": 1}-- plan = mcp.call("get_instrumentation_plan", {"capability": "triage"})- [placement] = plan["placements"]- assert placement["target"]["qualname"] == "support_desk.agent.triage"- fix = placement["required_decorator"]- source = agent.read_text()- agent.write_text(source.replace("def triage(", f"{fix}\ndef triage(", 1))-- sample_agent.run(TICKETS[1], api_url=live_api.url, llm_url=support_desk_llm)- drain(worker)- assert coverage() == {"triage": 1, "answer": 2}diff --git a/tests/journeys/test_observe.py b/tests/journeys/test_observe.pynew file mode 100644index 00000000..75890df4--- /dev/null+++ b/tests/journeys/test_observe.py@@ -0,0 +1,452 @@+import json+import uuid+from datetime import UTC, datetime, timedelta++import pytest+from fakes.vendors import LangfuseAPI, support_desk_trace++from overbae.models import ConnectorCredential++from .conftest import GOOD_REPLY+from .otlp import EXPECTATION, RUN_SIGNALS, Trace, score_history, trace_spans+from .stack import drain, drain_scoring, settle++pytestmark = pytest.mark.covers("observe")++TICKETS = ("Refund order 42 please", "Where is order 42?", "Is order 42 refunded?")+++def test_observe(+ console,+ console_url,+ replay_recorder,+ cli,+ mcp_for,+ rest_for,+ sample_agent,+ live_api,+ support_desk_llm,+ judges,+ fake_llm,+ worker,+ beat,+ monkeypatch,+):+ copy_the_onboarding_prompt(console, console_url, live_api)++ cli.scan(sample_agent)+ cli.sync(sample_agent)+ key = cli.project_key(sample_agent)+ mcp, rest = mcp_for(key), rest_for(key)+ project = mcp.project()["id"]+ snapshot = mcp.project()["repository_snapshot"]+ assert snapshot["commit"] == sample_agent.commit()+ assert snapshot["dirty"] is False+ assert snapshot["scanned_at"]+ for slug, truth in sample_agent.truth["capabilities"].items():+ capability = mcp.capability(slug)+ assert capability["name"] == truth["name"]+ assert capability["model"] == truth["model"]+ assert capability["status"] == "current"+ keep_new_api_keys_out_of_session_replay(console, project, replay_recorder)++ sdk_traces_arrive_as_rooted_trees(+ mcp, rest, sample_agent, live_api, support_desk_llm, fake_llm, worker+ )+ name_the_silent_capability_and_its_fix(+ mcp, rest, project, sample_agent, live_api, support_desk_llm, worker+ )+ every_surface_reads_the_same_scores(mcp, rest, project)+ console.goto(f"/capabilities?projectId={project}")+ for truth in sample_agent.truth["capabilities"].values():+ console.sees(truth["name"])+ console.goto(f"/observability?projectId={project}")+ console.click("Signals")+ console.sees("Signal checks")+ console.click("Sessions")+ console.click("Traces")+ console.sees("handle_ticket")++ score_once_per_evidence(mcp, rest, project, key, live_api, fake_llm, worker)+ raise_deduplicated_signals(mcp, rest, project, key, live_api, worker, beat)+ score_spans_before_their_root(mcp, rest, project, key, live_api, worker)+ import_a_vendor_trace(mcp, cli, sample_agent, fake_llm, worker, monkeypatch)++ show_agent_changes_without_reload(console, mcp, project)+ show_activity_and_onboarding_after_reload(console, mcp, rest, project, worker)+++def copy_the_onboarding_prompt(console, console_url, live_api):+ console._browser.call(+ console._page.context.grant_permissions, ["clipboard-read", "clipboard-write"]+ )+ console.press("Copy onboarding prompt")+ console.sees("Prompt copied")+ prompt = console._browser.call(console._page.evaluate, "navigator.clipboard.readText()")+ assert prompt == (+ f"Set me up on Overmind\n\nusing the API at {live_api.url.rstrip('/')}: "+ f"{console_url.rstrip('/')}/setup.md"+ )+ console.wait_until("""() => {+ const panel = document.querySelector('section[aria-label="Get started"]');+ return panel.querySelector('a[href$="/setup.md"]') &&+ [...panel.querySelectorAll('img')].every(img => img.complete && img.naturalWidth > 0);+ }""")+ console._browser.call(console._page.set_viewport_size, {"width": 390, "height": 844})+ console.wait_until("""() => {+ const panel = document.querySelector('section[aria-label="Get started"]');+ return panel.scrollWidth <= panel.clientWidth && panel.getBoundingClientRect().right <= innerWidth;+ }""")+ console.save_evidence("embedded-onboarding-mobile")+ console._browser.call(console._page.set_viewport_size, {"width": 1280, "height": 720})+ console._browser.call(lambda: console._page.get_by_role("tab", name="Data", exact=True).click())+ console.sees("Create dataset")+ console.wait_until("() => !document.querySelector('[role=dialog]')")+ console._browser.call(+ lambda: console._page.get_by_role("tab", name="Agent", exact=True).click()+ )+ console.sees("Copy onboarding prompt")+++def keep_new_api_keys_out_of_session_replay(console, project, replay_recorder):+ console.goto(f"/projects/{project}?projectId={project}")+ console.press("New API key")+ console._browser.call(lambda: console._page.add_script_tag(path=str(replay_recorder)))+ console._browser.call(+ console._page.evaluate,+ """() => {+ window.replayEvents = [];+ window.stopReplay = ReplayRecorder.record({+ emit: event => window.replayEvents.push(event),+ blockClass: 'ph-no-capture', maskTextClass: 'ph-mask', maskAllInputs: true+ });+ }""",+ )+ console.press("Create API key")+ console.sees("Your new API key:")+ console.wait_until("() => window.replayEvents.some(event => event.type === 3)")+ leaked = console._browser.call(+ console._page.evaluate,+ """() => {+ ReplayRecorder.record.takeFullSnapshot();+ const key = document.querySelector('[role="dialog"] code').textContent;+ const leaked = JSON.stringify(window.replayEvents).includes(key);+ window.stopReplay();+ return leaked;+ }""",+ )+ console.press("Done")+ console.wait_until("() => !document.querySelector('[role=\"dialog\"]')")+ assert leaked is False, "Session replay captured the API key"+++def sdk_traces_arrive_as_rooted_trees(+ mcp, rest, sample_agent, live_api, support_desk_llm, fake_llm, worker+):+ replies = sample_agent.run(TICKETS[0], api_url=live_api.url, llm_url=support_desk_llm)+ assert replies == ["Your refund is on its way. The order was delivered."]+ drain(worker)++ [root] = mcp.call("query_traces", {"limit": 100})["traces"]+ trace = mcp.read(f"overmind://traces/{root['trace_id']}")+ ids = {span["span_id"] for span in trace["spans"]}+ [tree_root] = [span for span in trace["spans"] if span["parent_span_id"] is None]+ assert all(span["parent_span_id"] in ids for span in trace["spans"] if span is not tree_root)+ assert trace["root"]["name"] == "handle_ticket"++ rows = mcp.call(+ "query_traces", {"trace_id": root["trace_id"], "all_spans": True, "limit": 100}+ )["traces"]+ assert {row["capability"] for row in rows if row["span_type"] == "llm_call"} == {+ "triage",+ "answer",+ }+ assert any(row["name"] == "lookup_order" and row["capability"] == "answer" for row in rows)+ assert any(row["model"] for row in rows)+ agent_tokens = sum(+ r.total_tokens for r in fake_llm.requests if r.url.startswith("http://fake-llm")+ )+ assert root["total_tokens"] == agent_tokens+ for slug in ("triage", "answer"):+ capability = mcp.capability(slug)["id"]+ [filtered] = mcp.call("query_traces", {"capability": capability})["traces"]+ assert filtered["span_id"] == root["span_id"]+ page = rest.request(+ "GET", "/api/traces/", params={"project": mcp.project()["id"], "capability": capability}+ )+ assert [row["span_id"] for row in page["results"]] == [root["span_id"]]+ spans = mcp.call("query_traces", {"capability": capability, "all_spans": True})["traces"]+ assert spans and all(span["capability"] == slug for span in spans)+++def name_the_silent_capability_and_its_fix(+ mcp, rest, project, sample_agent, live_api, support_desk_llm, worker+):+ agent = sample_agent.repo / "support_desk" / "agent.py"+ instrumented = '@overmind.run(capability="triage", capability_id=capability_id("triage"))\n'+ agent.write_text(agent.read_text().replace(instrumented, ""))++ def coverage() -> dict[str, int]:+ graph = rest.request("GET", "/api/agent/", params={"project": project})+ return {c["slug"]: c["trace_count"] for c in graph["capabilities"]}++ sample_agent.run(TICKETS[1], api_url=live_api.url, llm_url=support_desk_llm)+ drain(worker)+ assert coverage() == {"triage": 1, "answer": 2}++ plan = mcp.call("get_instrumentation_plan", {"capability": "triage"})+ [placement] = plan["placements"]+ assert placement["target"]["qualname"] == "support_desk.agent.triage"+ fix = placement["required_decorator"]+ agent.write_text(agent.read_text().replace("def triage(", f"{fix}\ndef triage(", 1))++ sample_agent.run(TICKETS[2], api_url=live_api.url, llm_url=support_desk_llm)+ drain_scoring(worker)+ assert coverage() == {"triage": 2, "answer": 3}+++def every_surface_reads_the_same_scores(mcp, rest, project):+ over_mcp = {+ row["trace_id"]: (row["eval_score"], row["trajectory_score"])+ for row in mcp.call("query_traces", {"limit": 10})["traces"]+ }+ page = rest.request("GET", "/api/traces/", params={"project": project})+ over_rest = {+ row["trace_id"]: (+ row["eval_attributes"]["score"],+ row["eval_attributes"]["trajectory"]["score"],+ )+ for row in page["results"]+ }+ assert len(over_mcp) == len(TICKETS)+ assert over_rest == over_mcp+ assert all(trajectory < 1 for _, trajectory in over_mcp.values())++ failures = mcp.call("query_failures", {"capability": "answer"})+ assert {f["trace_id"] for f in failures["failures"]} == set(over_mcp)+ assert mcp.call("inspect_capability_health", {})["scoring"]["trajectories"] == len(TICKETS)+ assert (+ mcp.call("inspect_capability_health", {"capability": "answer"})["scoring"]["pass_rate"] < 1+ )+++def score_once_per_evidence(mcp, rest, project, key, live_api, fake_llm, worker):+ answer = mcp.capability("answer")+ good = Trace(answer["id"], GOOD_REPLY, tools=[True])+ bad = Trace(answer["id"], "Your refund is on its way.", tools=[True])+ good.send(live_api.url, key)+ bad.send(live_api.url, key)+ drain_scoring(worker)++ roots = {+ row["trace_id"]: row+ for row in mcp.call("query_traces", {"capability": "answer", "limit": 20})["traces"]+ }+ assert roots[good.hex]["eval_score"] > roots[bad.hex]["eval_score"]+ assert roots[good.hex]["trajectory_score"] > roots[bad.hex]["trajectory_score"]++ root = trace_spans(rest, project, good)[good.root_id.hex()]+ expectation = root["eval_attributes"]["metrics"][EXPECTATION]+ assert expectation["verdict"] == "yes"+ assert expectation["score"] == 1.0+ assert root["eval_attributes"]["score"] == roots[good.hex]["eval_score"]++ first = score_history(rest, project, good)+ assert {row["source_type"] for row in first} == {"span", "trajectory"}+ judged = len(fake_llm.decisions)+ good.send(live_api.url, key)+ drain_scoring(worker)+ assert score_history(rest, project, good) == first+ assert len(fake_llm.decisions) == judged++ good.reply = "Your refund is on its way."+ good.send(live_api.url, key)+ drain_scoring(worker)+ assert len(score_history(rest, project, good)) > len(first)++ health = mcp.call("inspect_capability_health", {"capability": "answer"})+ assert health["scoring"]["scored"] >= 2+ assert any(m["metric"] == EXPECTATION for m in health["scoring"]["metrics"])+++def raise_deduplicated_signals(mcp, rest, project, key, live_api, worker, beat):+ checks = mcp.call("list_signals", {})["signals"]+ assert next(check for check in checks if check["signal_type"] == "tool_failure")["enabled"]++ failing = Trace(mcp.capability("answer")["id"], GOOD_REPLY, tools=[False, False, True])+ failing.send(live_api.url, key)+ drain_scoring(worker)+ beat(RUN_SIGNALS)+ beat(RUN_SIGNALS)++ events = rest.request(+ "GET",+ "/api/signal-events/",+ params={"project": project, "unseen": "true", "signal_type": "tool_failure"},+ )["results"]+ assert [(e["signal_type"], e["trace_id"]) for e in events] == [("tool_failure", failing.hex)]+ assert "lookup_order (2/3)" in events[0]["message"]++ assert mcp.call("list_signals", {})["unseen_events"] >= 1+ assert events[0]["id"] in [e["id"] for e in mcp.read("overmind://signal-events")["events"]]+ evidence = mcp.call("query_traces", {"signal_event": events[0]["id"]})+ assert [trace["trace_id"] for trace in evidence["traces"]] == [failing.hex]++ rest.request("POST", "/api/signal-events/mark-seen/", json={"project": project})+ assert mcp.call("list_signals", {})["unseen_events"] == 0+++def score_spans_before_their_root(mcp, rest, project, key, live_api, worker):+ trace = Trace(mcp.capability("answer")["id"], GOOD_REPLY, tools=[True, False])+ trace.send(live_api.url, key, root=False)+ drain_scoring(worker)+ tool_ids = [span_id.hex() for span_id, _ in trace.tools]+ before = {+ span_id: span["eval_attributes"]+ for span_id, span in trace_spans(rest, project, trace).items()+ }+ assert set(before) == set(tool_ids)+ assert all("score" in attributes for attributes in before.values())+ assert score_history(rest, project, trace)++ trace.send(live_api.url, key, tools=False)+ drain_scoring(worker)+ spans = trace_spans(rest, project, trace)+ assert {span_id: spans[span_id]["eval_attributes"] for span_id in tool_ids} == before+ assert spans[trace.root_id.hex()]["eval_attributes"]["trajectory"]["span_count"] == 3+ trajectories = [+ row for row in score_history(rest, project, trace) if row["source_type"] == "trajectory"+ ]+ assert len(trajectories) == 1+++def import_a_vendor_trace(mcp, cli, sample_agent, fake_llm, worker, monkeypatch):+ api = LangfuseAPI()+ trace_id, steps = support_desk_trace(datetime.now(UTC) - timedelta(hours=1))+ api.record(trace_id, steps)+ fake_llm.network.vendors.append(api)+ monkeypatch.setenv("LANGFUSE_PUBLIC_KEY", "pk-fake")+ monkeypatch.setenv("LANGFUSE_SECRET_KEY", "sk-fake")+ before = {root["trace_id"] for root in mcp.call("query_traces", {"limit": 100})["traces"]}++ added = json.loads(+ cli.run(+ "connector", "add", "langfuse", "--base-url", api.host, "--json", cwd=sample_agent.repo+ )+ )+ connector = added["id"]+ [source] = mcp.call(+ "inspect_connectors", {"connector": connector, "include_source_projects": True}+ )["connector"]["source_projects"]+ mapping = {+ "source": "observation_name",+ "assignments": {+ "triage": mcp.capability("triage")["id"],+ "answer": mcp.capability("answer")["id"],+ },+ }+ proposed = mcp.call(+ "configure_connector",+ {+ "connector": connector,+ "source_project_id": source["id"],+ "lookback_days": 7,+ "capability_mapping": mapping,+ },+ )+ assert proposed["mapping_pending"] is True+ approved = mcp.call("configure_connector", {"connector": connector, "confirm_mapping": True})+ assert approved["mapping_pending"] is False++ mcp.call("sync_connector", {"connector": connector})+ drain(worker)++ roots = [+ root+ for root in mcp.call("query_traces", {"limit": 100})["traces"]+ if root["trace_id"] not in before+ ]+ landed = 0+ for root in roots:+ spans = mcp.read(f"overmind://traces/{root['trace_id']}")["spans"]+ assert len([s for s in spans if s["parent_span_id"] is None]) == 1+ landed += len(spans)+ assert landed == len(steps)+ bound = {root["name"]: root["capability"] for root in roots}+ assert bound["triage"] == "triage"+ assert bound["answer"] == "answer"+ assert sum(root["total_tokens"] or 0 for root in roots) == sum(sum(s.tokens) for s in steps)+ # The chunk schedules its own continuation; an inactive connector stops it.+ ConnectorCredential.objects.filter(pk=connector).update(is_active=False)+++def show_agent_changes_without_reload(console, mcp, project):+ console.goto(f"/datasets?projectId={project}")+ console.sees("Datasets", exact=False)+ 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"},+ )["dataset"]["id"]+ console.sees("Live agent source")+ mcp.call("update_dataset", {"dataset": dataset, "name": "Renamed live source"})+ console.sees("Renamed live source")+ console.wait_until(+ "() => !document.body.textContent.includes('Live agent source') && window.activityDocument === 'unchanged'"+ )+ console._browser.call(lambda: console._page.context.set_offline(True))+ mcp.call("update_dataset", {"dataset": dataset, "name": "Reconnected live source"})+ console._browser.call(lambda: console._page.context.set_offline(False))+ console.sees("Reconnected live source")+ console.wait_until("() => window.activityDocument === 'unchanged'")+ console.press("unread notification")+ console.sees("Reconnected live source", exact=False)+ console.save_evidence("agent-live-notifications")+++def show_activity_and_onboarding_after_reload(console, mcp, rest, project, worker):+ activity = mcp.read("overmind://activity")+ assert {item["kind"] for item in activity["results"]} >= {+ "agent_connected",+ "repository_synced",+ "capabilities_available",+ }+ before = activity["count"]+ for _ in range(2):+ mcp.call("list_datasets")+ assert mcp.read("overmind://activity")["count"] == before++ console.goto(f"/?projectId={project}")+ mcp.call(+ "create_eval_matrix_row",+ {"name": "Visible activity check", "type": "llm", "source": "The answer is grounded."},+ )+ console.press("unread notification")+ console.sees("Visible activity check")+ console.press("Mark read")+ settle(worker, lambda: mcp.read("overmind://activity")["unseen_count"] == 0)++ console.goto(f"/?projectId={project}")+ console.press("Notifications")+ console.click("Visible activity check")+ console.wait_until("() => location.pathname.startsWith('/evaluations')")++ onboarding_run = str(uuid.uuid4())+ progress = mcp.call(+ "report_onboarding_progress", {"run_id": onboarding_run, "completed_steps": 2}+ )+ reporter = progress["milestones"][2]["actor_name"]+ assert reporter+ console.goto(f"/?projectId={project}")+ console.sees("Onboarding · Inspect repository")+ console.sees("2 of 10")+ console._browser.call(+ lambda: (+ console._page.get_by_label("Onboarding status", exact=True)+ .get_by_text(reporter, exact=True)+ .wait_for()+ )+ )+ mcp.call("report_onboarding_progress", {"run_id": onboarding_run, "completed_steps": 10})+ console.wait_until("() => !document.querySelector('[aria-label=\"Onboarding status\"]')")+ console.save_evidence("onboarding-complete")diff --git a/tests/journeys/test_the_loop.py b/tests/journeys/test_optimise.pysimilarity index 98%rename from tests/journeys/test_the_loop.pyrename to tests/journeys/test_optimise.pyindex 954491e5..83093f78 100644--- a/tests/journeys/test_the_loop.py+++ b/tests/journeys/test_optimise.py@@ -2,10 +2,14 @@ import jsonimport subprocessimport sys+import pytest+from .conftest import GOOD_REPLYfrom .stack import drainfrom .surfaces import SDK+pytestmark = pytest.mark.covers("optimise")+TICKETS = ("Refund order 42 please", "Where is order 42?")RUN_ONE_DATAPOINT = """\@@ -43,7 +47,7 @@ def _candidate_diff(repo) -> str:return diff-def test_failing_traces_become_a_measured_winning_diff(+def test_optimise(cli,mcp_for,sample_agent,diff --git a/tests/journeys/test_periodic_tasks_recover.py b/tests/journeys/test_periodic_tasks_recover.pydeleted file mode 100644index b8755db6..00000000--- a/tests/journeys/test_periodic_tasks_recover.py+++ /dev/null@@ -1,59 +0,0 @@-import multiprocessing-import os-import time-import uuid--import redis--from overbae.celery import app-from overbae.tasks.utils.task_lock import acquire_task_lock, with_task_lock--from .stack import drain---def test_evidence_collection_for_a_missing_training_job_stops(worker, fake_modal):- app.send_task("overbae.tasks.finetuning.collect_training_evidence", args=[str(uuid.uuid4())])- drain(worker)- assert not fake_modal.log---def test_a_task_lock_expires_on_its_timeout_and_releases_after_the_task(settings):- settings.CELERY_BROKER_URL = os.environ["TEST_REDIS_URL"]- client = redis.from_url(os.environ["TEST_REDIS_URL"])- key = "celery:lock:journey_expiring_lock"- client.delete(key)-- @with_task_lock(lock_name="journey_expiring_lock", timeout=7)- def held_ttl():- return client.ttl(key)-- assert 0 < held_ttl() <= 7- assert client.ttl(key) == -2---def _hold_and_die(name: str) -> None:- with acquire_task_lock(name, timeout=1, renew=True):- os._exit(0)---def test_a_renewed_lock_holds_while_its_holder_runs_and_frees_soon_after_it_dies(settings):- settings.CELERY_BROKER_URL = os.environ["TEST_REDIS_URL"]- name = "journey_renewed_lock"- redis.from_url(os.environ["TEST_REDIS_URL"]).delete(f"celery:lock:{name}")-- with acquire_task_lock(name, timeout=1, renew=True) as held:- assert held- time.sleep(2.5)- with acquire_task_lock(name, timeout=1) as rival:- assert not rival- with acquire_task_lock(name, timeout=1) as after_release:- assert after_release-- killed = multiprocessing.get_context("fork").Process(target=_hold_and_die, args=(name,))- killed.start()- killed.join(10)- with acquire_task_lock(name, timeout=1) as while_dead_lease_runs:- assert not while_dead_lease_runs- time.sleep(1.5)- with acquire_task_lock(name, timeout=1) as after_lease:- assert after_leasediff --git a/tests/journeys/test_recovery.py b/tests/journeys/test_recovery.pynew file mode 100644index 00000000..269890e2--- /dev/null+++ b/tests/journeys/test_recovery.py@@ -0,0 +1,158 @@+import multiprocessing+import os+import uuid+from datetime import timedelta++import pytest+import redis+from django.utils import timezone++from overbae.celery import app+from overbae.models import Activity, DatasetPreparation+from overbae.tasks.datasets import reap_stuck_runs+from overbae.tasks.utils.task_lock import acquire_task_lock, with_task_lock++from .conftest import GOOD_REPLY+from .otlp import SWEEP_SPANS, SWEEP_TRAJECTORIES, SWEEP_WAIT, Trace, score_history, trace_spans+from .stack import drain, settle++pytestmark = pytest.mark.covers("recovery")+++def test_evidence_collection_for_a_missing_training_job_stops(worker, fake_modal):+ app.send_task("overbae.tasks.finetuning.collect_training_evidence", args=[str(uuid.uuid4())])+ drain(worker)+ assert not fake_modal.log+++def test_a_task_lock_expires_on_its_timeout_and_releases_after_the_task(settings):+ settings.CELERY_BROKER_URL = os.environ["TEST_REDIS_URL"]+ client = redis.from_url(os.environ["TEST_REDIS_URL"])+ key = "celery:lock:journey_expiring_lock"+ client.delete(key)++ @with_task_lock(lock_name="journey_expiring_lock", timeout=7)+ def held_ttl():+ return client.ttl(key)++ assert 0 < held_ttl() <= 7+ assert client.ttl(key) == -2+++def _hold_and_die(name: str) -> None:+ with acquire_task_lock(name, timeout=2, renew=True):+ os._exit(0)+++def _server_ms(client) -> int:+ seconds, microseconds = client.time()+ return seconds * 1000 + microseconds // 1000+++def test_a_renewed_lock_holds_while_its_holder_runs_and_frees_soon_after_it_dies(settings, worker):+ settings.CELERY_BROKER_URL = os.environ["TEST_REDIS_URL"]+ name = "journey_renewed_lock"+ client = redis.from_url(os.environ["TEST_REDIS_URL"])+ key = f"celery:lock:{name}"+ client.delete(key)++ with acquire_task_lock(name, timeout=2, renew=True) as held:+ assert held+ first_expiry = client.pexpiretime(key)+ settle(worker, lambda: _server_ms(client) > first_expiry, timeout=10)+ with acquire_task_lock(name, timeout=2) as rival:+ assert not rival+ with acquire_task_lock(name, timeout=2) as after_release:+ assert after_release++ killed = multiprocessing.get_context("fork").Process(target=_hold_and_die, args=(name,))+ killed.start()+ killed.join(10)+ with acquire_task_lock(name, timeout=2) as while_dead_lease_runs:+ assert not while_dead_lease_runs+ settle(worker, lambda: not client.exists(key), timeout=5)+ with acquire_task_lock(name, timeout=2) as after_lease:+ assert after_lease+++def project(cli, mcp_for, rest_for, sample_agent, worker, judges):+ cli.scan(sample_agent)+ cli.sync(sample_agent)+ key = cli.project_key(sample_agent)+ return mcp_for(key), rest_for(key), key+++def test_a_failing_judge_is_tried_three_times_then_scored_with_errors(+ project, live_api, worker, fake_llm, beat, clock+):+ mcp, rest, key = project+ project_id = mcp.project()["id"]+ fake_llm.fail(lambda request: request.url.rstrip("/").endswith("/systemone"))++ def judge_calls() -> int:+ return sum(r.url.rstrip("/").endswith("/systemone") for r in fake_llm.requests)++ trace = Trace(mcp.capability("answer")["id"], GOOD_REPLY, tools=[True])+ trace.send(live_api.url, key)+ drain(worker)+ per_pass = judge_calls()+ assert per_pass > 0++ for _ in range(5):+ clock.shift(SWEEP_WAIT)+ beat(SWEEP_SPANS, SWEEP_TRAJECTORIES)+ # Three span passes over the root's rows, then three trajectory passes of path_judge.+ assert judge_calls() == 3 * per_pass + 3++ root = trace_spans(rest, project_id, trace)[trace.root_id.hex()]+ attributes = root["eval_attributes"]+ assert {m["error"] for m in attributes["metrics"].values() if m["type"] == "llm"} == {+ "scoring failed after 3 attempts"+ }+ path_judge = attributes["trajectory"]["metrics"]["path_judge"]+ assert path_judge["error"] == "scoring failed after 3 attempts"+ assert {row["source_type"] for row in score_history(rest, project_id, trace)} == {+ "span",+ "trajectory",+ }++ clock.shift(SWEEP_WAIT)+ beat(SWEEP_SPANS, SWEEP_TRAJECTORIES)+ assert judge_calls() == 3 * per_pass + 3+++def test_console_ends_an_open_preparation_and_idle_preparations_expire(console, workshop):+ project = workshop.project()["id"]+ datasets = [+ workshop.call(+ "start_dataset", {"name": name, "brief": "Prepare support rows", "intent": "train"}+ )["dataset"]["id"]+ for name in ("Abandoned preparation", "Idle preparation", "Recently active preparation")+ ]+ for dataset in datasets:+ workshop.call(+ "start_dataset_preparation", {"dataset": dataset, "request_key": f"open-{dataset}"}+ )+ console.goto(f"/datasets/{datasets[0]}?projectId={project}")+ console.sees("Preparing")+ console.press("End preparation")+ console.wait_until("() => !document.body.textContent.includes('End preparation')")+ ended = workshop.call("inspect_dataset_workbench", {"dataset": datasets[0]})+ assert ended["preparation_workflow"]["state"] == "cancelled"++ idle = DatasetPreparation.objects.get(dataset_id=datasets[1])+ active = DatasetPreparation.objects.get(dataset_id=datasets[2])+ stale = timezone.now() - timedelta(hours=25)+ DatasetPreparation.objects.filter(pk__in=[idle.pk, active.pk]).update(updated_at=stale)+ Activity.objects.filter(key=f"preparation:{idle.pk}").update(updated_at=stale)+ assert reap_stuck_runs()["preparations_expired"] == 1+ kept = workshop.call("inspect_dataset_workbench", {"dataset": datasets[2]})+ assert kept["preparation_workflow"]["state"] == "preparing"+ expired = workshop.call("inspect_dataset_workbench", {"dataset": datasets[1]})+ assert expired["preparation_workflow"]["state"] == "cancelled"+ restarted = workshop.call(+ "start_dataset_preparation", {"dataset": datasets[1], "request_key": "after-expiry"}+ )+ assert restarted["preparation_workflow"]["state"] == "preparing"+ console.healthy()diff --git a/tests/journeys/test_scoring_load.py b/tests/journeys/test_scoring_load.pyindex 0685bc74..22d442f2 100644--- a/tests/journeys/test_scoring_load.py+++ b/tests/journeys/test_scoring_load.py@@ -5,10 +5,14 @@ import timeimport uuidfrom pathlib import Path+import pytest+from overbae.tasks.training_experiments import reconcilefrom .conftest import RUNS+pytestmark = [pytest.mark.load, pytest.mark.covers("capacity")]+ROOT = Path(__file__).resolve().parents[2]diff --git a/tests/journeys/test_sdk_server_contract.py b/tests/journeys/test_sdk_server_contract.pyindex 3320423c..9e030412 100644--- a/tests/journeys/test_sdk_server_contract.py+++ b/tests/journeys/test_sdk_server_contract.py@@ -1,7 +1,11 @@+import pytest+from overbae.api import overmind_attrsfrom overbae.models.traces import USAGE_ATTR_KEYSfrom overmind import attrs+pytestmark = pytest.mark.covers("sdk-wire")+def _constants(module) -> dict[str, str]:return {k: v for k, v in vars(module).items() if k.isupper() and isinstance(v, str)}diff --git a/tests/journeys/test_serve.py b/tests/journeys/test_serve.pynew file mode 100644index 00000000..ccd01cef--- /dev/null+++ b/tests/journeys/test_serve.py@@ -0,0 +1,96 @@+import json++import pytest+from overmind.client import Client, OvermindInferenceError++from overbae.models import DedicatedDeployment, DeployedModel, Project+from overbae.services.provider_pricing import refresh_rates++from .datasets import until++pytestmark = pytest.mark.covers("serve")++DEPLOY = "overbae.tasks.inference_controller.reconcile_deployments"+MESSAGES = [{"role": "user", "content": "Where is order 42?"}]+++def _dedicated_reply(**_kwargs):+ return {+ "status": 200,+ "headers": {"content-type": "application/json"},+ "body": json.dumps(+ {+ "model": "dedicated/internal",+ "choices": [+ {+ "message": {"role": "assistant", "content": "Order 42 left the depot."},+ "finish_reason": "stop",+ }+ ],+ "usage": {"prompt_tokens": 1, "completion_tokens": 5, "total_tokens": 6},+ }+ ).encode(),+ }+++def test_serve(+ cli, mcp_for, sample_agent, live_api, fake_llm, fake_modal, scripted, worker, beat, console+):+ cli.scan(sample_agent)+ cli.sync(sample_agent)+ key = cli.project_key(sample_agent)+ mcp = mcp_for(key)+ project = Project.objects.get(pk=mcp.project()["id"])+ DeployedModel.objects.create(+ project=project,+ model_id="ft-sdk-journey",+ status=DeployedModel.Status.READY,+ base_model_id="Qwen/Qwen3-1.7B",+ max_model_len=16384,+ gpu_type="L4",+ )+ client = Client(api_key=key, base_url=live_api.url)+ fake_llm.on(lambda r: "inference.test" in r.url, "Order 42 shipped today.")+ fake_llm.on(lambda r: "openrouter.ai" in r.url, "Order 42 is in transit.")++ served = client.chat.completions.create(model="ft-sdk-journey", messages=MESSAGES)+ assert served.choices[0].message.content == "Order 42 shipped today."+ assert served.usage.total_tokens > 0+ streamed = client.chat.completions.create(+ model="ft-sdk-journey", messages=MESSAGES, stream=True+ )+ assert "".join(c.choices[0].delta.content or "" for c in streamed) == "Order 42 shipped today."+ frontier = client.chat.completions.create(model="openai/gpt-5-mini", messages=MESSAGES)+ assert frontier.choices[0].message.content == "Order 42 is in transit."+ assert "ft-sdk-journey" in {model.id for model in client.models.list().data}+ assert client.models.get("ft-sdk-journey").id == "ft-sdk-journey"+ with pytest.raises(OvermindInferenceError, match="HTTP 404"):+ client.models.get("ft-nobody")++ refresh_rates()+ fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _dedicated_reply)+ fake_modal.worker_stats = {"num_total_runners": 1, "backlog": 0, "num_running_inputs": 0}+ started = mcp.call(+ "start_dedicated_deployment",+ {"deployment": "ft-sdk-journey", "gpu_type": "H100", "min_replicas": 1, "max_replicas": 1},+ )++ def status() -> str:+ return DedicatedDeployment.objects.get(pk=started["id"]).status++ until(beat, lambda: status() == "online", DEPLOY)+ dedicated = client.chat.completions.create(model=started["model_id"], messages=MESSAGES)+ assert dedicated.choices[0].message.content == "Order 42 left the depot."+ assert started["model_id"] in {model.id for model in client.models.list().data}++ mcp.call("stop_dedicated_deployment", {"deployment": "ft-sdk-journey"})+ fake_modal.worker_stats = {"num_total_runners": 0, "backlog": 0, "num_running_inputs": 0}+ until(beat, lambda: status() == "offline", DEPLOY)+ deployed = DeployedModel.objects.get(model_id="ft-sdk-journey")+ console.goto(f"/inference/{deployed.pk}?projectId={project.pk}")+ console.sees("Offline")+ console.sees("0 running · 1–1 configured")++ scripted("http://inference.test").reply(json_body={"ok": True})+ assert client.models.delete("ft-sdk-journey").deleted is True+ assert DeployedModel.objects.get(model_id="ft-sdk-journey").status == "deleted"diff --git a/tests/journeys/test_kit_gpu_training.py b/tests/journeys/test_spend_stops.pysimilarity index 97%rename from tests/journeys/test_kit_gpu_training.pyrename to tests/journeys/test_spend_stops.pyindex 92651a30..ee8e2298 100644--- a/tests/journeys/test_kit_gpu_training.py+++ b/tests/journeys/test_spend_stops.py@@ -3,6 +3,8 @@ import pytestfrom .datasets import tickets, training_rows, until, uploadfrom .stack import drain+pytestmark = pytest.mark.covers("spend-stops")+PREPARE = "overbae.tasks.training_preparation.reconcile"TRAIN = "overbae.tasks.finetuning_reconciler.reconcile_finetuning_jobs"diff --git a/tests/journeys/test_tabular_partition.py b/tests/journeys/test_tabular_partition.pydeleted file mode 100644index 1a09dfcd..00000000--- a/tests/journeys/test_tabular_partition.py+++ /dev/null@@ -1,95 +0,0 @@-import csv-import json--from .datasets import upload-from .stack import drain---def test_tabular_upload_transform_and_temporal_partition_preserve_distinct_observations(- workshop, cli, sample_agent, worker, tmp_path-):- path = tmp_path / "measurements.csv"- records = [- {- "state": "active",- "text": "shared description",- "measurement": i,- "period": i // 2,- "label": i % 2,- }- for i in range(8)- ]- with path.open("w", newline="") as stream:- writer = csv.DictWriter(stream, fieldnames=list(records[0]))- writer.writeheader()- writer.writerows(records)- dataset = upload(cli, sample_agent, path, "--intent", "train")- drain(worker)- source = workshop.call("inspect_dataset", {"dataset": dataset})["active"]- original = workshop.call("query_dataset", {"dataset": dataset, "sql": "select * from t"})[- "rows"- ]- source_keys = [r["_overmind_provenance"]["source_content_keys"] for r in original]- assert len({key for keys in source_keys for key in keys}) == 8- transformed = [- {- "source_row": row["source_row"],- "period": row["period"],- "decision": {- "state": json.dumps({k: row[k] for k in ("state", "text", "measurement")}),- "question": "Is the measurement positive?",- "kind": "choice",- "options": ["No", "Yes"],- "target_probabilities": [1 - row["label"], row["label"]],- "target_semantics": "categorical_gold",- },- }- for row in original- ]- imported = workshop.call(- "import_dataset_version",- {- "dataset": dataset,- "source_cell": source["id"],- "source_fingerprint": source["fingerprint"],- "name": "Declared decision inputs",- "request_key": "measurement-inputs",- "imported_rows": transformed,- "provenance": "Deterministic fixture declares features and the supplied label.",- },- )- drain(worker)- result = workshop.call("get_job", {"kind": "dataset_pipeline", "id": imported["job"]["id"]})- assert result["status"] == "completed", result- prepared = workshop.call("inspect_dataset", {"dataset": dataset})["active"]- roles = ["train", "development", "calibration", "final"]- created = workshop.call(- "create_data_partition",- {- "name": "Chronological measurements",- "source_cell": prepared["id"],- "request_key": "measurement-periods",- "recipe": {- "seed": 42,- "fractions": dict.fromkeys(roles, 0.25),- "holdouts": [- {"field": "period", "values": [i], "role": role} for i, role in enumerate(roles)- ],- },- },- )- drain(worker)- partition = workshop.call(- "get_job", {"kind": "data_partition", "id": created["workflow"]["id"]}- )- assert partition["status"] == "completed", partition- assert partition["progress"]["report"]["counts"] == dict.fromkeys(roles, 2)- retained = workshop.call(- "query_dataset",- {- "dataset": dataset,- "cell": source["id"],- "sql": "select * from t",- },- )["rows"]- assert retained == originaldiff --git a/tests/journeys/test_access.py b/tests/journeys/test_tenancy.pysimilarity index 98%rename from tests/journeys/test_access.pyrename to tests/journeys/test_tenancy.pyindex e4d88572..ea47bc18 100644--- a/tests/journeys/test_access.py+++ b/tests/journeys/test_tenancy.py@@ -7,6 +7,8 @@ from overbae.urls import routerfrom .stack import drain+pytestmark = pytest.mark.covers("tenancy")+@pytest.fixturedef secrets(cli, mcp_for, sample_agent, live_api, support_desk_llm, worker):diff --git a/tests/journeys/test_traces_arrive.py b/tests/journeys/test_traces_arrive.pydeleted file mode 100644index d5846b5c..00000000--- a/tests/journeys/test_traces_arrive.py+++ /dev/null@@ -1,142 +0,0 @@-import uuid--import pytest-import requests-from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest-from opentelemetry.proto.common.v1.common_pb2 import AnyValue, KeyValue-from opentelemetry.proto.trace.v1.trace_pb2 import ResourceSpans, ScopeSpans, Span--from .stack import drain---def project(cli, mcp_for, sample_agent, worker):- cli.scan(sample_agent)- cli.sync(sample_agent)- return mcp_for(cli.project_key(sample_agent))---def spans_of(mcp, trace_id: str) -> list[dict]:- return mcp.call("query_traces", {"trace_id": trace_id, "all_spans": True, "limit": 100})[- "traces"- ]---def assert_one_rooted_tree(mcp, trace_id: str) -> dict:- trace = mcp.read(f"overmind://traces/{trace_id}")- spans = trace["spans"]- ids = {span["span_id"] for span in spans}- roots = [span for span in spans if span["parent_span_id"] is None]- assert len(roots) == 1- assert all(span["parent_span_id"] in ids for span in spans if span is not roots[0])- return trace---def test_sdk_traces_arrive_as_one_rooted_tree_bound_to_capabilities(- project, sample_agent, live_api, support_desk_llm, fake_llm, worker, rest_for, cli-):- replies = sample_agent.run(- "Refund order 42 please", api_url=live_api.url, llm_url=support_desk_llm- )- assert replies == ["Your refund is on its way. The order was delivered."]- drain(worker)-- [root] = project.call("query_traces", {"limit": 100})["traces"]- trace = assert_one_rooted_tree(project, root["trace_id"])- assert trace["root"]["name"] == "handle_ticket"-- rows = spans_of(project, root["trace_id"])- models = [row for row in rows if row["model"]]- by_capability = {row["capability"] for row in rows if row["span_type"] == "llm_call"}- assert by_capability == {"triage", "answer"}- assert any(row["name"] == "lookup_order" and row["capability"] == "answer" for row in rows)- for capability in by_capability:- [match] = project.call("query_traces", {"capability": capability, "limit": 100})["traces"]- assert match["trace_id"] == root["trace_id"]-- agent_tokens = sum(- r.total_tokens for r in fake_llm.requests if r.url.startswith("http://fake-llm")- )- assert root["total_tokens"] == agent_tokens- assert models- rest = rest_for(cli.project_key(sample_agent))- for slug in ("triage", "answer"):- capability = project.capability(slug)["id"]- [filtered] = project.call("query_traces", {"capability": capability})["traces"]- assert filtered["span_id"] == root["span_id"]- page = rest.request(- "GET",- "/api/traces/",- params={- "project": project.project()["id"],- "capability": capability,- },- )- assert [row["span_id"] for row in page["results"]] == [root["span_id"]]- spans = project.call("query_traces", {"capability": capability, "all_spans": True})[- "traces"- ]- assert spans and all(span["capability"] == slug for span in spans)---def _attr(key: str, value) -> KeyValue:- if isinstance(value, int):- return KeyValue(key=key, value=AnyValue(int_value=value))- return KeyValue(key=key, value=AnyValue(string_value=str(value)))---def test_any_otel_exporter_can_send_traces_without_the_sdk(project, live_api, cli, sample_agent):- triage = project.capability("triage")- trace_id = uuid.uuid4().bytes- root_id, call_id = uuid.uuid4().bytes[:8], uuid.uuid4().bytes[:8]- request = ExportTraceServiceRequest(- resource_spans=[- ResourceSpans(- scope_spans=[- ScopeSpans(- spans=[- Span(- trace_id=trace_id,- span_id=root_id,- parent_span_id=b"\x00" * 8,- name="classify",- start_time_unix_nano=1_000,- end_time_unix_nano=9_000,- ),- Span(- trace_id=trace_id,- span_id=call_id,- parent_span_id=root_id,- name="chat openai/gpt-4.1-mini",- start_time_unix_nano=2_000,- end_time_unix_nano=8_000,- attributes=[- _attr("overmind.capability.id", triage["id"]),- _attr("gen_ai.system", "openai"),- _attr("gen_ai.request.model", "openai/gpt-4.1-mini"),- _attr("gen_ai.usage.input_tokens", 10),- _attr("gen_ai.usage.output_tokens", 5),- ],- ),- ]- )- ]- )- ]- )- response = requests.post(- f"{live_api.url}/api/v1/traces",- data=request.SerializeToString(),- headers={- "Content-Type": "application/x-protobuf",- "X-Api-Key": cli.project_key(sample_agent),- },- timeout=30,- )- assert response.status_code == 200-- hex_id = trace_id.hex()- assert_one_rooted_tree(project, hex_id)- rows = {row["span_id"]: row for row in spans_of(project, hex_id)}- assert rows[call_id.hex()]["capability"] == "triage"- assert rows[root_id.hex()]["total_tokens"] == 15diff --git a/tests/journeys/test_model_training.py b/tests/journeys/test_train.pysimilarity index 84%rename from tests/journeys/test_model_training.pyrename to tests/journeys/test_train.pyindex 4368a5c2..f2e83abd 100644--- a/tests/journeys/test_model_training.py+++ b/tests/journeys/test_train.py@@ -1,9 +1,13 @@import re+import pytest+from .conftest import GOOD_REPLY, answer_turnfrom .datasets import tickets, training_rows, until, uploadfrom .stack import drain+pytestmark = pytest.mark.covers("train")+PREPARE = "overbae.tasks.training_preparation.reconcile"TRAIN = "overbae.tasks.finetuning_reconciler.reconcile_finetuning_jobs"DEPLOY = "overbae.tasks.inference_controller.reconcile_deployments"@@ -17,7 +21,7 @@ def trained_turn(request):return {"content": GOOD_REPLY}-def test_a_trained_model_is_benchmarked_served_and_switched_in(+def test_train(workshop,cli,sample_agent,@@ -29,6 +33,8 @@ def test_a_trained_model_is_benchmarked_served_and_switched_in(fake_llm,live_api,tmp_path,+ rest_for,+ console,):def served(prefix):return lambda r: "inference.test" in r.url and r.model.startswith(prefix)@@ -152,3 +158,24 @@ def test_a_trained_model_is_benchmarked_served_and_switched_in(assert replies[-1] == GOOD_REPLYmetrics = workshop.read(f"overmind://deployments/{deployment}")["metrics"]assert metrics["request_count"] >= 2++ rest = rest_for(cli.project_key(sample_agent))+ pinned = rest.request(+ "GET", f"/api/finetuning-jobs/{job}/model-swap-prompt/", params={"pin": "true"}+ )+ assert model_id in pinned["prompt"]+ project = workshop.project()["id"]+ group = rest.request("GET", f"/api/finetuning-jobs/{job}/")["group_id"]+ console._browser.call(+ console._page.context.grant_permissions, ["clipboard-read", "clipboard-write"]+ )+ console.goto(f"/training?projectId={project}&groupId={group}&jobId={job}")+ console.sees("Live model")+ console._browser.call(+ lambda: console._page.get_by_role(+ "button", name=re.compile("^Copy a prompt switching to ")+ ).click()+ )+ console.sees("Prompt copied")+ copied = console._browser.call(console._page.evaluate, "navigator.clipboard.readText()")+ assert alias in copieddiff --git a/tests/journeys/test_work_once.py b/tests/journeys/test_work_once.pynew file mode 100644index 00000000..03550cbb--- /dev/null+++ b/tests/journeys/test_work_once.py@@ -0,0 +1,86 @@+import json++import pytest++from .conftest import GOOD_REPLY+from .otlp import (+ RUN_SIGNALS,+ SWEEP_SPANS,+ SWEEP_TRAJECTORIES,+ SWEEP_WAIT,+ Trace,+ score_history,+ trace_spans,+)+from .stack import drain++pytestmark = pytest.mark.covers("work-once")+++def project(cli, mcp_for, rest_for, sample_agent, worker, judges):+ cli.scan(sample_agent)+ cli.sync(sample_agent)+ key = cli.project_key(sample_agent)+ return mcp_for(key), rest_for(key), key+++def test_scored_spans_trajectories_and_drift_verdicts_are_never_judged_again(+ project, live_api, worker, fake_llm, beat, clock+):+ mcp, rest, key = project+ project_id = mcp.project()["id"]+ mcp.call("set_signal_subscription", {"signal_type": "plan_drift", "enabled": True})++ trace = Trace(mcp.capability("answer")["id"], GOOD_REPLY, tools=[True])+ trace.send(live_api.url, key)+ drain(worker)+ beat(RUN_SIGNALS)+ tool_id = trace.tools[0][0].hex()+ # The judges meet an expectation only on the good reply, so the tool step drifts.+ assert trace_spans(rest, project_id, trace)[tool_id]["eval_attributes"]["drift"] == 0.0++ judged = len(fake_llm.decisions)+ clock.shift(SWEEP_WAIT)+ beat(RUN_SIGNALS, SWEEP_SPANS, SWEEP_TRAJECTORIES)+ assert len(fake_llm.decisions) == judged++ trace.add_tool(True)+ trace.send(live_api.url, key)+ drain(worker)+ beat(RUN_SIGNALS)+ spans = trace_spans(rest, project_id, trace)+ assert spans[trace.tools[1][0].hex()]["eval_attributes"]["drift"] == 0.0+ assert spans[trace.root_id.hex()]["eval_attributes"]["trajectory"]["span_count"] == 2+ trajectories = [+ row for row in score_history(rest, project_id, trace) if row["source_type"] == "trajectory"+ ]+ assert len(trajectories) == 1++ judged = len(fake_llm.decisions)+ clock.shift(SWEEP_WAIT)+ beat(RUN_SIGNALS, SWEEP_SPANS, SWEEP_TRAJECTORIES)+ assert len(fake_llm.decisions) == judged+++def test_cli_batch_lands_once_and_mcp_retains_all_sources(+ workshop, cli, sample_agent, worker, tmp_path+):+ paths = [tmp_path / "first.jsonl", tmp_path / "second.jsonl"]+ for index, path in enumerate(paths):+ path.write_text(json.dumps({"value": index}) + "\n")+ arguments = ["dataset", "upload", *(str(path) for path in paths), "--json"]+ uploaded = json.loads(cli.run(*arguments, cwd=sample_agent.repo))+ drain(worker)+ replay = json.loads(cli.run(*arguments, cwd=sample_agent.repo))+ assert replay["id"] == uploaded["id"]+ assert replay["transfer"]["id"] == uploaded["transfer"]["id"]+ inspected = workshop.call("inspect_dataset", {"dataset": uploaded["id"]})+ assert inspected["active"]["rows"] == 2+ assert inspected["cell_page"]["total"] == 1+ assert [source["filename"] for source in inspected["sources"]] == [path.name for path in paths]+ rows = workshop.call(+ "query_dataset",+ {"dataset": uploaded["id"], "sql": "SELECT value FROM t ORDER BY source_row"},+ )["rows"]+ assert rows == [{"value": 0}, {"value": 1}]diff --git a/tests/journeys/test_workshop_analytics.py b/tests/journeys/test_workshop_analytics.pydeleted file mode 100644index 5ad7b6bb..00000000--- a/tests/journeys/test_workshop_analytics.py+++ /dev/null@@ -1,74 +0,0 @@-import json--from .datasets import upload-from .stack import drain---def test_workshop_publishes_version_bound_analytics_to_mcp_and_rest(- workshop, cli, sample_agent, worker, tmp_path, rest_for-):- source_file = tmp_path / "imbalanced.jsonl"- source_file.write_text(- "".join(json.dumps({"amount": i, "fraud": int(i == 1000)}) + "\n" for i in range(1001))- )- dataset = upload(cli, sample_agent, source_file, "--intent", "train")- drain(worker)- source = workshop.call("inspect_dataset", {"dataset": dataset})["active"]- result = workshop.call(- "import_dataset_version",- {- "dataset": dataset,- "source_cell": source["id"],- "source_fingerprint": source["fingerprint"],- "name": "Fraud decisions",- "request_key": "analytics-transform",- "provenance": "Test fixture encodes the supplied fraud label without changing rows.",- "imported_rows": [- {- "source_row": i,- "decision": {- "state": json.dumps({"amount": i}),- "question": "Fraud?",- "kind": "choice",- "options": ["No", "Yes"],- "target_probabilities": [int(i != 1000), int(i == 1000)],- "target_semantics": "categorical_gold",- },- }- for i in range(1001)- ],- },- )- drain(worker)- receipt = workshop.call("get_job", {"kind": "dataset_pipeline", "id": result["job"]["id"]})- assert receipt["status"] == "completed", receipt- detail = workshop.call("inspect_dataset", {"dataset": dataset})- cell = next(cell for cell in detail["cells"] if cell["id"] == detail["active"]["id"])- report = cell["analytics"]- assert report["fingerprint"] == cell["fingerprint"]- assert report["cell"] == cell["id"]- assert report["families"][0]["counts"] == [1000, 1]- assert report["rows_scanned"] == 1001- assert (- next(c for c in report["checks"] if c["id"] == "targets.class_balance")["status"]- == "warning"- )- assert receipt["progress"]["analytics"]["fingerprint"] == report["fingerprint"]- rest = rest_for(cli.project_key(sample_agent)).request("GET", f"/api/datasets/{dataset}/")- rest_cell = next(c for c in rest["cells"] if c["id"] == cell["id"])- assert rest_cell["analytics"] == report- exploration = workshop.call(- "explore_dataset",- {- "source_cell": cell["id"],- "name": "Refresh analytics",- "request_key": "refresh-analytics",- },- )- drain(worker)- refreshed = workshop.call(- "get_job", {"kind": "data_exploration", "id": exploration["workflow"]["id"]}- )- assert refreshed["status"] == "completed", refreshed- after = workshop.call("inspect_dataset", {"dataset": dataset})- assert after["active"]["fingerprint"] == cell["fingerprint"]diff --git a/tests/mcp_fixtures.py b/tests/mcp_fixtures.pyindex 9ad40285..8b766d40 100644--- a/tests/mcp_fixtures.py+++ b/tests/mcp_fixtures.py@@ -2,13 +2,20 @@ import uuidfrom collections.abc import Sequencefrom typing import Any+import pytest+from asgiref.sync import async_to_syncfrom conftest import EVAL_ROWS, TRAIN_ROWS, frozen_dataset+from django.test import TestCasefrom factories import make_matrix_row, make_project, make_userfrom overbae.models import APIToken, Capability, EvalMatrix, EvalSet+from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContextMAX_MANIFEST_BYTES = 93 * 1024+# The ASGI MCP app serves requests on another thread with its own connection,+# so it sees only committed rows.+asgi_db = pytest.mark.django_db(transaction=True)EXPECTED_TOOL_NAMES = {"start_dataset_preparation",@@ -99,6 +106,13 @@ EXPECTED_TOOL_NAMES = {}+def call_tool(name: str, arguments: dict[str, Any], context: MCPContext):+ # From the test thread, thread-sensitive handlers run on this thread and share the+ # test transaction; on-commit work runs as it would after a real commit.+ with TestCase.captureOnCommitCallbacks(execute=True):+ return async_to_sync(CATALOG.call)(name, arguments, context)++def mcp_context(permission: str | Sequence[str] = "read", **fields: Any) -> MCPContext:user = make_user()project = make_project(member=user)diff --git a/tests/migration_replay.py b/tests/migration_replay.pynew file mode 100644index 00000000..54750637--- /dev/null+++ b/tests/migration_replay.py@@ -0,0 +1,47 @@+"""Replay a data migration on a scratch Postgres database.++pytest runs with --nomigrations, so a data migration that rewrites rows ships with+a replay test that migrates to the parent, writes rows, migrates to the target and+reads them back. Delete the replay test once a published release has applied the+migration.+"""++from __future__ import annotations++import uuid+from collections.abc import Iterator+from contextlib import contextmanager++import psycopg2+from django.db import connections+from django.db.backends.postgresql.base import DatabaseWrapper+from django.test import override_settings+++@contextmanager+def scratch_database(django_db_blocker) -> Iterator[DatabaseWrapper]:+ """Swap an empty database in as `default`; build a `MigrationExecutor` on it."""+ settings = connections["default"].settings_dict+ name = f"migration_{uuid.uuid4().hex[:12]}"+ admin = psycopg2.connect(+ dbname="postgres",+ user=settings["USER"],+ password=settings["PASSWORD"],+ host=settings["HOST"],+ port=settings["PORT"],+ )+ admin.autocommit = True+ admin.cursor().execute(f'CREATE DATABASE "{name}"')+ original = connections["default"]+ database = DatabaseWrapper({**settings, "NAME": name}, alias="default")+ try:+ with django_db_blocker.unblock(), override_settings(MIGRATION_MODULES={}):+ connections["default"] = database+ try:+ yield database+ finally:+ database.close()+ connections["default"] = original+ finally:+ admin.cursor().execute(f'DROP DATABASE IF EXISTS "{name}" WITH (FORCE)')+ admin.close()diff --git a/tests/test_activity_contract.py b/tests/test_activity_contract.pyindex e14eab47..ef40970b 100644--- a/tests/test_activity_contract.py+++ b/tests/test_activity_contract.py@@ -1,11 +1,11 @@-import asyncioimport jsonimport refrom pathlib import Pathimport pytest+from asgiref.sync import async_to_syncfrom mcp.shared.exceptions import McpError-from mcp_fixtures import mcp_context+from mcp_fixtures import call_tool, mcp_contextfrom rest_framework.test import APIClientfrom overbae.models import (@@ -16,15 +16,14 @@ from overbae.models import (FinetuningJob,ProjectMembership,)-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import bind_contextfrom overbae.services.mcp.resources import read_resource-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("live-console")]def call(context, tool, **arguments):- result = asyncio.run(CATALOG.call(tool, arguments, context))+ result = call_tool(tool, arguments, context)assert not result.isError, result.contentreturn result.structuredContent@@ -32,7 +31,7 @@ def call(context, tool, **arguments):def read_activity(context, project_id=None):with bind_context(context):uri = "overmind://activity" + (f"?project_id={project_id}" if project_id else "")- return json.loads(asyncio.run(read_resource(uri))[0].content)+ return json.loads(async_to_sync(read_resource)(uri)[0].content)def client_for(context):@@ -41,6 +40,7 @@ def client_for(context):return client[email protected]("privacy")def test_feed_never_copies_tool_arguments_and_failed_calls_record_nothing():context = mcp_context(permission=["read", "write"], client_name="codex")created = call(@@ -57,11 +57,12 @@ def test_feed_never_copies_tool_arguments_and_failed_calls_record_nothing():call(context, "delete_eval_matrix_row", row=created["row"]["id"])after = read_activity(context)assert any(item["action"] == "Deleted an evaluation" for item in after["results"])- rejected = asyncio.run(CATALOG.call("create_eval_matrix_row", {"name": "Invalid"}, context))+ rejected = call_tool("create_eval_matrix_row", {"name": "Invalid"}, context)assert rejected.isErrorassert read_activity(context)["count"] == after["count"][email protected]("tenancy")def test_activity_read_state_is_per_user_scoped_and_cannot_acknowledge_future_changes():context = mcp_context(permission=["read", "write"])peer = mcp_context(permission=["read", "write"])@@ -176,10 +177,8 @@ def test_reported_onboarding_uses_current_roadmap_without_notification_noise():reset = call(context, "report_onboarding_progress", run_id=str(uuid4()), completed_steps=2)assert sum(bool(step["completed_at"]) for step in reset["milestones"]) == 2for count in (-1, 11):- rejected = asyncio.run(- CATALOG.call(- "report_onboarding_progress", {"run_id": run_id, "completed_steps": count}, context- )+ rejected = call_tool(+ "report_onboarding_progress", {"run_id": run_id, "completed_steps": count}, context)assert rejected.isError@@ -204,7 +203,7 @@ def test_preparation_completion_rejects_foreign_outputs_and_unfinished_jobs():"state": "completed","outputs": [str(foreign_cell.pk)],}- assert asyncio.run(CATALOG.call("update_dataset_preparation", args, context)).isError+ assert call_tool("update_dataset_preparation", args, context).isErrorargs["outputs"] = [str(source.pk)]DatasetPipelineRun.objects.create(dataset=dataset,@@ -213,8 +212,8 @@ def test_preparation_completion_rejects_foreign_outputs_and_unfinished_jobs():request_key="pending",state="queued",)- assert asyncio.run(CATALOG.call("update_dataset_preparation", args, context)).isError- assert asyncio.run(CATALOG.call("update_dataset_preparation", args, peer)).isError+ assert call_tool("update_dataset_preparation", args, context).isError+ assert call_tool("update_dataset_preparation", args, peer).isErrorassert (call(context, "inspect_dataset_workbench", dataset=str(dataset.pk))["preparation_workflow"]["state"@@ -228,4 +227,4 @@ def test_preparation_completion_rejects_foreign_outputs_and_unfinished_jobs():preparation_id=workflow["id"],state="cancelled",)- assert asyncio.run(CATALOG.call("update_dataset_preparation", args, context)).isError+ assert call_tool("update_dataset_preparation", args, context).isErrordiff --git a/tests/test_adapter_archive_base.py b/tests/test_adapter_archive_base.pyindex 4c12ab72..2711d36f 100644--- a/tests/test_adapter_archive_base.py+++ b/tests/test_adapter_archive_base.py@@ -1,7 +1,11 @@from unittest.mock import Mock+import pytest+from overbae.modal import register_model as registration+pytestmark = pytest.mark.covers("model-runtime")+def test_archive_restore_preserves_base_identity_instead_of_cache_key(tmp_path, monkeypatch):staging = tmp_path / "adapter-cache"diff --git a/tests/test_api_error_disclosure.py b/tests/test_api_error_disclosure.pyindex edd5d313..840afda8 100644--- a/tests/test_api_error_disclosure.py+++ b/tests/test_api_error_disclosure.py@@ -16,6 +16,8 @@ from overbae.models import (User,)+pytestmark = pytest.mark.covers("privacy")+PRIVATE_DIAGNOSTIC = "Traceback: /srv/private/worker.py provider_token=do-not-expose"diff --git a/tests/test_api_robots.py b/tests/test_api_robots.pyindex 4d2efc9e..f0c3b532 100644--- a/tests/test_api_robots.py+++ b/tests/test_api_robots.py@@ -7,6 +7,8 @@ from starlette.testclient import TestClientfrom overbae.asgi import application+pytestmark = pytest.mark.covers("http-api")+API_URL = "https://api.overmindlab.ai"BLOCKED_PATHS = ("/", "/api/capabilities/", "/api/docs/", "/health")FETCHABLE_PATHS = (diff --git a/tests/test_api_tokens.py b/tests/test_api_tokens.pyindex 71a101b3..156fd9d3 100644--- a/tests/test_api_tokens.py+++ b/tests/test_api_tokens.py@@ -9,7 +9,7 @@ from rest_framework_simplejwt.tokens import RefreshTokenfrom overbae.api.scoping import project_ids_forfrom overbae.models import APIToken, Project, ProjectMembership, User-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("authentication")]def _jwt(user: User) -> APIClient:diff --git a/tests/test_base_model_cache.py b/tests/test_base_model_cache.pyindex d37f5b0e..068f2056 100644--- a/tests/test_base_model_cache.py+++ b/tests/test_base_model_cache.py@@ -3,8 +3,12 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+import pytest+from overbae.modal.register_model import _base_model_dir, _snapshot_is_complete+pytestmark = pytest.mark.covers("model-runtime")+def _shard(d: Path, name: str, size: int = 16) -> None:(d / name).write_bytes(b"\0" * size)diff --git a/tests/test_baseten_billing.py b/tests/test_baseten_billing.pyindex 9af8d14d..7b8f668a 100644--- a/tests/test_baseten_billing.py+++ b/tests/test_baseten_billing.py@@ -18,7 +18,7 @@ from overbae.services.baseten_billing import (usage_summary_chunks,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]def _training_summary(*items: dict) -> dict:diff --git a/tests/test_benchmark_artifact.py b/tests/test_benchmark_artifact.pyindex 681f1195..34ef00bc 100644--- a/tests/test_benchmark_artifact.py+++ b/tests/test_benchmark_artifact.py@@ -14,6 +14,8 @@ from overbae.services.benchmarks.schema import (parse_artifact,)+pytestmark = pytest.mark.covers("metrics-math")+_LEGAL_PROVENANCE = {p.value for p in Provenance}diff --git a/tests/test_benchmark_grading.py b/tests/test_benchmark_grading.pyindex 76630d59..94cc836f 100644--- a/tests/test_benchmark_grading.py+++ b/tests/test_benchmark_grading.py@@ -13,6 +13,8 @@ from overbae.services.benchmarks.grading import (from overbae.services.benchmarks.schema import BenchmarkScore, Provenancefrom overbae.services.benchmarks.taxonomy import Skill, TaskType+pytestmark = pytest.mark.covers("metrics-math")+_IF = str(Skill.INSTRUCTION_FOLLOWING)_FAITH = str(Skill.FAITHFULNESS)_REASONING = str(Skill.REASONING)diff --git a/tests/test_benchmark_taxonomy.py b/tests/test_benchmark_taxonomy.pyindex 8a51dcad..6b022f54 100644--- a/tests/test_benchmark_taxonomy.py+++ b/tests/test_benchmark_taxonomy.py@@ -11,6 +11,8 @@ from overbae.services.benchmarks.taxonomy import (weights_for,)+pytestmark = pytest.mark.covers("metrics-math")+_LEGAL_AXES = {str(skill) for skill in Skill} | {str(domain) for domain in Domain}_TASK_TYPES = list(TaskType)diff --git a/tests/test_billing_provider.py b/tests/test_billing_provider.pyindex 3a5d3b9c..a6afff5c 100644--- a/tests/test_billing_provider.py+++ b/tests/test_billing_provider.py@@ -11,7 +11,7 @@ from overbae.models import BillingService, BillingTelemetryfrom overbae.services.billing_ledger import charge_credits, grant_free_creditsfrom overbae.services.billing_provider import get_billing-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]User = get_user_model()diff --git a/tests/test_billing_renewal.py b/tests/test_billing_renewal.pyindex 18d7c616..720a2681 100644--- a/tests/test_billing_renewal.py+++ b/tests/test_billing_renewal.py@@ -20,7 +20,7 @@ from overbae.services.billing_ledger import (granted_usd,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]User = get_user_model()diff --git a/tests/test_braintrust_adapter.py b/tests/test_braintrust_adapter.pyindex b69a4ab9..33fea2fd 100644--- a/tests/test_braintrust_adapter.py+++ b/tests/test_braintrust_adapter.py@@ -7,7 +7,7 @@ from overbae.models import ConnectorCredentialfrom overbae.services.connectors.braintrust.adapter import BraintrustAdapterfrom overbae.services.connectors.braintrust.client import BraintrustError-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("vendor-connectors")]@pytest.fixturediff --git a/tests/test_braintrust_client.py b/tests/test_braintrust_client.pyindex 704a1e6c..17f26069 100644--- a/tests/test_braintrust_client.py+++ b/tests/test_braintrust_client.py@@ -9,6 +9,8 @@ from overbae.services.connectors.braintrust.client import (build_span_query,)+pytestmark = pytest.mark.covers("vendor-connectors")+_WHERE = "created >= '2026-01-01'"diff --git a/tests/test_braintrust_mapping.py b/tests/test_braintrust_mapping.pyindex 7db42eee..8faf660e 100644--- a/tests/test_braintrust_mapping.py+++ b/tests/test_braintrust_mapping.py@@ -17,6 +17,8 @@ from overbae.services.connectors.schema import ()from overbae.services.connectors.spans import span_id_for+pytestmark = pytest.mark.covers("vendor-connectors")+# 2026-01-02T00:00:00Z and one second later, as Braintrust logs them._START = 1767312000.0diff --git a/tests/test_capabilities_api.py b/tests/test_capabilities_api.pyindex b9899527..dd0b3b57 100644--- a/tests/test_capabilities_api.py+++ b/tests/test_capabilities_api.py@@ -14,12 +14,11 @@ from overbae.models import (FinetuningJob,Project,ProjectMembership,- Span,User,)from overbae.services.capabilities import identity-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("identity")]def _trained_model(project, capability, *, status="ready"):@@ -32,43 +31,7 @@ def _trained_model(project, capability, *, status="ready"):)-def test_benchmark_selection_does_not_change_live_model_and_can_reset_to_codebase():- project = _project()- capability = _capability(project, "Support", model="anthropic/claude-opus-4-7")- live = _trained_model(project, capability)- benchmark = _trained_model(project, capability)- capability.active_model = live- capability.save(update_fields=["active_model"])- client = _client(project)- url = f"/api/capabilities/{capability.id}/"-- response = client.patch(url, {"benchmark_model": str(benchmark.id)}, format="json")- assert response.status_code == 200, response.content- assert response.json()["benchmark_model"] == str(benchmark.id)- capability.refresh_from_db()- assert capability.active_model_id == live.id- listed = client.get("/api/capabilities/", {"project": project.id}).json()["results"]- assert listed[0]["benchmark_model"] == str(benchmark.id)-- response = client.patch(url, {"benchmark_model": None}, format="json")- assert response.status_code == 200, response.content- capability.refresh_from_db()- assert capability.benchmark_model_id is None- assert capability.active_model_id == live.id--[email protected]("status", ["queued", "deploying", "failed", "deleted", "deleting"])-def test_benchmark_must_be_ready(status):- project = _project()- capability = _capability(project, "Support")- model = _trained_model(project, capability, status=status)- response = _client(project).patch(- f"/api/capabilities/{capability.id}/", {"benchmark_model": str(model.id)}, format="json"- )- assert response.status_code == 400- assert "benchmark_model" in response.json()--[email protected]("tenancy")def test_benchmark_rejects_other_projects_and_evaluation_infrastructure():project = _project()capability = _capability(project, "Support")@@ -122,64 +85,6 @@ def test_create_slugifies_the_name_and_binds_its_identity():assert identity.lookup(project.id, "refund-bot") == capability-def test_list_shows_current_rows_and_leftover_only_on_request():- project = _project()- current = _capability(project, "Brain")- leftover = _capability(project, "Old Judge", status=Capability.Status.LEFTOVER)- _capability(project, "Gone", status=Capability.Status.DELETED)- client = _client(project)-- ids = {- r["id"] for r in client.get("/api/capabilities/", {"project": project.id}).json()["results"]- }- assert ids == {str(current.id)}- asked = client.get("/api/capabilities/", {"project": project.id, "status": "leftover"}).json()- assert {r["id"] for r in asked["results"]} == {str(leftover.id)}- assert client.get(f"/api/capabilities/{leftover.id}/").json()["status"] == "leftover"---def test_delete_hides_the_row_and_keeps_its_data():- project = _project()- capability = _capability(project, "Brain")- span = Span.objects.create(- span_id=uuid.uuid4().hex[:16],- trace_id=uuid.uuid4().hex,- project=project,- capability=capability,- start_time_ns=1,- end_time_ns=2,- )- dataset = frozen_dataset(- project, EVAL_ROWS, capability=capability, name="rows", contract="eval"- )- client = _client(project)-- assert client.delete(f"/api/capabilities/{capability.id}/").status_code == 204- capability.refresh_from_db()- assert capability.status == Capability.Status.DELETED- assert client.get(f"/api/capabilities/{capability.id}/").status_code == 404- assert client.get("/api/capabilities/", {"project": project.id}).json()["results"] == []- assert identity.lookup(project.id, "brain") is None- span.refresh_from_db()- dataset.refresh_from_db()- assert span.capability_id == capability.id and dataset.capability_id == capability.id- assert client.delete(f"/api/capabilities/{capability.id}/").status_code == 404---def test_deleted_capability_alias_stops_serving():- project = _project()- model = DeployedModel.objects.create(- project=project, model_id="ft-x", status=DeployedModel.Status.READY, base_model_id="m"- )- live = _capability(project, "Triage", active_model=model)- gone = _capability(project, "Old Triage", active_model=model)- gone.set_status(Capability.Status.DELETED)- client = _client(project)- models = client.get("/api/v1/models").json()["data"]- assert any(m["id"] == f"overmind/{live.id}" for m in models)- assert not any(m["id"] == f"overmind/{gone.id}" for m in models)--def test_agent_graph_endpoint_returns_current_rows_without_a_scan_report():project = _project()current = _capability(project, "Brain")@@ -192,14 +97,3 @@ def test_agent_graph_endpoint_returns_current_rows_without_a_scan_report():assert "last_scan" not in bodyassert "analyzed_sha" not in body and "repo_full_name" not in bodyassert client.get("/api/agent/", {"project": _project().id}).status_code == 404---def test_list_reads_the_dataset_product_off_the_active_cell():- project = _project()- capability = _capability(project, "Brain")- frozen_dataset(project, EVAL_ROWS, capability=capability, name="rows", contract="eval")- client = _client(project)-- row = client.get("/api/capabilities/", {"project": project.id}).json()["results"][0]- assert row["dataset_size"] == len(EVAL_ROWS)- assert row["dataset_has_expected_output"] is Truediff --git a/tests/test_capability_identity.py b/tests/test_capability_identity.pyindex 77d625c7..5dfd55ae 100644--- a/tests/test_capability_identity.py+++ b/tests/test_capability_identity.py@@ -7,7 +7,7 @@ from overbae.models import Capability, IdentityAlias, Spanfrom overbae.services.capabilities import identityfrom overbae.services.connectors.capabilities import resolve_capability as connector_resolve-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("identity")]def _capability(project, name, slug=None, **extra) -> Capability:diff --git a/tests/test_capability_rebind.py b/tests/test_capability_rebind.pyindex a28b45c2..0a7fdfb0 100644--- a/tests/test_capability_rebind.py+++ b/tests/test_capability_rebind.py@@ -9,7 +9,7 @@ from factories import make_projectfrom overbae.models import Capability, Spanfrom overbae.tasks.capability_rebind import rebind_unbound_spans-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("identity")]def _span(project, *, name="", attributes=None, capability=None) -> Span:diff --git a/tests/test_capability_task_type.py b/tests/test_capability_task_type.pyindex ae3566b6..9dda046e 100644--- a/tests/test_capability_task_type.py+++ b/tests/test_capability_task_type.py@@ -11,6 +11,8 @@ from django.core.cache import cachefrom overbae.services.benchmarks.taxonomy import TaskTypefrom overbae.services.codebase import task_type+pytestmark = pytest.mark.covers("recommendations")+@pytest.fixturedef capability():diff --git a/tests/test_celery_topology.py b/tests/test_celery_topology.pyindex dda51964..9a3566ee 100644--- a/tests/test_celery_topology.py+++ b/tests/test_celery_topology.py@@ -15,6 +15,8 @@ import pytestimport yamlfrom django.conf import settings+pytestmark = pytest.mark.covers("topology")+REPO_ROOT = Path(__file__).resolve().parents[1]DEFAULT_QUEUE = getattr(settings, "CELERY_TASK_DEFAULT_QUEUE", "celery")diff --git a/tests/test_codebase_artifacts.py b/tests/test_codebase_artifacts.pyindex 8b8ca26e..aa519214 100644--- a/tests/test_codebase_artifacts.py+++ b/tests/test_codebase_artifacts.py@@ -1,7 +1,11 @@from __future__ import annotations+import pytest+from overbae.services.codebase import artifacts as A # noqa: N812+pytestmark = pytest.mark.covers("sdk-wire")+def test_model_resolution_preserves_defaults_without_inventing_an_active_model():card = _valid_card()diff --git a/tests/test_completions_api.py b/tests/test_completions_api.pyindex b374f027..85e4f3cc 100644--- a/tests/test_completions_api.py+++ b/tests/test_completions_api.py@@ -16,7 +16,7 @@ from overbae.models import InferenceCall, Project, ProjectMembership, Userfrom overbae.models.inference import DeployedModelfrom overbae.services.inference_client import InferenceClientError-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("llm-gateway")]def _consume(response):diff --git a/tests/test_compute_meter.py b/tests/test_compute_meter.pyindex 573678a7..e3cbdadb 100644--- a/tests/test_compute_meter.py+++ b/tests/test_compute_meter.py@@ -6,6 +6,8 @@ import pytestfrom modal_shared.compute_usage import ComputeMeter+pytestmark = pytest.mark.covers("measured-facts")+def test_worker_without_cgroups_includes_finished_child_resource_usage():counters = {diff --git a/tests/test_connector_capability_resolution.py b/tests/test_connector_capability_resolution.pyindex 78f0917b..f9a1bd52 100644--- a/tests/test_connector_capability_resolution.py+++ b/tests/test_connector_capability_resolution.py@@ -13,7 +13,7 @@ from overbae.services.connectors.capability_resolution import (unmapped_root_names,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("vendor-connectors")]def _capability(project, name, *, path="", fn="", meta=None) -> Capability:diff --git a/tests/test_connector_contract.py b/tests/test_connector_contract.pyindex 1dcad019..5ba1ae16 100644--- a/tests/test_connector_contract.py+++ b/tests/test_connector_contract.py@@ -38,6 +38,8 @@ from overbae.services.connectors.langsmith.client import (LangSmithTimeoutError,)+pytestmark = pytest.mark.covers("vendor-connectors")+_SINCE = datetime(2026, 1, 2, tzinfo=UTC)_LS_PROJECT = "11111111-1111-1111-1111-111111111111"diff --git a/tests/test_connector_disconnect.py b/tests/test_connector_disconnect.pyindex b35e9871..520eb9b2 100644--- a/tests/test_connector_disconnect.py+++ b/tests/test_connector_disconnect.py@@ -13,7 +13,7 @@ from overbae.api.serializers import ConnectorCredentialSerializerfrom overbae.api.views import ConnectorCredentialViewSetfrom overbae.models import ConnectorCredential, ConnectorSyncConfig, Project, Span-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("vendor-connectors")]def _cred(project: Project, *, key: str = "pk-same", name: str = "LF") -> ConnectorCredential:diff --git a/tests/test_connector_mutable_rows.py b/tests/test_connector_mutable_rows.pyindex fc4fd73a..90709c4d 100644--- a/tests/test_connector_mutable_rows.py+++ b/tests/test_connector_mutable_rows.py@@ -6,7 +6,7 @@ from factories import make_connectorfrom overbae.models import ConnectorCredential, LiveScoringWork, Spanfrom overbae.tasks import connector_sync-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("vendor-connectors")]@pytest.fixturediff --git a/tests/test_connector_poll.py b/tests/test_connector_poll.pyindex 674d4a55..ddf1e60b 100644--- a/tests/test_connector_poll.py+++ b/tests/test_connector_poll.py@@ -14,7 +14,7 @@ from overbae.models import ConnectorCredential, Spanfrom overbae.services.connectors.sync import boundary_import_key, enqueue_connector_syncfrom overbae.tasks import connector_sync-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("vendor-connectors")]@pytest.fixturediff --git a/tests/test_connector_profiling.py b/tests/test_connector_profiling.pyindex e73f27f2..d7d7590e 100644--- a/tests/test_connector_profiling.py+++ b/tests/test_connector_profiling.py@@ -1,5 +1,6 @@"""The profiler must find capability boundaries without relying on the CAPABILITY type."""+import pytestfrom fakes.ledgerline import langchain_style_trace, scan_inbox_trace, triage_email_tracefrom overbae.services.connectors.braintrust.mapping import BRAINTRUST@@ -7,6 +8,8 @@ from overbae.services.connectors.langfuse.mapping import LANGFUSEfrom overbae.services.connectors.profiling import profile_capability_candidates as _profilefrom overbae.services.connectors.records import ObservationRecord+pytestmark = pytest.mark.covers("vendor-connectors")+def profile_capability_candidates(traces, conventions=LANGFUSE):return _profile(traces, conventions)diff --git a/tests/test_context_budget.py b/tests/test_context_budget.pyindex c2b479ef..a760713b 100644--- a/tests/test_context_budget.py+++ b/tests/test_context_budget.py@@ -20,6 +20,8 @@ from overbae.services.finetuning_eval import sync_eval_scoresfrom overbae.services.inference_client import ContextBudgetError, InferenceClientfrom overbae.services.judging import funnel+pytestmark = pytest.mark.covers("plans")+@pytest.mark.parametrize("payload", [{}, {"max_tokens": None}, {"max_completion_tokens": None}])def test_missing_output_limit_reserves_capacity(payload):diff --git a/tests/test_credit_topup.py b/tests/test_credit_topup.pyindex e5c834b1..8bf4d47e 100644--- a/tests/test_credit_topup.py+++ b/tests/test_credit_topup.py@@ -12,7 +12,7 @@ from overbae.api.billing import CREDIT_TOPUP_PURPOSEfrom overbae.models import BillingService, BillingTelemetry, Subscription, SubscriptionStatusfrom overbae.services.billing_ledger import FREE_CREDITS_USD, balance_usd-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]User = get_user_model()@@ -176,3 +176,22 @@ def test_an_invoice_without_a_subscription_does_not_activate_pro(stripe):user.refresh_from_db()assert user.subscription.status == SubscriptionStatus.INCOMPLETEassert balance_usd(user) == FREE_CREDITS_USD+++def test_plan_checkout_opens_one_subscription_and_refuses_an_active_plan(stripe, settings):+ settings.STRIPE_PRO_PRICE_ID = "price_pro"+ settings.FRONTEND_URL = "https://console.example"+ user = _make_user("plan-checkout")++ r = auth_client(user).post(reverse("billing-checkout"))++ assert r.status_code == 200+ [session] = stripe.sessions+ assert r.data["checkout_url"] == session["url"]+ assert session["mode"] == "subscription"+ assert session["line_items"] == [{"price": "price_pro", "quantity": "1"}]+ assert session["cancel_url"] == "https://console.example/settings?billing=cancel"+ assert session["subscription_data"]["metadata"]["user_id"] == str(user.pk)+ Subscription.objects.create(user=user, status=SubscriptionStatus.ACTIVE)+ assert auth_client(user).post(reverse("billing-checkout")).status_code == 400+ assert len(stripe.sessions) == 1diff --git a/tests/test_data_first_workflow.py b/tests/test_data_first_workflow.pyindex e4b8a17d..c974634b 100644--- a/tests/test_data_first_workflow.py+++ b/tests/test_data_first_workflow.py@@ -22,7 +22,7 @@ from overbae.services import native_evaluationfrom overbae.services.datasets import land, lifecycle, paths, rows, store, use, workbenchfrom overbae.services.datasets.partition_plans import build-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]def workspace():diff --git a/tests/test_data_workflow_migration.py b/tests/test_data_workflow_migration.pydeleted file mode 100644index b4f83e4e..00000000--- a/tests/test_data_workflow_migration.py+++ /dev/null@@ -1,61 +0,0 @@-from django.db import connections-from django.db.backends.sqlite3.base import DatabaseWrapper-from django.db.migrations.executor import MigrationExecutor-from django.test import override_settings--BASE = ("overbae", "0018_workshop_sources_and_funding")-TARGET = ("overbae", "0021_data_exploration")---def test_workflow_migration_preserves_completed_native_results(tmp_path, django_db_blocker):- original = connections["default"]- database = DatabaseWrapper(- {**original.settings_dict, "NAME": str(tmp_path / "workflow-migration.sqlite3")},- alias="default",- )- with django_db_blocker.unblock(), override_settings(MIGRATION_MODULES={}):- connections["default"] = database- try:- executor = MigrationExecutor(database)- executor.migrate([BASE])- apps = executor.loader.project_state([BASE]).apps- project = apps.get_model("overbae", "Project").objects.create(name="Frozen experiment")- dataset = apps.get_model("overbae", "Dataset").objects.create(- project=project, name="Final", intent="eval"- )- cell = apps.get_model("overbae", "Cell").objects.create(- dataset=dataset, position=0, state="ok", fingerprint="unchanged"- )- calibration = apps.get_model("overbae", "Cell").objects.create(- dataset=dataset, position=1, state="ok", fingerprint="calibration"- )- job = apps.get_model("overbae", "FinetuningJob").objects.create(- project=project, dataset=dataset, name="Saved", base_model="Qwen/Qwen3.5-4B"- )- plan = apps.get_model("overbae", "NativeEvaluationPlan").objects.create(- job=job,- final_cell=cell,- calibration_cell=calibration,- state="completed",- config={"runtime": {"app": "original"}},- calls={"final_candidate": {"call_id": "fc-original"}},- calibration={"frozen": True},- results={"original": 0.32},- )- executor = MigrationExecutor(database)- executor.migrate([TARGET])- apps = executor.loader.project_state([TARGET]).apps- restored = apps.get_model("overbae", "NativeEvaluationPlan").objects.get(pk=plan.pk)- assert restored.project_id == project.pk- assert restored.calls == {"final_candidate": {"call_id": "fc-original"}}- assert restored.calibration == {"frozen": True}- assert restored.results == {"original": 0.32}- assert restored.config["runtime"] == {"app": "original"}- assert restored.config["logarithm_floor"] is None- assert restored.final_cell_id == cell.pk- assert restored.state == "completed"- assert apps.get_model("overbae", "DecisionPerformanceRun").objects.count() == 0- assert apps.get_model("overbae", "DataExploration").objects.count() == 0- finally:- database.close()- connections["default"] = originaldiff --git a/tests/test_dataset_api.py b/tests/test_dataset_api.pyindex 940b953b..b575c0ff 100644--- a/tests/test_dataset_api.py+++ b/tests/test_dataset_api.py@@ -22,7 +22,7 @@ from overbae.models import ()from overbae.services.datasets import paths, store, use-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("lineage")]ROWS = [{"question": "q1", "answer": "a1", "tag": "keep"},@@ -59,53 +59,6 @@ def _create(client, project, rows=ROWS, **extra):return Dataset.objects.get(pk=res.data["id"])-def test_create_lands_the_source_and_reads_back_with_cells():- project = _project()- client = _client(project)- dataset = _create(client, project, rows=[dict(r) for r in EVAL_ROWS], intent="eval")- res = client.get(f"/api/datasets/{dataset.id}/")- assert res.status_code == 200- body = res.data- assert body["state"] == "idle" and body["intent"] == "eval"- assert [c["version"] for c in body["cells"]] == ["1.0"]- assert body["cells"][0]["fits"] == {"ok": True, "reason": ""}- assert body["active_version"] == "1.0" and body["rows"] == 2- assert "chat" not in body--[email protected]("split", [False, True])[email protected]("choice", ["automatic", "none", "selected"])-def test_creation_distinguishes_no_capability_from_automatic_matching(split, choice):- project = _project()- client = _client(project)- matched = Capability.objects.create(project=project, name="Matched", slug="matched")- selected = Capability.objects.create(project=project, name="Selected", slug="selected")- rows = [{**row, "capability_id": str(matched.id)} for row in EVAL_ROWS * 2]- body = {"name": "Choice", "project": str(project.id), "source": {"rows": rows}}- if choice != "automatic":- body["capability"] = None if choice == "none" else str(selected.id)- if split:- body.update(eval_percent=30, position="tail")- else:- body["intent"] = "train"- response = client.post(- "/api/datasets/split/" if split else "/api/datasets/", body, format="json"- )- assert response.status_code == 201, response.data- ids = (- [response.data[role]["id"] for role in ("train", "eval")]- if split- else [response.data["id"]]- )- expected = {"automatic": matched.id, "none": None, "selected": selected.id}[choice]- for dataset in Dataset.objects.filter(pk__in=ids):- assert dataset.state == Dataset.State.IDLE, dataset.error- assert dataset.capability_rank[0]["capability_id"] == str(matched.id)- assert dataset.capability_id == expected- if not split:- assert dataset.intent == "train"--def test_create_from_traces_validates_the_selection_before_creating():project = _project()client = _client(project)@@ -139,6 +92,7 @@ def test_create_from_traces_validates_the_selection_before_creating():assert queued.call_args.kwargs["kwargs"]["source"] == {"traces": {"trace_ids": [trace]}}[email protected]("tenancy")def test_create_rejects_two_sources_and_a_foreign_capability():project = _project()client = _client(project)@@ -162,20 +116,6 @@ def test_create_rejects_two_sources_and_a_foreign_capability():assert res.status_code == 404-def test_rows_carry_diff_marks_against_the_cell_before():- project = _project()- client = _client(project)- dataset = _create(client, project)- shape = import_version(- dataset, [dict(r, tag=r["tag"].upper(), source_row=i) for i, r in enumerate(ROWS)]- )- res = client.get(f"/api/datasets/{dataset.id}/rows/", {"cell": str(shape.id), "diff": "1"})- assert res.status_code == 200- marks = res.data["marks"]- assert marks[0] == {"before": {"tag": "keep"}}- assert len(marks) == 3--def test_row_pages_cross_storage_groups_without_changing_values_or_positions(monkeypatch):monkeypatch.setattr(store, "ROW_GROUP_SIZE", 3)project = _project()@@ -260,18 +200,6 @@ def test_patch_sets_capability_intent_and_active_cell():}-def test_list_filters_by_intent_and_shows_the_active_version():- project = _project()- client = _client(project)- _create(client, project, rows=[dict(r) for r in EVAL_ROWS], intent="eval")- _create(client, project, intent="train")- res = client.get("/api/datasets/", {"project": str(project.id), "intent": "eval"})- assert res.status_code == 200- assert [d["intent"] for d in res.data["results"]] == ["eval"]- assert res.data["results"][0]["active_version"] == "1.0"- assert res.data["results"][0]["cells"] == []--def test_preparation_names_an_optimizer_experiment_by_its_capability():project = _project()client = _client(project)@@ -317,6 +245,7 @@ def test_delete_refused_while_a_version_is_used():assert res.status_code == 204[email protected]("tenancy")def test_another_project_reads_and_writes_nothing():project = _project()dataset = _create(_client(project), project, intent="eval")diff --git a/tests/test_dataset_chain.py b/tests/test_dataset_chain.pyindex 32b9e1fe..f83e5775 100644--- a/tests/test_dataset_chain.py+++ b/tests/test_dataset_chain.py@@ -8,7 +8,7 @@ from conftest import EVAL_ROWS, TRAIN_ROWS, frozen_dataset, import_version, revifrom overbae.models import Capability, Cell, Dataset, EvalRun, Projectfrom overbae.services.datasets import diff, land, lifecycle, paths, store, use-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("lineage")]def _project() -> Project:diff --git a/tests/test_dataset_consumer_contract.py b/tests/test_dataset_consumer_contract.pyindex 4a66f816..f681f4ca 100644--- a/tests/test_dataset_consumer_contract.py+++ b/tests/test_dataset_consumer_contract.py@@ -13,6 +13,8 @@ from overbae.services.datasets.examples import prepare_examplesfrom overbae.services.datasets.partition import contamination_keys, split_rowsfrom overbae.services.datasets.sampling import select_rows+pytestmark = pytest.mark.covers("data-logic")+def example(index=1, mode="extraction"):return {diff --git a/tests/test_dataset_context.py b/tests/test_dataset_context.pyindex 50fe7941..5986b5d9 100644--- a/tests/test_dataset_context.py+++ b/tests/test_dataset_context.py@@ -12,6 +12,8 @@ from overbae.services.datasets.examples import prepare_examplesfrom overbae.services.datasets.profile import profile_recordsfrom overbae.services.finetuning_validator import row_to_finetuning_line, validate_rows+pytestmark = pytest.mark.covers("recommendations")+def example(prompt="Extract fields", **extra):return {diff --git a/tests/test_dataset_context_task_type.py b/tests/test_dataset_context_task_type.pyindex 37538213..15e95989 100644--- a/tests/test_dataset_context_task_type.py+++ b/tests/test_dataset_context_task_type.py@@ -13,7 +13,7 @@ from overbae.services.benchmarks.taxonomy import TaskTypefrom overbae.services.datasets import profilerfrom overbae.services.recommendation import get_recommendation-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("recommendations")]_LONG_PARAGRAPH = ("The quarterly filing restates revenue across every regional segment and "diff --git a/tests/test_dataset_contract.py b/tests/test_dataset_contract.pyindex 8766f8c7..99866671 100644--- a/tests/test_dataset_contract.py+++ b/tests/test_dataset_contract.py@@ -9,6 +9,8 @@ from overbae.services.datasets import contractfrom overbae.services.datasets.rows import row_from_recordfrom overbae.services.finetuning_validator import row_to_finetuning_line, validate_rows+pytestmark = pytest.mark.covers("data-logic")+TURNS = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"}]TOOLS = [{"type": "function", "function": {"name": "f", "parameters": {"type": "object"}}}]diff --git a/tests/test_dataset_dispatch.py b/tests/test_dataset_dispatch.pyindex ff0b0136..f843ec4f 100644--- a/tests/test_dataset_dispatch.py+++ b/tests/test_dataset_dispatch.py@@ -11,7 +11,7 @@ from overbae.services.datasets import dispatchfrom overbae.services.datasets.lifecycle import DatasetErrorfrom overbae.tasks.datasets import land as land_task-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("work-once")]ROWS = [{"question": "q1", "answer": "a1"}]diff --git a/tests/test_dataset_files.py b/tests/test_dataset_files.pyindex 8f2c0f93..45a00275 100644--- a/tests/test_dataset_files.py+++ b/tests/test_dataset_files.py@@ -6,6 +6,8 @@ import pytestfrom overbae.services.datasets import files+pytestmark = pytest.mark.covers("data-logic")+def _read(tmp_path, name: str, body: str | bytes):path = tmp_path / namediff --git a/tests/test_dataset_fingerprints.py b/tests/test_dataset_fingerprints.pyindex e05a48d3..2955ef0b 100644--- a/tests/test_dataset_fingerprints.py+++ b/tests/test_dataset_fingerprints.py@@ -2,6 +2,8 @@ import pytestfrom overbae.services.datasets.partition import contamination_keys, content_key, preserve_lineage+pytestmark = pytest.mark.covers("data-logic")+@pytest.mark.parametrize("column",diff --git a/tests/test_dataset_gate.py b/tests/test_dataset_gate.pyindex 63ef55e7..9edb2891 100644--- a/tests/test_dataset_gate.py+++ b/tests/test_dataset_gate.py@@ -28,7 +28,7 @@ from overbae.services.datasets import lifecycle, usefrom overbae.tasks import datasets as dataset_tasksfrom tests.workshop_script_fixtures import retained_package, select_script-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("lineage")]def _setup():diff --git a/tests/test_dataset_import_receipts.py b/tests/test_dataset_import_receipts.pyindex 4e57d69d..6c44350d 100644--- a/tests/test_dataset_import_receipts.py+++ b/tests/test_dataset_import_receipts.py@@ -21,7 +21,7 @@ from overbae.services.datasets.lifecycle import DatasetErrorfrom overbae.tasks import datasets as dataset_tasksfrom overbae.tasks.cleanup_tmp import cleanup_uploads-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("work-once")]@pytest.fixturediff --git a/tests/test_dataset_land_traces.py b/tests/test_dataset_land_traces.pyindex a9732132..671bbac5 100644--- a/tests/test_dataset_land_traces.py+++ b/tests/test_dataset_land_traces.py@@ -14,7 +14,7 @@ from factories import make_projectfrom overbae.models import Capability, Conversation, Dataset, Spanfrom overbae.services.datasets import land, paths, selection-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]NS = 1_700_000_000_000_000_000COLUMNS = [spec["name"] for spec in land.TRACE_MANIFEST]@@ -253,6 +253,18 @@ def test_a_selected_capability_lands_its_own_invocation_and_score():assert row["score"] == pytest.approx(0.8)+def test_a_selected_capability_absent_from_a_trace_lands_the_whole_trace():+ project = make_project()+ matched = Capability.objects.create(project=project, name="Matched", slug="matched")+ selected = Capability.objects.create(project=project, name="Selected", slug="selected")+ trace, _ = _chat_trace(project, text="kept", capability=matched)+ dataset = Dataset.objects.create(project=project, name="t", capability=selected)+ land.land_traces(dataset, {"trace_ids": [trace]})+ df = read_table(paths.cell_path(dataset.id, dataset.source.id))+ assert df["trace_id"].tolist() == [trace]+ assert df.iloc[0]["messages"][-1]["content"] == "kept"++def test_repeated_invocations_of_the_selected_capability_fail_the_landing():project = make_project()router = Capability.objects.create(project=project, name="Router", slug="router")diff --git a/tests/test_dataset_preparation.py b/tests/test_dataset_preparation.pyindex 41ea70b0..15f6d84a 100644--- a/tests/test_dataset_preparation.py+++ b/tests/test_dataset_preparation.py@@ -2,6 +2,8 @@ import pytestfrom overbae.services.datasets.partition import content_key, split_rows+pytestmark = pytest.mark.covers("data-logic")+def test_split_clusters_content_and_groups_and_reports_stratification():source = [diff --git a/tests/test_dataset_query_capacity.py b/tests/test_dataset_query_capacity.pyindex 26b8d4c2..a45e5d02 100644--- a/tests/test_dataset_query_capacity.py+++ b/tests/test_dataset_query_capacity.py@@ -2,6 +2,8 @@ import timeimport pytestfrom asgiref.sync import async_to_sync+from django.db import connection+from django.test.utils import CaptureQueriesContextfrom factories import make_project, make_userfrom overbae.models import APIToken, Dataset@@ -9,7 +11,7 @@ from overbae.services.datasets import landfrom overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("capacity")]def test_missing_query_admission_backend_is_retryable_and_does_not_change_the_source(settings):@@ -37,3 +39,18 @@ def test_missing_query_admission_backend_is_retryable_and_does_not_change_the_soassert error["retryable"] and error["fields"]["cell"] == str(dataset.active_cell.pk)assert error["fields"]["retry_after_seconds"] == "1"assert dataset.cells.count() == 1+++def _landing_queries(rows):+ dataset = Dataset.objects.create(project=make_project(), name="t", intent="train")+ with CaptureQueriesContext(connection) as queries:+ land.land_rows(dataset, rows)+ return len(queries)+++def test_landing_queries_do_not_grow_with_rows():+ rows = [+ {"messages": [{"role": "user", "content": f"q{i}"}, {"role": "assistant", "content": "a"}]}+ for i in range(3000)+ ]+ assert _landing_queries(rows) < _landing_queries(rows[:10]) + 10diff --git a/tests/test_dataset_scale.py b/tests/test_dataset_scale.pyindex 38220038..ffc6d90a 100644--- a/tests/test_dataset_scale.py+++ b/tests/test_dataset_scale.py@@ -11,7 +11,7 @@ import pytestfrom overbae.models import Dataset, Projectfrom overbae.services.datasets import diff, land, paths, store-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.load, pytest.mark.covers("capacity")]ROWS = 20_000diff --git a/tests/test_dataset_selection.py b/tests/test_dataset_selection.pyindex 436e408a..896d3203 100644--- a/tests/test_dataset_selection.py+++ b/tests/test_dataset_selection.py@@ -11,7 +11,7 @@ from factories import make_projectfrom overbae.models import Spanfrom overbae.services.datasets.selection import TraceSource, TraceSourceError, allowed_filters-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]NS = 1_700_000_000_000_000_000diff --git a/tests/test_dataset_snapshots.py b/tests/test_dataset_snapshots.pyindex be7f6d68..cc3194d8 100644--- a/tests/test_dataset_snapshots.py+++ b/tests/test_dataset_snapshots.py@@ -4,7 +4,7 @@ from django.utils import timezonefrom overbae.models import Cell, Dataset, Projectfrom overbae.services.mcp.resources import dataset_run_job_payload-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("lineage")]@pytest.mark.parametrize("count", [1, 10])diff --git a/tests/test_dataset_split.py b/tests/test_dataset_split.pyindex 7a759d03..9396d3d4 100644--- a/tests/test_dataset_split.py+++ b/tests/test_dataset_split.py@@ -6,6 +6,7 @@ from __future__ import annotationsimport uuidimport pytest+from mcp_fixtures import call_toolfrom rest_framework.test import APIClientfrom rest_framework_simplejwt.tokens import RefreshToken@@ -13,7 +14,7 @@ from overbae.models import Dataset, Project, ProjectMembership, Span, Userfrom overbae.services.datasets import dispatch, land, paths, storefrom overbae.services.datasets.lifecycle import DatasetError-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("data-logic")]ROWS = [{"input": f"q{i}", "expected_output": f"a{i}"} for i in range(10)]@@ -184,10 +185,8 @@ def test_split_endpoint_returns_the_pair_and_validates_the_cut():@pytest.mark.django_db(transaction=True)def test_mcp_create_from_traces_with_split_returns_both_datasets():- import asynciofrom overbae.models import APIToken- from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContextproject, user = _project(), _user()@@ -217,7 +216,7 @@ def test_mcp_create_from_traces_with_split_returns_both_datasets():)def call(arguments):- return asyncio.run(CATALOG.call("create_dataset_from_traces", arguments, context))+ return call_tool("create_dataset_from_traces", arguments, context)refused = call({"name": "T", "trace_ids": traces, "intent": "train", "split": {}})assert refused.isError is Truediff --git a/tests/test_dataset_statistics.py b/tests/test_dataset_statistics.pyindex d14b46d2..689252a4 100644--- a/tests/test_dataset_statistics.py+++ b/tests/test_dataset_statistics.py@@ -8,6 +8,8 @@ import pytestfrom overbae.services.datasets import store+pytestmark = pytest.mark.covers("recovery")+def test_concurrent_statistics_are_isolated_cached_and_labelled(tmp_path):path = tmp_path / "rows.parquet"diff --git a/tests/test_dataset_store.py b/tests/test_dataset_store.pyindex 9402e9e6..fd259f39 100644--- a/tests/test_dataset_store.py+++ b/tests/test_dataset_store.py@@ -8,6 +8,8 @@ import pytestfrom overbae.services.datasets import files, store+pytestmark = pytest.mark.covers("lineage")+ROWS = [{"source_row": 0,diff --git a/tests/test_dataset_streaming.py b/tests/test_dataset_streaming.pyindex 2cdf432e..274d3700 100644--- a/tests/test_dataset_streaming.py+++ b/tests/test_dataset_streaming.py@@ -6,6 +6,8 @@ import pytestfrom overbae.models import Dataset, Projectfrom overbae.services.datasets import files, land, paths, store+pytestmark = pytest.mark.covers("data-logic")+def test_stream_writer_checks_late_types_without_retaining_rows(tmp_path):class Row(dict):diff --git a/tests/test_dataset_transfers.py b/tests/test_dataset_transfers.pyindex acfc8ddb..a83fa711 100644--- a/tests/test_dataset_transfers.py+++ b/tests/test_dataset_transfers.py@@ -18,7 +18,7 @@ from overbae.models import ()from overbae.services.datasets import files, paths, store-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("lineage")]@pytest.fixturediff --git a/tests/test_dataset_uploads.py b/tests/test_dataset_uploads.pyindex 2b24198d..92b1899e 100644--- a/tests/test_dataset_uploads.py+++ b/tests/test_dataset_uploads.py@@ -12,6 +12,8 @@ from rest_framework.test import APIClientfrom overbae.models import Dataset, Project, ProjectMembership, Userfrom overbae.services.datasets import files, paths+pytestmark = pytest.mark.covers("data-logic")+def _upload(name, content):upload_id, _ = files.begin_upload(name)diff --git a/tests/test_decision_artifact.py b/tests/test_decision_artifact.pyindex df41e5a7..2bdc4485 100644--- a/tests/test_decision_artifact.py+++ b/tests/test_decision_artifact.py@@ -4,6 +4,8 @@ import pytestfrom modal_shared.decision_artifact import read_artifact, seal_artifact+pytestmark = pytest.mark.covers("lineage")+def checkpoint(path):path.mkdir()diff --git a/tests/test_decision_batching.py b/tests/test_decision_batching.pyindex aec19dd2..d1363121 100644--- a/tests/test_decision_batching.py+++ b/tests/test_decision_batching.py@@ -2,6 +2,8 @@ import pytestfrom modal_shared.decision_batching import microbatches+pytestmark = pytest.mark.covers("plans")+def rows(lengths):return [{"key": str(i), "input_ids": [i] * n} for i, n in enumerate(lengths)]diff --git a/tests/test_decision_benchmark_conversion.py b/tests/test_decision_benchmark_conversion.pyindex c5a3621e..07bcf135 100644--- a/tests/test_decision_benchmark_conversion.py+++ b/tests/test_decision_benchmark_conversion.py@@ -5,6 +5,8 @@ import pytestfrom scripts.decision_benchmarks import convert_row, prepare+pytestmark = pytest.mark.covers("metrics-math")+def hard_row():payload = {diff --git a/tests/test_decision_benchmark_scoring.py b/tests/test_decision_benchmark_scoring.pyindex a6aec113..ce67f08f 100644--- a/tests/test_decision_benchmark_scoring.py+++ b/tests/test_decision_benchmark_scoring.py@@ -7,6 +7,8 @@ from modal_shared.decision_inference import input_digestfrom modal_shared.training_data import file_digestfrom overbae.services.decision_benchmark_scoring import compare_suite, score_suite+pytestmark = pytest.mark.covers("metrics-math")+def fixture(tmp_path):suite = tmp_path / "suite"diff --git a/tests/test_decision_checkpoint.py b/tests/test_decision_checkpoint.pyindex 73f8d4c7..bf666c21 100644--- a/tests/test_decision_checkpoint.py+++ b/tests/test_decision_checkpoint.py@@ -4,6 +4,8 @@ import pytestfrom modal_shared.decisions import compare_predictions+pytestmark = pytest.mark.covers("lineage")+def predictions():return [diff --git a/tests/test_decision_job_identity.py b/tests/test_decision_job_identity.pyindex f5cdb2b0..937d201c 100644--- a/tests/test_decision_job_identity.py+++ b/tests/test_decision_job_identity.py@@ -1,22 +1,24 @@-import asyncioimport importlibimport jsonfrom types import SimpleNamespaceimport pytest+from asgiref.sync import async_to_syncfrom conftest import frozen_datasetfrom django.apps import appsfrom django.db import connectionfrom factories import auth_client, make_project, make_userfrom mcp.shared.exceptions import McpError+from mcp_fixtures import call_toolfrom overbae.models import APIToken, DecisionJob, FinetuningJob-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext, bind_contextfrom overbae.services.mcp.resources import read_resourcefrom overbae.services.training_preparation import begin_preparationfrom overbae.tasks import finetuning+pytestmark = pytest.mark.covers("work-once")+def decision_dataset(project):return frozen_dataset(@@ -45,7 +47,7 @@ def decision_dataset(project):)[email protected]_db(transaction=True)def test_decision_identity_reuses_the_exact_training_run(monkeypatch, settings):settings.FINETUNING_BACKEND = "modal"monkeypatch.setenv("MODAL_ENVIRONMENT", "test")@@ -97,21 +99,17 @@ def test_decision_identity_reuses_the_exact_training_run(monkeypatch, settings):project=project,token=APIToken(scope={"scope": "project", "permission": ["read", "write"]}),)- mcp_catalog = asyncio.run(CATALOG.call("list_decision_training_models", {}, context))+ mcp_catalog = call_tool("list_decision_training_models", {}, context)assert not mcp_catalog.isError, mcp_catalog.structuredContentassert {entry["family"] for entry in mcp_catalog.structuredContent["models"]} == {"clef","d3","d1",}- receipt = asyncio.run(- CATALOG.call("get_job", {"kind": "decision_job", "id": first.data["id"]}, context)- )+ receipt = call_tool("get_job", {"kind": "decision_job", "id": first.data["id"]}, context)assert not receipt.isError, receipt.structuredContentassert receipt.structuredContent["details"]["finetuning_job"] == str(run.id)- progress = asyncio.run(- CATALOG.call("inspect_training_progress", {"job": first.data["id"]}, context)- )+ progress = call_tool("inspect_training_progress", {"job": first.data["id"]}, context)assert not progress.isError, progress.structuredContentasync def read_decision_resource(bound_context):@@ -119,49 +117,43 @@ def test_decision_identity_reuses_the_exact_training_run(monkeypatch, settings):contents = list(await read_resource(f"overmind://jobs/decision_job/{first.data['id']}"))return json.loads(contents[0].content)- resource = asyncio.run(read_decision_resource(context))+ resource = async_to_sync(read_decision_resource)(context)assert resource["id"] == first.data["id"]assert resource["finetuning_job"] == str(run.id)- estimate = asyncio.run(- CATALOG.call(- "estimate_finetune",- {- "dataset": str(dataset.id),- "base_model": "Cloudflare/clef-flash",- "validation_enabled": False,- },- context,- )+ estimate = call_tool(+ "estimate_finetune",+ {+ "dataset": str(dataset.id),+ "base_model": "Cloudflare/clef-flash",+ "validation_enabled": False,+ },+ context,)assert not estimate.isError, estimate.structuredContentassert estimate.structuredContent["training_contract"]["inference_contract"] == "decision"- launched = asyncio.run(- CATALOG.call(- "start_decision_job",- {- "dataset": str(dataset.id),- "base_model": "Cloudflare/clef-flash",- "request_key": "decision-run-mcp",- "validation_enabled": False,- },- context,- )+ launched = call_tool(+ "start_decision_job",+ {+ "dataset": str(dataset.id),+ "base_model": "Cloudflare/clef-flash",+ "request_key": "decision-run-mcp",+ "validation_enabled": False,+ },+ context,)assert not launched.isError, launched.structuredContentassert launched.structuredContent["decision_job"]["kind"] == "decision_job"- replay = asyncio.run(- CATALOG.call(- "start_decision_job",- {- "dataset": str(dataset.id),- "base_model": "Cloudflare/clef-flash",- "request_key": "decision-run-mcp",- "validation_enabled": False,- },- context,- )+ replay = call_tool(+ "start_decision_job",+ {+ "dataset": str(dataset.id),+ "base_model": "Cloudflare/clef-flash",+ "request_key": "decision-run-mcp",+ "validation_enabled": False,+ },+ context,)assert not replay.isError, replay.structuredContentassert (@@ -178,12 +170,10 @@ def test_decision_identity_reuses_the_exact_training_run(monkeypatch, settings):project=other_project,token=APIToken(scope={"scope": "project", "permission": ["read"]}),)- hidden = asyncio.run(- CATALOG.call("get_job", {"kind": "decision_job", "id": first.data["id"]}, other_context)- )+ hidden = call_tool("get_job", {"kind": "decision_job", "id": first.data["id"]}, other_context)assert hidden.isErrorwith pytest.raises(McpError):- asyncio.run(read_decision_resource(other_context))+ async_to_sync(read_decision_resource)(other_context)unsupported = client.post("/api/decision-jobs/",@@ -201,7 +191,7 @@ def test_decision_identity_reuses_the_exact_training_run(monkeypatch, settings):assert wrong_hyperparameters.status_code == 400[email protected]_db(transaction=True)def test_general_training_launch_exposes_decision_identity(monkeypatch, settings):settings.FINETUNING_BACKEND = "modal"monkeypatch.setattr(@@ -230,7 +220,7 @@ def test_general_training_launch_exposes_decision_identity(monkeypatch, settingsassert general_training.data["decision_job_id"] == str(identity.id)[email protected]_db(transaction=True)def test_decision_preparation_creates_the_same_training_identity(settings):settings.FINETUNING_BACKEND = "modal"user = make_user()@@ -262,22 +252,20 @@ def test_decision_preparation_creates_the_same_training_identity(settings):project=project,token=APIToken(scope={"scope": "project", "permission": ["read", "write"]}),)- prepared = asyncio.run(- CATALOG.call(- "prepare_training_data",- {- "dataset": str(dataset.id),- "base_model": "Cloudflare/clef-flash",- "context_length": 32768,- },- context,- )+ prepared = call_tool(+ "prepare_training_data",+ {+ "dataset": str(dataset.id),+ "base_model": "Cloudflare/clef-flash",+ "context_length": 32768,+ },+ context,)assert not prepared.isError, prepared.structuredContentassert prepared.structuredContent["decision_job"]["id"] == str(job.decision_job.id)[email protected]_db(transaction=True)def test_existing_native_training_run_receives_decision_identity():user = make_user()project = make_project(member=user)diff --git a/tests/test_decision_metrics.py b/tests/test_decision_metrics.pyindex 98e6f2ce..d251775f 100644--- a/tests/test_decision_metrics.py+++ b/tests/test_decision_metrics.py@@ -4,6 +4,8 @@ import pytestfrom modal_shared.decision_metrics import score_decision+pytestmark = pytest.mark.covers("metrics-math")+def request(kind="choice", count=2):return {diff --git a/tests/test_decision_performance_workflow.py b/tests/test_decision_performance_workflow.pyindex 38e542d0..3e7a00c1 100644--- a/tests/test_decision_performance_workflow.py+++ b/tests/test_decision_performance_workflow.py@@ -9,7 +9,7 @@ from overbae.models import DecisionPerformanceRequest, DecisionPerformanceRunfrom overbae.services import decision_performance, native_evaluationfrom overbae.services.decision_performance import validate_response-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("work-once")]def test_saved_performance_workload_measures_client_requests_and_retains_failures():diff --git a/tests/test_decision_prediction.py b/tests/test_decision_prediction.pyindex 1e4408fd..b82910a9 100644--- a/tests/test_decision_prediction.py+++ b/tests/test_decision_prediction.py@@ -8,6 +8,8 @@ import pytestfrom modal_shared.decision_inference import prepare_requestsfrom modal_shared.serving.artifacts import digest_json+pytestmark = pytest.mark.covers("data-logic")+@dataclassclass EncodedRecord:diff --git a/tests/test_decision_provider_recovery.py b/tests/test_decision_provider_recovery.pyindex db1b0249..1f94fcd6 100644--- a/tests/test_decision_provider_recovery.py+++ b/tests/test_decision_provider_recovery.py@@ -10,7 +10,7 @@ from overbae.services import decision_providers, native_evaluationfrom overbae.services.decision_providers import interpret_responsefrom overbae.services.native_evaluation import create_plan-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("work-once")]def fixture():diff --git a/tests/test_decision_quality_journey.py b/tests/test_decision_quality_journey.pyindex e64dc695..a09dc39c 100644--- a/tests/test_decision_quality_journey.py+++ b/tests/test_decision_quality_journey.py@@ -6,6 +6,8 @@ from modal_shared.training_monitoring import fingerprintfrom overbae.models import Dataset, FinetuningJob, Projectfrom overbae.services import training_monitoring+pytestmark = pytest.mark.covers("measured-facts")+@pytest.mark.django_dbdef test_native_quality_survives_receipts_replay_and_later_loss_check():diff --git a/tests/test_decision_target_semantics.py b/tests/test_decision_target_semantics.pyindex 4033308c..6640bd2b 100644--- a/tests/test_decision_target_semantics.py+++ b/tests/test_decision_target_semantics.py@@ -6,6 +6,8 @@ import pytestfrom modal_shared.decisions import decision_line, decision_requestfrom overbae.services.datasets.contract import measure+pytestmark = pytest.mark.covers("data-logic")+def request():return {diff --git a/tests/test_decision_training.py b/tests/test_decision_training.pyindex 79a4fe6d..c421ad23 100644--- a/tests/test_decision_training.py+++ b/tests/test_decision_training.py@@ -15,6 +15,8 @@ from overbae.services.datasets.contract import measure, training_linefrom overbae.services.finetuning_validator import validate_dataset, validate_rowsfrom overbae.services.training_preparation import request_preparation+pytestmark = pytest.mark.covers("data-logic")+def example():return {diff --git a/tests/test_decision_workshop.py b/tests/test_decision_workshop.pyindex e7626676..8cb2a74a 100644--- a/tests/test_decision_workshop.py+++ b/tests/test_decision_workshop.py@@ -10,7 +10,7 @@ from overbae.services.datasets.examples import prepare_examplesfrom overbae.services.datasets.profile import profile_recordsfrom overbae.services.datasets.review import decision_changed-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]def corpus(settings, tmp_path, intent, records):diff --git a/tests/test_dedicated_deployment.py b/tests/test_dedicated_deployment.pyindex c702dd6c..cc3236c6 100644--- a/tests/test_dedicated_deployment.py+++ b/tests/test_dedicated_deployment.py@@ -13,27 +13,13 @@ from rest_framework.test import APIClientfrom rest_framework_simplejwt.tokens import RefreshTokenfrom overbae.core.errors import InputValidationError-from overbae.modal.gpu_selector import GPU_TIERS, dedicated_gpu_names, select_gpufrom overbae.models import BillingTelemetry, DedicatedDeployment, InferenceCall, Project, Userfrom overbae.models.billing import BillingServicefrom overbae.models.inference import DeployedModelfrom overbae.services import dedicatedfrom overbae.services.provider_pricing import refresh_rates-pytestmark = pytest.mark.django_db--_SMALL = {- "total_params_b": 3,- "num_attn_layers": 28,- "num_kv_heads": 8,- "head_dim": 128,-}-_HUGE = {- "total_params_b": 70,- "num_attn_layers": 80,- "num_kv_heads": 8,- "head_dim": 128,-}+pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]def _user() -> User:@@ -69,15 +55,6 @@ def _ok(**_kwargs):}-def test_h100_is_a_dedicated_choice_beside_a100_and_not_a_serverless_pick():- names = dedicated_gpu_names(_SMALL, 2048, fp8=False)- assert "A100-80GB" in names- assert "H100" in names- assert "H100" not in dedicated_gpu_names(_HUGE, 2048, fp8=False)- assert "H100" not in {tier["name"] for tier in GPU_TIERS}- assert select_gpu(_SMALL, 2048)[0] != "H100"--def test_missing_rate_refuses_start_and_a_second_start_conflicts(fake_modal):refresh_rates()user = _user()@@ -131,6 +108,7 @@ def test_stopped_deployment_can_restart_with_its_saved_configuration(fake_modal)assert restarted.idle_shutdown_seconds == 600[email protected]("ledger")def test_running_replicas_are_metered_and_idle_replicas_are_not(fake_modal):refresh_rates()user = _user()@@ -188,6 +166,7 @@ def test_gpu_change_scales_the_previous_gpu_to_zero(fake_modal):assert row.status == DedicatedDeployment.Status.DEPLOYING[email protected]("ledger")def test_dedicated_chat_skips_per_request_billing_and_appears_in_the_model_list(fake_modal):refresh_rates()user = _user()diff --git a/tests/test_dedicated_fold_stage.py b/tests/test_dedicated_fold_stage.pyindex 01032a2b..8157feb3 100644--- a/tests/test_dedicated_fold_stage.py+++ b/tests/test_dedicated_fold_stage.py@@ -2,8 +2,12 @@from pathlib import Path+import pytest+from modal_shared.serving.stage import stage_base+pytestmark = pytest.mark.covers("model-runtime")+def test_stage_links_shards_and_overlays_the_adapter_template(tmp_path: Path):base = tmp_path / "base"diff --git a/tests/test_dedicated_lora_merge.py b/tests/test_dedicated_lora_merge.pyindex af38e6f3..c796f96c 100644--- a/tests/test_dedicated_lora_merge.py+++ b/tests/test_dedicated_lora_merge.py@@ -3,9 +3,13 @@import importlibfrom types import SimpleNamespace+import pytest+from overbae.modal import modal_vllm_worker as servingfrom overbae.services.dedicated_runtime import chat, parameters, worker_class_name+pytestmark = pytest.mark.covers("model-runtime")+def test_dedicated_lora_uses_the_plain_worker_and_no_runtime_adapter():deployed = SimpleNamespace(diff --git a/tests/test_dedicated_progress.py b/tests/test_dedicated_progress.pyindex 2a0d0947..62113f4b 100644--- a/tests/test_dedicated_progress.py+++ b/tests/test_dedicated_progress.py@@ -7,6 +7,8 @@ from overbae.models import DedicatedDeployment, DeployedModel, Projectfrom overbae.services import dedicated_progressfrom overbae.services.dedicated_progress import parse_log+pytestmark = pytest.mark.covers("measured-facts")+def test_startup_counters_and_compilation_are_measured():assert parse_log(diff --git a/tests/test_dedicated_usage.py b/tests/test_dedicated_usage.pyindex 50443c7f..e99dd2f1 100644--- a/tests/test_dedicated_usage.py+++ b/tests/test_dedicated_usage.py@@ -7,6 +7,8 @@ from django.utils import timezonefrom overbae.models import BillingTelemetry, DedicatedDeployment, DeployedModel, Project, Userfrom overbae.services.inference_metrics import dedicated_usage+pytestmark = pytest.mark.covers("measured-facts")+@pytest.mark.django_dbdef test_dedicated_usage_is_model_scoped_and_preserves_missing_measurements():diff --git a/tests/test_document_service.py b/tests/test_document_service.pyindex 3a588260..e693ec9f 100644--- a/tests/test_document_service.py+++ b/tests/test_document_service.py@@ -6,6 +6,8 @@ import pytestfrom overbae.services.datasets import documentsfrom sandbox.protocol import header_bytes+pytestmark = pytest.mark.covers("sandbox")+def test_parser_refuses_scripts_and_mismatched_bytes(sandbox_server):url, token = sandbox_server@@ -43,7 +45,7 @@ def test_parser_configuration_has_no_in_process_fallback(settings, tmp_path):documents.extract(path, filename=path.name)[email protected]_db(transaction=True)def test_completed_ocr_pages_survive_interruption_and_stay_project_scoped():import uuid@@ -158,7 +160,7 @@ def test_progress_backpressure_preserves_checkpoint_and_does_not_block_watchdog(assert received == [{"ocr_checkpoint": {"page": 1}}][email protected]_db(transaction=True)def test_corrupt_checkpoint_is_recomputed_and_expiry_is_bounded():import uuidfrom datetime import timedeltadiff --git a/tests/test_ecs_worker_rollout.py b/tests/test_ecs_worker_rollout.pyindex 3d5cfc2e..a43c21b4 100644--- a/tests/test_ecs_worker_rollout.py+++ b/tests/test_ecs_worker_rollout.py@@ -7,6 +7,8 @@ import pytestfrom scripts import deploy_ecsfrom scripts.deploy_ecs import migration_request, render_task_definition, service_ready+pytestmark = pytest.mark.covers("topology")+@pytest.fixturedef definition():diff --git a/tests/test_eval_context_suggestions.py b/tests/test_eval_context_suggestions.pyindex 5830fc40..9e3d196e 100644--- a/tests/test_eval_context_suggestions.py+++ b/tests/test_eval_context_suggestions.py@@ -4,6 +4,8 @@ import pytestfrom overbae.innermind import context as suggestions+pytestmark = pytest.mark.covers("recommendations")+@pytest.fixturedef catalog(monkeypatch):diff --git a/tests/test_eval_context_warnings.py b/tests/test_eval_context_warnings.pyindex 3a09dddd..06cb17aa 100644--- a/tests/test_eval_context_warnings.py+++ b/tests/test_eval_context_warnings.py@@ -9,6 +9,8 @@ from overbae.models import DeployedModel, Projectfrom overbae.services import llm_contextfrom overbae.services.judging import funnel+pytestmark = pytest.mark.covers("plans")+class Verdict(BaseModel):score: floatdiff --git a/tests/test_eval_control_capacity.py b/tests/test_eval_control_capacity.pyindex 11631f6e..bc463b4d 100644--- a/tests/test_eval_control_capacity.py+++ b/tests/test_eval_control_capacity.py@@ -10,7 +10,7 @@ from django.test.utils import CaptureQueriesContextfrom overbae.innermind import generationfrom overbae.models import EvalRun, EvalRunRow, Project-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("capacity")]def examined_history_rows(node):diff --git a/tests/test_eval_generation_admission.py b/tests/test_eval_generation_admission.pyindex 9d8b5b06..efd13e31 100644--- a/tests/test_eval_generation_admission.py+++ b/tests/test_eval_generation_admission.py@@ -12,7 +12,7 @@ from django.utils import timezonefrom overbae.innermind import generation, runsfrom overbae.models import EvalGenerationScheduler, EvalRun, EvalRunRow, Project-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("capacity")]@pytest.mark.django_db(transaction=True)diff --git a/tests/test_eval_row_api.py b/tests/test_eval_row_api.pyindex b9ad95c6..9981458d 100644--- a/tests/test_eval_row_api.py+++ b/tests/test_eval_row_api.py@@ -6,7 +6,7 @@ from rest_framework.test import APIClientfrom overbae.models import EvalRun, EvalRunRow, Project, ProjectMembership, User-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]def test_run_rows_include_paired_input_output_and_reference():@@ -49,68 +49,3 @@ def test_run_rows_include_paired_input_output_and_reference():assert detail.status_code == 200, detail.dataassert detail.data["input"] == "q1"assert detail.data["output"] == "answer 1"---def test_historical_run_without_rows_returns_no_paired_results():- user = User.objects.create_user(email=f"eval-legacy-{uuid.uuid4()}@test.com")- project = Project.objects.create(name="Legacy", slug=f"eval-legacy-{uuid.uuid4()}")- ProjectMembership.objects.create(user=user, project=project)- run = EvalRun.objects.create(project=project, name="Legacy", status="completed")- client = APIClient()- client.force_authenticate(user)-- response = client.get("/api/eval-run-rows/", {"run": str(run.id)})- assert response.status_code == 200, response.data- assert response.data["count"] == 0- assert response.data["results"] == []---def test_run_row_without_dataset_cell_has_no_input_or_reference():- user = User.objects.create_user(email=f"eval-no-cell-{uuid.uuid4()}@test.com")- project = Project.objects.create(name="No cell", slug=f"eval-no-cell-{uuid.uuid4()}")- ProjectMembership.objects.create(user=user, project=project)- run = EvalRun.objects.create(project=project, name="No cell", status="completed")- row = EvalRunRow.objects.create(run=run, row_index=0, output="answer", state="done")- client = APIClient()- client.force_authenticate(user)-- response = client.get("/api/eval-run-rows/", {"run": str(run.id)})- assert response.status_code == 200, response.data- assert response.data["results"][0]["input"] is None- assert response.data["results"][0]["output"] == "answer"- assert response.data["results"][0]["reference"] is None- detail = client.get(f"/api/eval-run-rows/{row.id}/")- assert detail.status_code == 200, detail.data- assert detail.data["input"] is None---def test_historical_display_index_does_not_invent_a_dataset_reference():- user = User.objects.create_user(email=f"eval-index-{uuid.uuid4()}@test.com")- project = Project.objects.create(name="Historical", slug=f"eval-index-{uuid.uuid4()}")- ProjectMembership.objects.create(user=user, project=project)- dataset = frozen_dataset(project, EVAL_ROWS, contract="eval")- run = EvalRun.objects.create(- project=project,- dataset=dataset,- cell=dataset.active_cell,- mode="generate",- status="completed",- )- EvalRunRow.objects.create(- run=run,- row_index=0,- output="uncaptured input",- metadata={"legacy_sample": {"row_index": None}},- )- EvalRunRow.objects.create(- run=run, row_index=1, output="first input", metadata={"legacy_sample": {"row_index": 0}}- )- client = APIClient()- client.force_authenticate(user)- response = client.get("/api/eval-run-rows/", {"run": str(run.id), "ordering": "row_index"})- assert response.status_code == 200, response.data- first, second = response.data["results"]- assert first["input"] is None- assert first["reference"] is None- assert second["input"] == "q1"- assert second["reference"] == "a1"diff --git a/tests/test_eval_run_provenance.py b/tests/test_eval_run_provenance.pyindex 32867cc8..8f31d46f 100644--- a/tests/test_eval_run_provenance.py+++ b/tests/test_eval_run_provenance.py@@ -10,7 +10,7 @@ from conftest import EVAL_ROWS, frozen_datasetfrom overbae.api.eval_serializers import EvalRunSerializerfrom overbae.models import EvalRun, Project-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("lineage")]@pytest.fixturediff --git a/tests/test_evaluation_activity.py b/tests/test_evaluation_activity.pyindex 0e9367ed..5842a8be 100644--- a/tests/test_evaluation_activity.py+++ b/tests/test_evaluation_activity.py@@ -13,7 +13,7 @@ from overbae.models import (User,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("http-api")]def test_activity_pages_filters_and_scopes_both_evaluation_formats():@@ -65,39 +65,3 @@ def test_activity_pages_filters_and_scopes_both_evaluation_formats():facets = client.get("/api/eval-runs/activity-datasets/", {"project": str(project.id)})assert facets.data == [{"id": str(dataset.id), "name": dataset.name}]assert client.get(url, {**params, "status": "fabricated"}).status_code == 400--- "field", ["variant_count", "evaluator_count", "dataset_name", "capability_name", "status"]-)-def test_activity_sorts_both_formats_before_pagination(field):- user = User.objects.create_user(email=f"sort-{uuid.uuid4()}@test.com")- project = Project.objects.create(name="Sort", slug=f"sort-{uuid.uuid4()}")- ProjectMembership.objects.create(user=user, project=project)- dataset = frozen_dataset(project, EVAL_ROWS, contract="eval")- response_run = EvalRun.objects.create(- project=project, dataset=dataset, name="Response", status="completed"- )- plan = NativeEvaluationPlan.objects.create(- project=project,- final_cell=dataset.active_cell,- name="Native",- state="prepared",- config={"participants": [{"key": "base"}, {"key": "trained"}]},- )- client = APIClient()- client.force_authenticate(user)- for direction in ("", "-"):- params = {"project": project.id, "ordering": direction + field, "page_size": 1}- first = client.get("/api/eval-runs/activity/", params)- second = client.get("/api/eval-runs/activity/", {**params, "page": 2})- assert first.status_code == second.status_code == 200- assert first.data["count"] == 2- assert {r["id"] for r in first.data["results"] + second.data["results"]} == {- str(response_run.id),- str(plan.id),- }- if field == "variant_count":- assert first.data["results"][0]["id"] == str(plan.id if direction else response_run.id)- if field == "evaluator_count":- assert first.data["results"][0]["id"] == str(response_run.id)diff --git a/tests/test_finetuning.py b/tests/test_finetuning.pyindex 965733bd..6710d947 100644--- a/tests/test_finetuning.py+++ b/tests/test_finetuning.py@@ -22,7 +22,7 @@ from overbae.models import (User,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("tenancy")]CELERY_PATH = "overbae.tasks.finetuning.run_finetuning.apply_async"@@ -73,52 +73,12 @@ class _FakeAsyncResult:self.id = task_id[email protected]("authentication")def test_unauthenticated_requests_rejected():r = APIClient().get(reverse("finetuningjob-list"))assert r.status_code == 401-def test_list_only_shows_jobs_in_user_projects():- u_a, p_a, _, ds_a = _setup_project_with_dataset()- _u_b, p_b, _, ds_b = _setup_project_with_dataset()-- FinetuningJob.objects.create(project=p_a, dataset=ds_a, base_model="m")- FinetuningJob.objects.create(project=p_b, dataset=ds_b, base_model="m")-- r = auth_client(u_a).get(reverse("finetuningjob-list"))- assert r.status_code == 200- projects = {str(row["project"]) for row in r.data["results"]}- assert projects == {str(p_a.id)}---def test_create_dispatches_celery_and_persists_job():- u, p, _, ds = _setup_project_with_dataset()-- with patch(CELERY_PATH, return_value=_FakeAsyncResult("celery-xyz")) as mock_apply:- r = auth_client(u).post(- reverse("finetuningjob-list"),- _job_payload(project_id=str(p.id), dataset_id=str(ds.id)),- format="json",- )-- assert r.status_code == 201, r.data- job = FinetuningJob.objects.get(pk=r.data["id"])- assert job.status == FinetuningJob.Status.QUEUED- assert job.triggered_by_id == u.id- assert job.celery_task_id == "celery-xyz"- assert job.base_model == "meta-llama/Llama-3.2-3B-Instruct"- assert {key: value for key, value in job.hyperparameters.items() if key != "monitoring"} == {- "learning_rate": 3e-4,- "epochs": 2,- "objective": "assistant_cross_entropy",- }- assert job.hyperparameters["monitoring"]["mode"] == "adaptive"-- mock_apply.assert_called_once()- kwargs = mock_apply.call_args.kwargs- assert kwargs["kwargs"] == {"job_id": str(job.id)}--def test_create_rejects_dataset_from_other_project():u, p, _, _ = _setup_project_with_dataset()foreign_project = make_project("foreign")@@ -137,6 +97,7 @@ def test_create_rejects_dataset_from_other_project():mock_apply.assert_not_called()[email protected]("authentication")def test_create_rejects_when_user_not_project_member():u_member, p, _, ds = _setup_project_with_dataset()outsider = make_user("[email protected]")@@ -178,17 +139,6 @@ def test_create_rejects_capability_from_other_project():mock_apply.assert_not_called()-def test_retrieve_includes_events_inline():- u, p, _, ds = _setup_project_with_dataset()- job = FinetuningJob.objects.create(project=p, dataset=ds, base_model="m")- FinetuningJobEvent.objects.create(job=job, event_type="status_change", message="→ queued")- FinetuningJobEvent.objects.create(job=job, event_type="log", message="prepared")-- r = auth_client(u).get(reverse("finetuningjob-detail", kwargs={"id": job.id}))- assert r.status_code == 200- assert len(r.data["events"]) == 2--def test_retrieve_404_for_foreign_job():u, _, _, _ = _setup_project_with_dataset()_, p2, _, ds2 = _setup_project_with_dataset()@@ -198,30 +148,7 @@ def test_retrieve_404_for_foreign_job():assert r.status_code == 404-def test_cancel_transitions_non_terminal_job():- u, p, _, ds = _setup_project_with_dataset()- job = FinetuningJob.objects.create(- project=p, dataset=ds, base_model="m", status=FinetuningJob.Status.RUNNING- )-- r = auth_client(u).post(reverse("finetuningjob-cancel", kwargs={"id": job.id}))- assert r.status_code == 200- job.refresh_from_db()- assert job.status == FinetuningJob.Status.CANCELLED---def test_cancel_is_noop_for_terminal_job():- u, p, _, ds = _setup_project_with_dataset()- job = FinetuningJob.objects.create(- project=p, dataset=ds, base_model="m", status=FinetuningJob.Status.SUCCEEDED- )-- r = auth_client(u).post(reverse("finetuningjob-cancel", kwargs={"id": job.id}))- assert r.status_code == 200- job.refresh_from_db()- assert job.status == FinetuningJob.Status.SUCCEEDED--[email protected]("state-machines")def test_retry_dispatches_celery_for_failed_job():u, p, _, ds = _setup_project_with_dataset()job = FinetuningJob.objects.create(@@ -244,6 +171,7 @@ def test_retry_dispatches_celery_for_failed_job():mock_apply.assert_called_once_with(kwargs={"job_id": str(job.id)})[email protected]("state-machines")def test_retry_rejects_non_failed_job():u, p, _, ds = _setup_project_with_dataset()job = FinetuningJob.objects.create(@@ -257,6 +185,7 @@ def test_retry_rejects_non_failed_job():mock_apply.assert_not_called()[email protected]("http-api")def test_events_endpoint_returns_events_for_job():u, p, _, ds = _setup_project_with_dataset()job = FinetuningJob.objects.create(project=p, dataset=ds, base_model="m")@@ -266,32 +195,3 @@ def test_events_endpoint_returns_events_for_job():r = auth_client(u).get(reverse("finetuningjob-events", kwargs={"id": job.id}))assert r.status_code == 200assert {row["message"] for row in r.data} == {"one", "two"}---def test_list_filters_by_status():- u, p, _, ds = _setup_project_with_dataset()- FinetuningJob.objects.create(- project=p, dataset=ds, base_model="m", status=FinetuningJob.Status.QUEUED- )- FinetuningJob.objects.create(- project=p, dataset=ds, base_model="m", status=FinetuningJob.Status.SUCCEEDED- )-- r = auth_client(u).get(reverse("finetuningjob-list") + "?status=succeeded")- assert r.status_code == 200- statuses = {row["status"] for row in r.data["results"]}- assert statuses == {"succeeded"}---def test_datasets_list_filters_by_project():- u, p_mine, capability_mine, _ = _setup_project_with_dataset()- _dataset(capability_mine)- _dataset(capability_mine)- _u_other, _p_other, foreign_capability, _ = _setup_project_with_dataset()- _dataset(foreign_capability)-- r = auth_client(u).get(reverse("dataset-list") + f"?project={p_mine.id}")- assert r.status_code == 200- assert r.data["count"] == 3- for row in r.data["results"]:- assert str(row["capability"]) == str(capability_mine.id)diff --git a/tests/test_finetuning_baseline_target.py b/tests/test_finetuning_baseline_target.pyindex 9402704e..a620bdc9 100644--- a/tests/test_finetuning_baseline_target.py+++ b/tests/test_finetuning_baseline_target.py@@ -24,7 +24,7 @@ from overbae.services.finetuning_eval import (sync_eval_scores,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("llm-gateway")]GATEWAY = "https://gateway.example.modal.run"diff --git a/tests/test_finetuning_baseten_plan.py b/tests/test_finetuning_baseten_plan.pyindex 607406f3..55a9e4e7 100644--- a/tests/test_finetuning_baseten_plan.py+++ b/tests/test_finetuning_baseten_plan.py@@ -15,6 +15,8 @@ from overbae.services.finetuning_policy import (from overbae.services.finetuning_runner import ModalRunnerfrom overbae.services.recommendation.hyperparams import compute_hyperparams+pytestmark = pytest.mark.covers("plans")+def _plan(**overrides):kwargs = dict(diff --git a/tests/test_finetuning_baseten_runner.py b/tests/test_finetuning_baseten_runner.pyindex 20210764..80bb15bf 100644--- a/tests/test_finetuning_baseten_runner.py+++ b/tests/test_finetuning_baseten_runner.py@@ -14,6 +14,8 @@ from overbae.services.finetuning_runner import (progress_from_snapshot,)+pytestmark = pytest.mark.covers("model-runtime")+_REMOTE_ID = "proj-1:job-9"diff --git a/tests/test_finetuning_catalog.py b/tests/test_finetuning_catalog.pyindex 1289b9f9..06f90238 100644--- a/tests/test_finetuning_catalog.py+++ b/tests/test_finetuning_catalog.py@@ -16,6 +16,8 @@ from overbae.models import Project, ProjectMembership, Userfrom overbae.services.finetuning_catalog import fetch_finetuning_model_catalogfrom overbae.services.recommendation import tier_models+pytestmark = pytest.mark.covers("model-runtime")+_MODELS_JSON = Path(__file__).resolve().parents[1] / "overbae" / "modal" / "models.json"_CATALOG: list[dict] = json.loads(_MODELS_JSON.read_text())["models"]diff --git a/tests/test_finetuning_checkpoints.py b/tests/test_finetuning_checkpoints.pyindex a678f89a..6647dae8 100644--- a/tests/test_finetuning_checkpoints.py+++ b/tests/test_finetuning_checkpoints.py@@ -8,10 +8,8 @@ from botocore.exceptions import ClientError, EndpointConnectionError, NoCredentifrom rest_framework.test import APIClientfrom overbae.models import Dataset, DeployedModel, FinetuningJob, Project, ProjectMembership, User-from overbae.services.finetuning_checkpoints import (- CheckpointArchiveError,- get_checkpoint_download_url,-)++pytestmark = pytest.mark.covers("tenancy")def _job(*, provider="modal", user_id="user-1", job_id="job-1"):@@ -22,57 +20,6 @@ def _job(*, provider="modal", user_id="user-1", job_id="job-1"):)-def test_get_checkpoint_download_url_requires_bucket(settings):- settings.AWS_BUCKET_NAME = ""- with pytest.raises(CheckpointArchiveError, match="not configured"):- get_checkpoint_download_url(_job())---def test_get_checkpoint_download_url_unsupported_provider_has_no_files(settings):- settings.AWS_BUCKET_NAME = "ft-bucket"- assert get_checkpoint_download_url(_job(provider="together")) is None--[email protected]("code", ["404", "NoSuchKey", "NotFound"])-def test_get_checkpoint_download_url_missing_object(settings, code):- settings.AWS_BUCKET_NAME = "ft-bucket"- settings.AWS_REGION = "eu-west-1"- settings.AWS_ACCESS_KEY_ID = "ak"- settings.AWS_SECRET_ACCESS_KEY = "sk"-- err = ClientError({"Error": {"Code": code, "Message": "Not Found"}}, "HeadObject")- mock_s3 = MagicMock()- mock_s3.head_object.side_effect = err-- with patch("boto3.client", return_value=mock_s3):- assert get_checkpoint_download_url(_job()) is None- mock_s3.generate_presigned_url.assert_not_called()---def test_get_checkpoint_download_url_success(settings):- settings.AWS_BUCKET_NAME = "ft-bucket"- settings.AWS_REGION = "eu-west-1"- settings.AWS_ACCESS_KEY_ID = "ak"- settings.AWS_SECRET_ACCESS_KEY = "sk"-- mock_s3 = MagicMock()- mock_s3.head_object.return_value = {"ContentLength": 42}- mock_s3.generate_presigned_url.return_value = "https://s3.example/checkpoint.zip"-- with patch("boto3.client", return_value=mock_s3):- result = get_checkpoint_download_url(_job(provider="baseten"))-- assert result == {- "name": "checkpoint.zip",- "size_bytes": 42,- "download_url": "https://s3.example/checkpoint.zip",- }- mock_s3.head_object.assert_called_once_with(- Bucket="ft-bucket",- Key="user-1/job-1/checkpoints/checkpoint.zip",- )--@pytest.fixturedef checkpoint_endpoint(db):user = User.objects.create_user(email="[email protected]", password="test")@@ -90,31 +37,6 @@ def checkpoint_endpoint(db):return client, f"/api/deployed-models/{deployed.id}/checkpoints/", job-def test_checkpoint_listing_recovers_when_archive_arrives(checkpoint_endpoint):- client, url, job = checkpoint_endpoint- s3 = MagicMock()- s3.head_object.side_effect = [- ClientError({"Error": {"Code": "404"}}, "HeadObject"),- {"ContentLength": 2_000_000},- ]- s3.generate_presigned_url.return_value = "https://s3.example/checkpoint.zip"- with patch("boto3.client", return_value=s3):- pending = client.get(url)- assert pending.status_code == 200- assert pending.json() == {"files": []}- ready = client.get(url)- assert ready.status_code == 200- assert ready.json() == {- "files": [- {- "name": "checkpoint.zip",- "size_bytes": 2_000_000,- "download_url": "https://s3.example/checkpoint.zip",- }- ]- }--@pytest.mark.parametrize("failure", ["access_denied", "transport", "credentials", "signing"])def test_checkpoint_storage_failures_remain_errors(checkpoint_endpoint, caplog, failure):client, url, job = checkpoint_endpoint@@ -138,17 +60,6 @@ def test_checkpoint_storage_failures_remain_errors(checkpoint_endpoint, caplog,assert str(job.id) in caplog.text-def test_checkpoint_listing_unsupported_provider_skips_storage(checkpoint_endpoint):- client, url, job = checkpoint_endpoint- job.provider = "together"- job.save(update_fields=["provider"])- with patch("boto3.client") as storage:- response = client.get(url)- assert response.status_code == 200- assert response.json() == {"files": []}- storage.assert_not_called()--def test_checkpoint_listing_rejects_other_project(checkpoint_endpoint):client, url, _ = checkpoint_endpointoutsider = User.objects.create_user(email="[email protected]", password="test")@@ -157,12 +68,3 @@ def test_checkpoint_listing_rejects_other_project(checkpoint_endpoint):response = client.get(url)assert response.status_code == 404storage.assert_not_called()---def test_checkpoint_download_configuration_failure_is_logged(checkpoint_endpoint, settings, caplog):- client, url, job = checkpoint_endpoint- settings.AWS_BUCKET_NAME = ""- response = client.get(url)- assert response.status_code == 502- assert response.json() == {"detail": "Checkpoint downloads are not configured."}- assert str(job.id) in caplog.textdiff --git a/tests/test_finetuning_context_length.py b/tests/test_finetuning_context_length.pyindex 2491570a..fe32dc79 100644--- a/tests/test_finetuning_context_length.py+++ b/tests/test_finetuning_context_length.py@@ -23,6 +23,8 @@ from overbae.services.recommendation.analysis import build_analysisfrom overbae.services.recommendation.constraints import eligible_modelsfrom overbae.services.recommendation.hyperparams import compute_hyperparams+pytestmark = pytest.mark.covers("plans")+_POLICY = get_training_context_policy("baseten")_BUCKETS = sorted(int(b) for b in _POLICY["context_buckets"])_HEADROOM = int(_POLICY["context_headroom"])diff --git a/tests/test_finetuning_context_reco.py b/tests/test_finetuning_context_reco.pyindex 9a69bb0b..e2eb5bef 100644--- a/tests/test_finetuning_context_reco.py+++ b/tests/test_finetuning_context_reco.py@@ -27,7 +27,7 @@ from overbae.services.finetuning_pricing import (from overbae.services.recommendation.analysis import build_analysisfrom overbae.services.recommendation.capability_context import collect_capability_context-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("plans")]CELERY_PATH = "overbae.tasks.finetuning.run_finetuning.apply_async"diff --git a/tests/test_finetuning_download_progress.py b/tests/test_finetuning_download_progress.pyindex 4b8fcca5..94913fc1 100644--- a/tests/test_finetuning_download_progress.py+++ b/tests/test_finetuning_download_progress.py@@ -4,6 +4,8 @@ otherwise-silent HF weight download; the runner parses them into PollSnapshot.from __future__ import annotations+import pytest+from overbae.services.finetuning_runner import (PollSnapshot,filter_activity_logs,@@ -11,6 +13,8 @@ from overbae.services.finetuning_runner import (progress_from_snapshot,)+pytestmark = pytest.mark.covers("measured-facts")+def _logs(*messages: str) -> list[dict]:return [{"message": m, "timestamp": str(1_000_000 + i)} for i, m in enumerate(messages)]diff --git a/tests/test_finetuning_eval_schedule.py b/tests/test_finetuning_eval_schedule.pyindex 4dd53b53..72802c0e 100644--- a/tests/test_finetuning_eval_schedule.py+++ b/tests/test_finetuning_eval_schedule.py@@ -31,7 +31,7 @@ from overbae.services.finetuning_eval import (from overbae.tasks.finetuning import run_finetuningfrom overbae.tasks.inference_controller import reconcile_deployments-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("plans")]FIELDS = ("eval_incumbent_before", "eval_incumbent_after", "eval_model_before", "eval_model_after")diff --git a/tests/test_finetuning_in_training_eval.py b/tests/test_finetuning_in_training_eval.pyindex 4a645b1b..8cc3a57d 100644--- a/tests/test_finetuning_in_training_eval.py+++ b/tests/test_finetuning_in_training_eval.py@@ -33,7 +33,7 @@ from overbae.services.finetuning_eval import (tick_job_evals,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("metrics-math")]def _setup(*, with_eval_link=True):diff --git a/tests/test_finetuning_lifecycle.py b/tests/test_finetuning_lifecycle.pyindex 96faa03f..abfac941 100644--- a/tests/test_finetuning_lifecycle.py+++ b/tests/test_finetuning_lifecycle.py@@ -1,5 +1,7 @@from __future__ import annotations+import pytest+from overbae.services.finetuning_runner import (LIFECYCLE_COMPLETED,LIFECYCLE_DEPLOYMENT,@@ -11,6 +13,8 @@ from overbae.services.finetuning_runner import (scrub_backend_names,)+pytestmark = pytest.mark.covers("state-machines")+def test_setup_before_first_step():assert lifecycle_stage("running", {"trained_steps": 0}) == LIFECYCLE_SETUPdiff --git a/tests/test_finetuning_monitor.py b/tests/test_finetuning_monitor.pyindex 343975a7..374b2abb 100644--- a/tests/test_finetuning_monitor.py+++ b/tests/test_finetuning_monitor.py@@ -18,7 +18,7 @@ from overbae.services.finetuning_runner import ()from overbae.tasks.finetuning import observe_finetuning_job-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("measured-facts")]def _auth_client(user) -> APIClient:diff --git a/tests/test_finetuning_new.py b/tests/test_finetuning_new.pyindex c5347433..690f5b33 100644--- a/tests/test_finetuning_new.py+++ b/tests/test_finetuning_new.py@@ -49,7 +49,7 @@ from overbae.services.recommendation.hyperparams import (hyperparam_provenance,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]CELERY_PATH = "overbae.tasks.finetuning.run_finetuning.apply_async"diff --git a/tests/test_finetuning_observe.py b/tests/test_finetuning_observe.pyindex d0c1635d..db4ee698 100644--- a/tests/test_finetuning_observe.py+++ b/tests/test_finetuning_observe.py@@ -17,7 +17,7 @@ from overbae.models.finetuning import FinetuningJobfrom overbae.services.finetuning_runner import PollSnapshotfrom overbae.tasks.finetuning_reconciler import _RUN_TASK, _reconcile-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("recovery")]def test_inflight_function_call_beats_stale_volume_failed():diff --git a/tests/test_finetuning_policy.py b/tests/test_finetuning_policy.pyindex 8313c9da..b266512f 100644--- a/tests/test_finetuning_policy.py+++ b/tests/test_finetuning_policy.py@@ -8,6 +8,8 @@ from overbae.services.finetuning_policy import (estimated_training_context_length,)+pytestmark = pytest.mark.covers("plans")+def test_default_epochs_scaling():assert default_epochs(10) == 10 # cappeddiff --git a/tests/test_finetuning_reconciler.py b/tests/test_finetuning_reconciler.pyindex 4d2ab628..c1f058b1 100644--- a/tests/test_finetuning_reconciler.py+++ b/tests/test_finetuning_reconciler.py@@ -14,7 +14,7 @@ from django.utils import timezonefrom overbae.models.finetuning import FinetuningJobfrom overbae.tasks.finetuning_reconciler import _reconcile-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("recovery")]def _job(status: str) -> FinetuningJob:diff --git a/tests/test_finetuning_runs_api.py b/tests/test_finetuning_runs_api.pyindex 15ad5b6e..b067b7e5 100644--- a/tests/test_finetuning_runs_api.py+++ b/tests/test_finetuning_runs_api.py@@ -1,20 +1,18 @@from __future__ import annotationsimport uuid-from datetime import timedeltaimport pytestfrom conftest import TRAIN_ROWS, frozen_datasetfrom django.db import connectionfrom django.test.utils import CaptureQueriesContextfrom django.urls import reverse-from django.utils import timezonefrom rest_framework.test import APIClientfrom rest_framework_simplejwt.tokens import RefreshTokenfrom overbae.models import Dataset, FinetuningJob, Project, ProjectMembership, User-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("tenancy")]RUNS_URL = reverse("finetuningjob-runs")LIST_URL = reverse("finetuningjob-list")@@ -45,20 +43,7 @@ def _job(project, dataset, **kwargs) -> FinetuningJob:)-def test_group_id_filter_finds_a_run_regardless_of_its_age():- client, project, dataset = _setup()- group = uuid.uuid4()- wanted = [_job(project, dataset, group_id=group) for _ in range(2)]- for _ in range(30):- _job(project, dataset, group_id=uuid.uuid4())-- r = client.get(LIST_URL, {"group_id": str(group), "ordering": "-created_at"})- assert r.status_code == 200, r.content- body = r.json()- assert body["count"] == 2- assert {row["id"] for row in body["results"]} == {str(j.id) for j in wanted}--[email protected]("capacity")@pytest.mark.parametrize("endpoint", [LIST_URL, RUNS_URL])def test_training_history_reads_dataset_versions_once_per_page(endpoint):client, project, dataset = _setup()@@ -77,109 +62,6 @@ def test_training_history_reads_dataset_versions_once_per_page(endpoint):assert len(many) <= len(first) + 1, (len(first), len(many))-def test_runs_returns_whole_runs_and_counts_runs_not_jobs():- client, project, dataset = _setup()- groups = [uuid.uuid4() for _ in range(3)]- for group in groups:- for _ in range(4):- _job(project, dataset, group_id=group)-- r = client.get(RUNS_URL, {"project": str(project.id)})- assert r.status_code == 200, r.content- body = r.json()- # 3 runs of 4 jobs each: the count is 3, not 12.- assert body["count"] == 3- assert len(body["results"]) == 3- assert all(len(run["jobs"]) == 4 for run in body["results"])- assert {run["group_id"] for run in body["results"]} == {str(g) for g in groups}- assert [run["run_id"] for run in body["results"]] == [- run["group_id"] for run in body["results"]- ]---def test_a_run_is_never_split_across_a_page_boundary():- """Paging over jobs would leave a run half on page 1, corrupting every- aggregate the client derives from its members."""- client, project, dataset = _setup()- groups = [uuid.uuid4() for _ in range(3)]- for group in groups:- for _ in range(3):- _job(project, dataset, group_id=group)-- first = client.get(RUNS_URL, {"page_size": 2}).json()- second = client.get(RUNS_URL, {"page_size": 2, "page": 2}).json()-- assert first["count"] == 3- assert len(first["results"]) == 2- assert len(second["results"]) == 1- assert all(len(run["jobs"]) == 3 for run in first["results"] + second["results"])- seen = [run["run_id"] for run in first["results"] + second["results"]]- assert sorted(seen) == sorted({str(g) for g in groups})---def test_runs_are_ordered_by_their_most_recent_job():- client, project, dataset = _setup()- older, newer = uuid.uuid4(), uuid.uuid4()- _job(project, dataset, group_id=older)- _job(project, dataset, group_id=newer)- # Give the older group a fresh job — it becomes the most recently active run.- _job(project, dataset, group_id=older)-- results = client.get(RUNS_URL).json()["results"]- assert [run["run_id"] for run in results] == [str(older), str(newer)]---def test_a_groupless_job_is_its_own_run_keyed_by_its_id():- """Matches the client's ``job.groupId ?? job.id``, and keeps ``group_id``- null so it is never mistaken for a value ``?group_id=`` would match."""- client, project, dataset = _setup()- lone = _job(project, dataset, group_id=None)-- results = client.get(RUNS_URL).json()["results"]- assert len(results) == 1- assert results[0]["run_id"] == str(lone.id)- assert results[0]["group_id"] is None- assert [job["id"] for job in results[0]["jobs"]] == [str(lone.id)]---def test_status_filter_selects_runs_with_any_matching_job_and_still_returns_them_whole():- """Run-level status means "has a job with this status"; dropping the non-matching- jobs would corrupt the status, progress and cost the client computes."""- client, project, dataset = _setup()- mixed = uuid.uuid4()- _job(project, dataset, group_id=mixed, status=FinetuningJob.Status.SUCCEEDED)- _job(project, dataset, group_id=mixed, status=FinetuningJob.Status.SUCCEEDED)- _job(project, dataset, group_id=mixed, status=FinetuningJob.Status.FAILED)- clean = uuid.uuid4()- _job(project, dataset, group_id=clean, status=FinetuningJob.Status.SUCCEEDED)-- failed = client.get(RUNS_URL, {"status": "failed"}).json()- assert failed["count"] == 1- assert failed["results"][0]["run_id"] == str(mixed)- assert sorted(job["status"] for job in failed["results"][0]["jobs"]) == [- "failed",- "succeeded",- "succeeded",- ]-- succeeded = client.get(RUNS_URL, {"status": "succeeded"}).json()- assert {run["run_id"] for run in succeeded["results"]} == {str(mixed), str(clean)}---def test_runs_honour_the_jobs_list_filters_and_search():- client, project, dataset = _setup()- other_dataset = frozen_dataset(project, TRAIN_ROWS, name="other", contract="train")- wanted = uuid.uuid4()- _job(project, dataset, group_id=wanted, name="checkout tuning")- _job(project, other_dataset, group_id=uuid.uuid4(), name="refund tuning")-- by_dataset = client.get(RUNS_URL, {"dataset": str(dataset.id)}).json()- assert [run["run_id"] for run in by_dataset["results"]] == [str(wanted)]-- by_search = client.get(RUNS_URL, {"search": "checkout"}).json()- assert [run["run_id"] for run in by_search["results"]] == [str(wanted)]--def test_runs_never_reach_another_projects_jobs():client, project, dataset = _setup()_job(project, dataset, group_id=uuid.uuid4())@@ -190,37 +72,6 @@ def test_runs_never_reach_another_projects_jobs():assert client.get(RUNS_URL).json()["count"] == 1-def test_dataset_facet_offers_every_dataset_with_a_job_not_just_the_loaded_page():- client, project, dataset = _setup()- old_dataset = frozen_dataset(project, TRAIN_ROWS, name="aardvark", contract="train")- _job(project, old_dataset, group_id=uuid.uuid4())- for _ in range(30):- _job(project, dataset, group_id=uuid.uuid4())-- r = client.get(reverse("finetuningjob-datasets"))- assert r.status_code == 200, r.content- # A bare array, not a pagination envelope.- assert r.json() == [- {"id": str(old_dataset.id), "name": "aardvark"},- {"id": str(dataset.id), "name": "ds"},- ]---def test_base_model_facet_is_distinct_and_scoped_to_the_callers_filters():- client, project, dataset = _setup()- other_dataset = frozen_dataset(project, TRAIN_ROWS, name="other", contract="train")- _job(project, dataset, base_model="a-model")- _job(project, dataset, base_model="a-model")- _job(project, other_dataset, base_model="z-model")-- r = client.get(reverse("finetuningjob-base-models"))- assert r.status_code == 200, r.content- assert r.json() == ["a-model", "z-model"]-- scoped = client.get(reverse("finetuningjob-base-models"), {"dataset": str(dataset.id)})- assert scoped.json() == ["a-model"]--def test_facets_never_leak_another_projects_values():client, project, dataset = _setup()_job(project, dataset, base_model="mine")@@ -232,6 +83,7 @@ def test_facets_never_leak_another_projects_values():assert [row["name"] for row in client.get(reverse("finetuningjob-datasets")).json()] == ["ds"][email protected]("lineage")def test_validation_pins_the_requested_cell_and_rejects_another_dataset_cell():client, project, dataset = _setup()other = frozen_dataset(project, TRAIN_ROWS, contract="train")@@ -248,73 +100,3 @@ def test_validation_pins_the_requested_cell_and_rejects_another_dataset_cell():client.post(url, {**body, "cell_id": str(other.active_cell.id)}, format="json").status_code== 404)--- "ordering",- [- "credits",- "-credits",- "name",- "-name",- "models",- "-models",- "status",- "-status",- "dataset",- "-dataset",- "created_at",- "-created_at",- "duration",- "-duration",- ],-)-def test_run_sorting_pages_whole_groups_with_filtered_members(ordering):- client, project, dataset = _setup()- a, b = uuid.uuid4(), uuid.uuid4()- _job(project, dataset, group_id=a, name="Alpha", cost_usd="2", status="succeeded")- _job(project, dataset, group_id=a, name="Alpha", cost_usd="9", status="failed")- _job(project, dataset, group_id=b, name="Beta", cost_usd="3", status="succeeded")- params = {"project": project.id, "status": "succeeded", "ordering": ordering, "page_size": 1}- first = client.get(RUNS_URL, params)- second = client.get(RUNS_URL, {**params, "page": 2})- assert first.status_code == second.status_code == 200- assert first.data["count"] == 2- rows = first.data["results"] + second.data["results"]- assert {row["run_id"] for row in rows} == {str(a), str(b)}- assert len(next(row for row in rows if row["run_id"] == str(a))["jobs"]) == 2- if ordering in ("credits", "-credits"):- assert rows[0]["run_id"] == str(a if ordering.startswith("-") else b)- if ordering in ("name", "-name"):- assert rows[0]["run_id"] == str(b if ordering.startswith("-") else a)---def test_run_sorting_rejects_unknown_columns():- client, project, _ = _setup()- assert client.get(RUNS_URL, {"project": project.id, "ordering": "private"}).status_code == 400---def test_run_names_sort_by_visible_name_without_model_prefix():- client, project, dataset = _setup()- alpha = _job(project, dataset, name="Qwen3 8B · Alpha", base_model="qwen/Qwen3-8B")- beta = _job(project, dataset, name="Beta · Llama 3.2 1B Instruct")- for ordering, first in [("name", alpha), ("-name", beta)]:- response = client.get(RUNS_URL, {"ordering": ordering, "page_size": 1})- assert response.status_code == 200, response.content- assert response.data["results"][0]["run_id"] == str(first.id)--[email protected]("ordering", ["duration", "-duration"])-def test_duration_sort_keeps_undisplayed_subsecond_durations_last(ordering):- client, project, dataset = _setup()- start = timezone.now() - timedelta(hours=1)- jobs = [- _job(project, dataset, started_at=start, completed_at=start + timedelta(seconds=seconds))- for seconds in (0.1, 90, 600)- ]- response = client.get(RUNS_URL, {"project": project.id, "ordering": ordering})- assert response.status_code == 200, response.content- measured = jobs[1:] if ordering == "duration" else jobs[:0:-1]- assert [r["run_id"] for r in response.data["results"]] == [- str(j.id) for j in [*measured, jobs[0]]- ]diff --git a/tests/test_finetuning_split.py b/tests/test_finetuning_split.pyindex cff66726..f433cb38 100644--- a/tests/test_finetuning_split.py+++ b/tests/test_finetuning_split.py@@ -4,9 +4,13 @@ import uuidimport weakreffrom types import SimpleNamespace+import pytest+from overbae.services.datasets.rows import DatasetRowfrom overbae.services.finetuning_split import split_datapoint_ids+pytestmark = pytest.mark.covers("data-logic")+def _dp(*,diff --git a/tests/test_galileo_adapter.py b/tests/test_galileo_adapter.pyindex 60d32196..319b4edc 100644--- a/tests/test_galileo_adapter.py+++ b/tests/test_galileo_adapter.py@@ -7,7 +7,7 @@ from overbae.models import ConnectorCredentialfrom overbae.services.connectors.galileo.adapter import GalileoAdapterfrom overbae.services.connectors.galileo.client import GalileoError-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("vendor-connectors")]_PROJECT = "11111111-1111-1111-1111-111111111111"_STREAM = "22222222-2222-2222-2222-222222222222"diff --git a/tests/test_galileo_client.py b/tests/test_galileo_client.pyindex 932b218b..bfddeed7 100644--- a/tests/test_galileo_client.py+++ b/tests/test_galileo_client.py@@ -4,6 +4,8 @@ import pytestfrom overbae.services.connectors.galileo.client import GalileoClient, GalileoError, split_source_id+pytestmark = pytest.mark.covers("vendor-connectors")+_PROJECT = "11111111-1111-1111-1111-111111111111"_STREAM = "22222222-2222-2222-2222-222222222222"_SOURCE = f"{_PROJECT}:{_STREAM}"diff --git a/tests/test_galileo_mapping.py b/tests/test_galileo_mapping.pyindex 9ab42579..14ac41b5 100644--- a/tests/test_galileo_mapping.py+++ b/tests/test_galileo_mapping.py@@ -2,12 +2,16 @@from types import SimpleNamespace+import pytest+from overbae.services.connectors.galileo.mapping import GALILEO, tree_to_recordsfrom overbae.services.connectors.mapping import observations_to_span_dicts as _to_span_dictsfrom overbae.services.connectors.profiling import profile_capability_candidatesfrom overbae.services.connectors.schema import CONNECTOR_SOURCE_ATTR, CONNECTOR_VERSION_ATTRfrom overbae.services.connectors.spans import span_id_for+pytestmark = pytest.mark.covers("vendor-connectors")+def observations_to_span_dicts(observations, **kwargs):return _to_span_dicts(observations, conventions=GALILEO, **kwargs)diff --git a/tests/test_guest_account.py b/tests/test_guest_account.pyindex c343e2b7..24258c39 100644--- a/tests/test_guest_account.py+++ b/tests/test_guest_account.py@@ -14,7 +14,7 @@ from overbae.api.guest import start_guest_sessionfrom overbae.models import Project, ProjectMembership, Userfrom overbae.tasks.guest_cleanup import sweep_guest_workspaces-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("authentication")]def _auth(user: User) -> APIClient:diff --git a/tests/test_idle_keepalive.py b/tests/test_idle_keepalive.pyindex efc0dc0c..90f8571a 100644--- a/tests/test_idle_keepalive.py+++ b/tests/test_idle_keepalive.py@@ -7,6 +7,8 @@ import pytestfrom overbae.api.streaming import aiter_keeping_idle_alive, iter_keeping_idle_alive+pytestmark = pytest.mark.covers("llm-gateway")+def test_first_item_is_ping():def source():diff --git a/tests/test_import_control_capacity.py b/tests/test_import_control_capacity.pyindex 8d4908cc..6768a19b 100644--- a/tests/test_import_control_capacity.py+++ b/tests/test_import_control_capacity.py@@ -13,7 +13,7 @@ from overbae.models import Dataset, DatasetImport, DatasetLandingWork, Projectfrom overbae.services.datasets import importsfrom overbae.services.queue_capacity import read_workloads-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("capacity")]@pytest.fixturediff --git a/tests/test_inference.py b/tests/test_inference.pyindex 67c50b09..ca5b31c7 100644--- a/tests/test_inference.py+++ b/tests/test_inference.py@@ -17,7 +17,7 @@ from overbae.models import ()from overbae.models.inference import DeployedModel, InferenceCall-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]def _dataset(capability: Capability) -> Dataset:@@ -49,22 +49,6 @@ def _deployed_model(project: Project, job: FinetuningJob | None = None) -> Deplo)-def test_inference_client_is_model_ready_returns_false_on_error():- from overbae.services.inference_client import InferenceClient-- client = InferenceClient(base_url="https://example.modal.run", api_key="k")- assert client.is_model_ready("some-model-id") is False---def test_inference_client_is_model_ready_returns_true_on_status():- from overbae.services.inference_client import InferenceClient-- p = make_project()- m = _deployed_model(p)- client = InferenceClient(base_url="https://example.modal.run", api_key="k")- assert client.is_model_ready(m.model_id) is True--def test_inference_client_check_health_returns_false_on_error(scripted):from overbae.services.inference_client import InferenceClient@@ -73,124 +57,6 @@ def test_inference_client_check_health_returns_false_on_error(scripted):assert client.check_health() is False-def test_make_model_id_slug_format():- from overbae.services.deployment import model_slug-- p = make_project()- job = _job(p)- slug = model_slug(job)- assert slug.startswith("ft-")- assert " " not in slug- assert slug == slug.lower()- assert str(job.id)[:8] in slug---def test_deploy_task_skips_when_no_remote_job_id():- from overbae.tasks.model_deployment import register_finetuned_model-- p = make_project()- capability = make_capability(p)- dataset = _dataset(capability)- job = FinetuningJob.objects.create(- project=p,- dataset=dataset,- base_model="meta-llama/Meta-Llama-3.1-8B-Instruct-Reference",- status="succeeded",- remote_job_id="",- )-- register_finetuned_model(job_id=str(job.id))- assert not DeployedModel.objects.filter(finetuning_job=job).exists()---def test_deploy_task_skips_non_succeeded_job():- from overbae.tasks.model_deployment import register_finetuned_model-- p = make_project()- job = _job(p, status="running")-- register_finetuned_model(job_id=str(job.id))- assert not DeployedModel.objects.filter(finetuning_job=job).exists()---def test_deploy_task_only_initializes_durable_state(fake_modal):- from overbae.tasks.model_deployment import register_finetuned_model-- job = _job(make_project(), status="succeeded")- register_finetuned_model(job_id=str(job.id))- register_finetuned_model(job_id=str(job.id))- deployed = DeployedModel.objects.get(finetuning_job=job)- assert deployed.status == "queued"- assert deployed.deployment_stage == "base"- assert deployed.deployment_attempts == 1- assert fake_modal.log == []---def test_deployed_models_list_returns_200():- u = make_user()- p = make_project()- make_member(u, p)- _deployed_model(p, _job(p))-- r = auth_client(u).get(reverse("deployedmodel-list"))- assert r.status_code == status.HTTP_200_OK- assert r.data["count"] == 1---def test_deployed_models_list_scoped_to_user_projects():- u_a = make_user()- p_a = make_project()- make_member(u_a, p_a)- _deployed_model(p_a, _job(p_a))-- p_b = make_project()- _deployed_model(p_b, _job(p_b))-- r = auth_client(u_a).get(reverse("deployedmodel-list"))- assert r.status_code == status.HTTP_200_OK- assert r.data["count"] == 1- assert str(r.data["results"][0]["project"]) == str(p_a.id)---def test_deployed_models_list_filters_by_project_server_side():- """The 30 noisy rows exceed the 25-row page, so a client-side match would miss ``mine``."""- u = make_user()- wanted, noisy = make_project(), make_project()- make_member(u, wanted)- make_member(u, noisy)- mine = _deployed_model(wanted, _job(wanted))- for _ in range(30):- _deployed_model(noisy, _job(noisy))-- r = auth_client(u).get(reverse("deployedmodel-list"), {"project": str(wanted.id)})- assert r.status_code == status.HTTP_200_OK- assert r.data["count"] == 1- assert str(r.data["results"][0]["id"]) == str(mine.id)---def test_deployed_models_list_filters_by_capability_and_status():- u = make_user()- p = make_project()- make_member(u, p)- capability = make_capability(p)- job = _job(p)- FinetuningJob.objects.filter(pk=job.pk).update(capability=capability)- mine = _deployed_model(p, job)- other = _deployed_model(p, _job(p))- DeployedModel.objects.filter(pk=other.pk).update(status=DeployedModel.Status.FAILED)-- client = auth_client(u)- by_capability = client.get(- reverse("deployedmodel-list"), {"capability": str(capability.id), "project": str(p.id)}- )- assert [str(row["id"]) for row in by_capability.data["results"]] == [str(mine.id)]-- by_status = client.get(reverse("deployedmodel-list"), {"status": "failed"})- assert [str(row["id"]) for row in by_status.data["results"]] == [str(other.id)]--def test_deployed_models_list_filters_to_the_no_capability_bucket():u = make_user()p = make_project()@@ -220,34 +86,6 @@ def test_deployed_models_list_filters_to_the_no_capability_bucket():assert bucket.data["count"] + named.data["count"] == 2[email protected]("deployment_status", ["deploying", "warming", "ready", "failed"])-def test_deployed_models_list_excludes_eval_infrastructure_before_pagination(deployment_status):- user = make_user()- project = make_project()- make_member(user, project)- trained = _deployed_model(project, _job(project))- DeployedModel.objects.filter(pk=trained.pk).update(status=deployment_status)- for index in range(26):- baseline = DeployedModel.objects.create(- project=project,- model_id=f"base--eval-{index}",- status=deployment_status,- )-- client = auth_client(user)- response = client.get(reverse("deployedmodel-list"), {"page_size": 1})- assert response.status_code == status.HTTP_200_OK- assert response.data["count"] == 1- assert response.data["next"] is None- assert [str(row["id"]) for row in response.data["results"]] == [str(trained.id)]-- search = client.get(reverse("deployedmodel-list"), {"search": "base--eval"})- assert search.data["count"] == 0- detail = client.get(reverse("deployedmodel-detail", args=[baseline.id]))- assert detail.status_code == status.HTTP_200_OK- assert DeployedModel.objects.filter(project=project, finetuning_job__isnull=True).count() == 26--def test_deployed_models_list_rejects_a_malformed_capability_id():"""The ``NO_CAPABILITY`` sentinel costs the param its ``UUIDFilter``; the 400 is raised by hand."""u = make_user()@@ -260,104 +98,7 @@ def test_deployed_models_list_rejects_a_malformed_capability_id():assert NO_CAPABILITY in str(r.data["capability"])-def test_deployed_models_list_honours_search_and_ordering():- u = make_user()- p = make_project()- make_member(u, p)- first = _deployed_model(p, _job(p))- second = _deployed_model(p, _job(p))-- client = auth_client(u)- found = client.get(reverse("deployedmodel-list"), {"search": first.model_id})- assert [str(row["id"]) for row in found.data["results"]] == [str(first.id)]-- oldest_first = client.get(reverse("deployedmodel-list"), {"ordering": "created_at"})- assert [str(row["id"]) for row in oldest_first.data["results"]] == [- str(first.id),- str(second.id),- ]- default = client.get(reverse("deployedmodel-list"))- assert [str(row["id"]) for row in default.data["results"]] == [str(second.id), str(first.id)]---def test_deployed_models_list_composes_search_with_the_capability_filter():- """``?capability=`` (DjangoFilterBackend) and ``?search=`` (SearchFilter) are separate backends- applied in sequence — they must intersect, not override each other."""- u = make_user()- p = make_project()- make_member(u, p)-- def attributed_job(capability):- job = _job(p)- FinetuningJob.objects.filter(pk=job.pk).update(capability=capability)- return job-- mine, theirs = make_capability(p), make_capability(p)-- # A job holds at most one deployment (OneToOne), so each row needs its own.- wanted = _deployed_model(p, attributed_job(mine))- same_capability_no_match = _deployed_model(p, attributed_job(mine))- other_capability_matches = _deployed_model(p, attributed_job(theirs))- DeployedModel.objects.filter(pk=wanted.pk).update(model_id="ft-needle-in-scope")- DeployedModel.objects.filter(pk=other_capability_matches.pk).update(- model_id="ft-needle-elsewhere"- )-- client = auth_client(u)- scope = {"project": str(p.id)}- both = client.get(- reverse("deployedmodel-list"), {**scope, "capability": str(mine.id), "search": "needle"}- )- assert both.status_code == status.HTTP_200_OK- assert [str(row["id"]) for row in both.data["results"]] == [str(wanted.id)]-- # Each half alone keeps a row the intersection drops — else an ignored filter would pass.- search_only = client.get(reverse("deployedmodel-list"), {**scope, "search": "needle"})- assert {str(row["id"]) for row in search_only.data["results"]} == {- str(wanted.id),- str(other_capability_matches.id),- }- capability_only = client.get(- reverse("deployedmodel-list"), {**scope, "capability": str(mine.id)}- )- assert {str(row["id"]) for row in capability_only.data["results"]} == {- str(wanted.id),- str(same_capability_no_match.id),- }---def test_deployed_models_list_still_overlays_median_latency_when_filtered():- u = make_user()- p = make_project()- make_member(u, p)- m = _deployed_model(p, _job(p))- for latency in (10, 20, 3000):- InferenceCall.objects.create(- deployed_model=m,- project=p,- latency_ms=latency,- tokens_per_second=10.0,- is_cold=False,- )-- r = auth_client(u).get(reverse("deployedmodel-list"), {"project": str(p.id)})- assert r.status_code == status.HTTP_200_OK- # Median, not the 1010ms mean the SQL annotation produced.- assert r.data["results"][0]["avg_latency_ms"] == 20---def test_deployed_models_retrieve():- u = make_user()- p = make_project()- make_member(u, p)- m = _deployed_model(p)-- r = auth_client(u).get(reverse("deployedmodel-detail", args=[str(m.id)]))- assert r.status_code == status.HTTP_200_OK- assert r.data["model_id"] == m.model_id- assert r.data["status"] == "ready"--[email protected]("tenancy")def test_deployed_models_retrieve_forbidden_for_other_user():u_a = make_user()p_a = make_project()@@ -369,6 +110,7 @@ def test_deployed_models_retrieve_forbidden_for_other_user():assert r.status_code == status.HTTP_404_NOT_FOUND[email protected]("identity")def test_deployed_models_delete_marks_deleted(scripted):gateway = scripted("http://inference.test").reply(json_body={"ok": True})u = make_user()@@ -397,6 +139,7 @@ def test_deploying_a_live_model_keeps_it_serving_without_new_gpu_work(fake_modalassert fake_modal.log == [][email protected]("recovery")def test_retrying_a_failed_deployment_requeues_it_and_clears_the_error(fake_modal):u = make_user()p = make_project()@@ -432,6 +175,7 @@ def test_deployed_models_retry_rejects_undeployable_job():assert m.status == DeployedModel.Status.FAILED[email protected]("ledger")def test_inference_pricing_estimate_and_unknown_gpu():from overbae.services.inference_pricing import estimate_call_cost, gpu_usd_per_second@@ -445,6 +189,7 @@ def test_inference_pricing_estimate_and_unknown_gpu():assert gpu_usd_per_second("nope") is None[email protected]("measured-facts")def test_model_metrics_endpoint_aggregates():u = make_user()p = make_project()@@ -476,35 +221,7 @@ def test_model_metrics_endpoint_aggregates():assert r.data["avg_latency_ms"] == pytest.approx(300.0)-def test_model_metrics_endpoint_empty_is_zeroed():- u = make_user()- p = make_project()- make_member(u, p)- m = _deployed_model(p)-- r = auth_client(u).get(reverse("deployedmodel-metrics", args=[str(m.id)]))- assert r.status_code == status.HTTP_200_OK- assert r.data["request_count"] == 0- assert r.data["total_tokens"] == 0- assert r.data["cost"] is None- assert r.data["cost_is_estimate"] is False---def test_model_activity_endpoint_returns_points():- u = make_user()- p = make_project()- make_member(u, p)- m = _deployed_model(p)- InferenceCall.objects.create(deployed_model=m, project=p, prompt_tokens=7, completion_tokens=3)-- r = auth_client(u).get(reverse("deployedmodel-activity", args=[str(m.id)]))- assert r.status_code == status.HTTP_200_OK- points = r.data["points"]- assert len(points) == 1- assert points[0]["request_count"] == 1- assert points[0]["total_tokens"] == 10--[email protected]("measured-facts")def test_metrics_separate_failures_end_to_end_and_warm_engine_latency():user, project = make_user(), make_project()make_member(user, project)@@ -531,40 +248,3 @@ def test_metrics_separate_failures_end_to_end_and_warm_engine_latency():assert response.data["avg_latency_ms"] == 10assert response.data["end_to_end_p50_ms"] == 300assert response.data["latest_failure"]["id"] == str(failed.pk)--[email protected]("field", ["avg_latency_ms", "avg_tokens_per_second"])-def test_deployed_models_sort_by_displayed_median_before_pagination(field):- user, project = make_user(), make_project()- make_member(user, project)- slow_mean = _deployed_model(project, _job(project))- fast_mean = _deployed_model(project, _job(project))- unmeasured = _deployed_model(project, _job(project))- for model, values in [(slow_mean, [10, 20, 3000]), (fast_mean, [30, 40, 50])]:- for value in values:- InferenceCall.objects.create(- deployed_model=model,- project=project,- latency_ms=value,- tokens_per_second=value,- is_cold=False,- outcome="succeeded",- )- for prefix, expected, median in [("", slow_mean, 20), ("-", fast_mean, 40)]:- response = auth_client(user).get(- reverse("deployedmodel-list"),- {- "project": project.id,- "ordering": prefix + field,- "page_size": 1,- },- )- assert response.status_code == 200, response.data- assert response.data["count"] == 3- assert response.data["results"][0]["id"] == str(expected.id)- assert response.data["results"][0][field] == median- last = auth_client(user).get(- reverse("deployedmodel-list"),- {"project": project.id, "ordering": prefix + field, "page_size": 1, "page": 3},- )- assert last.data["results"][0]["id"] == str(unmeasured.id)diff --git a/tests/test_inference_gpu_floor.py b/tests/test_inference_gpu_floor.pyindex 98e03b77..f0c8d646 100644--- a/tests/test_inference_gpu_floor.py+++ b/tests/test_inference_gpu_floor.py@@ -3,6 +3,8 @@ import pytestfrom overbae.modal.gpu_selector import select_gpufrom overbae.modal.model_registry import get_model_config_any_backend+pytestmark = pytest.mark.covers("model-runtime")+@pytest.mark.parametrize("model_id", ["google/gemma-4-E2B-it", "google/gemma-4-E4B-it"])@pytest.mark.parametrize("context", [512, 4096, 8192, 131072])diff --git a/tests/test_inference_live.py b/tests/test_inference_live.pyindex 9911859f..106a8a0d 100644--- a/tests/test_inference_live.py+++ b/tests/test_inference_live.py@@ -6,6 +6,8 @@ import pytestfrom overbae.models import DeployedModelfrom overbae.services import inference_live+pytestmark = pytest.mark.covers("measured-facts")+@pytest.fixturedef worker_status(monkeypatch):diff --git a/tests/test_inference_metric_accuracy.py b/tests/test_inference_metric_accuracy.pyindex a9301daa..e171aa22 100644--- a/tests/test_inference_metric_accuracy.py+++ b/tests/test_inference_metric_accuracy.py@@ -13,7 +13,7 @@ from overbae.models import Projectfrom overbae.models.inference import DeployedModel, InferenceCallfrom overbae.services.deployed_chat import record_inference_call-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("measured-facts")]def _model() -> DeployedModel:diff --git a/tests/test_inference_receipts.py b/tests/test_inference_receipts.pyindex 0f055020..a53fb73a 100644--- a/tests/test_inference_receipts.py+++ b/tests/test_inference_receipts.py@@ -10,7 +10,7 @@ from overbae.models import APIToken, DeployedModel, InferenceCall, Project, Projfrom overbae.services import inference_requestsfrom overbae.services.mcp.server import create_mcp_application-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("work-once")]def test_disconnect_reconnect_reuses_inference_and_rejects_changed_payload(monkeypatch, settings):diff --git a/tests/test_inference_routing.py b/tests/test_inference_routing.pyindex e3ed7d38..3a8904e5 100644--- a/tests/test_inference_routing.py+++ b/tests/test_inference_routing.py@@ -19,7 +19,7 @@ from overbae.models import FinetuningJobfrom overbae.models.inference import DeployedModelfrom overbae.services.inference_client import InferenceClient-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("llm-gateway")]def test_routing_headers_roundtrip():diff --git a/tests/test_innermind_migration.py b/tests/test_innermind_migration.pydeleted file mode 100644index f45bc5a2..00000000--- a/tests/test_innermind_migration.py+++ /dev/null@@ -1,216 +0,0 @@-import uuid--import psycopg2-import pytest-from django.db import connections-from django.db.backends.postgresql.base import DatabaseWrapper-from django.db.migrations.executor import MigrationExecutor-from django.test import override_settings--BASE = ("overbae", "0015_workshop_execution_clock")-TARGET = ("overbae", "0016_innermind")---def scratch_database():- settings = connections["default"].settings_dict- name = f"migration_{uuid.uuid4().hex[:12]}"- admin = psycopg2.connect(- dbname="postgres",- user=settings["USER"],- password=settings["PASSWORD"],- host=settings["HOST"],- port=settings["PORT"],- )- admin.autocommit = True- admin.cursor().execute(f'CREATE DATABASE "{name}"')- try:- yield name- finally:- admin.cursor().execute(f'DROP DATABASE IF EXISTS "{name}" WITH (FORCE)')- admin.close()---def test_evaluators_sets_and_variant_runs_become_matrix_rows_sets_and_grouped_runs(- scratch_database, django_db_blocker-):- original = connections["default"]- database = DatabaseWrapper(- {**original.settings_dict, "NAME": scratch_database}, alias="default"- )- with django_db_blocker.unblock(), override_settings(MIGRATION_MODULES={}):- connections["default"] = database- try:- executor = MigrationExecutor(database)- executor.migrate([BASE])- old = executor.loader.project_state([BASE]).apps- project = old.get_model("overbae", "Project").objects.create(name="Migration")- capability = old.get_model("overbae", "Capability").objects.create(- project=project, name="Answer", slug="answer"- )- evaluator = old.get_model("overbae", "Evaluator")- judge = evaluator.objects.create(- project=project,- capability=capability,- name="resolves",- kind="llm_judge",- rubric_md="The reply confirms the refund.",- )- check = evaluator.objects.create(- project=project,- capability=capability,- name="mentions-order",- kind="deterministic",- config={"check": "contains", "reference": "order"},- )- eval_set = old.get_model("overbae", "EvalSet").objects.create(- project=project, capability=capability, name="Tickets"- )- member = old.get_model("overbae", "EvalSetMember")- member.objects.create(eval_set=eval_set, evaluator=judge, order=0)- member.objects.create(eval_set=eval_set, evaluator=check, order=1)- dataset = old.get_model("overbae", "Dataset").objects.create(- project=project, name="Evaluation", intent="eval"- )- run = old.get_model("overbae", "EvalRun").objects.create(- project=project, dataset=dataset, eval_set=eval_set, name="Backtest"- )- variant = old.get_model("overbae", "EvalVariant")- baseline = variant.objects.create(- run=run, label="recorded", mode="recorded", is_baseline=True, order=0- )- candidate = variant.objects.create(- run=run, label="candidate", mode="generate", model_name="fake/model", order=1- )- run.summary = {- "variants": {- str(baseline.id): {"n": 3, "metrics": {"resolves": {"mean": 0.5, "n": 3}}},- str(candidate.id): {"n": 3, "metrics": {"resolves": {"mean": 0.9, "n": 3}}},- }- }- run.save(update_fields=["summary"])- run_evaluator = old.get_model("overbae", "RunEvaluator")- run_evaluator.objects.create(- run=run,- evaluator=judge,- snapshot={- "name": "resolves",- "kind": "llm_judge",- "rubric_md": "The frozen rule confirms the refund amount.",- },- order=0,- )- run_evaluator.objects.create(run=run, evaluator=check, order=1)- run_evaluator.objects.create(- run=run,- evaluator=None,- snapshot={- "name": "deleted-check",- "kind": "deterministic",- "config": {"check": "contains", "reference": "refund"},- },- order=2,- )-- executor.loader.build_graph()- executor.migrate([TARGET])- new = executor.loader.project_state([TARGET]).apps-- rows = {- row.name: row- for row in new.get_model("overbae", "EvalMatrix").objects.filter(- project_id=project.id- )- }- assert {name: row.type for name, row in rows.items()} == {- "resolves": "llm",- "mentions-order": "deterministic",- }- assert rows["resolves"].source == "The reply confirms the refund."- assert "'order' in output" in rows["mentions-order"].source.replace("needle", "'order'")- migrated_set = new.get_model("overbae", "EvalSet").objects.get(pk=eval_set.pk)- assert set(migrated_set.rows.values_list("name", flat=True)) == set(rows)-- runs = {- r.model_name or "recorded": r- for r in new.get_model("overbae", "EvalRun").objects.filter(project_id=project.id)- }- assert set(runs) == {"recorded", "fake/model"}- assert runs["recorded"].pk == run.pk- assert runs["recorded"].group == runs["fake/model"].group- assert runs["recorded"].is_baseline and not runs["fake/model"].is_baseline- for migrated_run in runs.values():- matrix = {row["name"]: row for row in migrated_run.matrix}- assert list(matrix) == ["resolves", "mentions-order", "deleted-check"]- assert matrix["resolves"]["source"] == "The frozen rule confirms the refund amount."- assert matrix["deleted-check"]["type"] == "deterministic"- assert "needle = 'refund'" in matrix["deleted-check"]["source"]- assert runs["recorded"].summary["score"] == 0.5- assert runs["fake/model"].summary["score"] == 0.9- finally:- connections["default"] = original- database.close()--[email protected]("start", ["0016_innermind", "0042_trainingplan"])-def test_joined_history_upgrades_from_either_branch(start, scratch_database, django_db_blocker):- original = connections["default"]- database = DatabaseWrapper(- {**original.settings_dict, "NAME": scratch_database}, alias="default"- )- target = ("overbae", "0043_innermind_training")- with django_db_blocker.unblock(), override_settings(MIGRATION_MODULES={}):- connections["default"] = database- try:- executor = MigrationExecutor(database)- executor.migrate([("overbae", start)])- old = executor.loader.project_state([("overbae", start)]).apps- project = old.get_model("overbae", "Project").objects.create(name="Preserved")- dataset = old.get_model("overbae", "Dataset").objects.create(- project=project, name="Source"- )- cell = old.get_model("overbae", "Cell").objects.create(dataset=dataset, position=0)- if start == "0016_innermind":- saved = old.get_model("overbae", "EvalMatrix").objects.create(- project=project, name="Quality", type="llm", source="A useful answer."- )- else:- user = old.get_model("overbae", "User").objects.create(- email="[email protected]", clerk_user_id="migration"- )- saved = old.get_model("overbae", "TrainingPlan").objects.create(- project=project,- source_cell=cell,- created_by=user,- name="Plan",- request_key="join",- request_fingerprint="request",- design_identity="design",- state="draft",- specification={"preserve": True},- )- executor.loader.build_graph()- executor.migrate([target])- new = executor.loader.project_state([target]).apps- assert (- new.get_model("overbae", "Project").objects.get(pk=project.pk).name == "Preserved"- )- assert new.get_model("overbae", "Cell").objects.filter(pk=cell.pk).exists()- assert new.get_model("overbae", "EvalMatrix").objects.count() == (- start == "0016_innermind"- )- assert new.get_model("overbae", "TrainingPlan").objects.count() == (- start == "0042_trainingplan"- )- if start == "0042_trainingplan":- assert new.get_model("overbae", "TrainingPlan").objects.get(- pk=saved.pk- ).specification == {"preserve": True}- else:- assert (- new.get_model("overbae", "EvalMatrix").objects.get(pk=saved.pk).source- == "A useful answer."- )- finally:- connections["default"] = original- database.close()diff --git a/tests/test_judge_funnel.py b/tests/test_judge_funnel.pyindex 4d478b25..8e525a62 100644--- a/tests/test_judge_funnel.py+++ b/tests/test_judge_funnel.py@@ -4,6 +4,8 @@ from pydantic import BaseModelfrom overbae.services.judging import funnelfrom overbae.services.judging.funnel import ResolvedJudge, parse_structured, sanitize_raw+pytestmark = pytest.mark.covers("metrics-math")+class _Verdict(BaseModel):explanation: strdiff --git a/tests/test_landing_admission.py b/tests/test_landing_admission.pyindex 52a0d18f..b484d508 100644--- a/tests/test_landing_admission.py+++ b/tests/test_landing_admission.py@@ -10,7 +10,7 @@ from overbae.services.datasets import admissionfrom overbae.services.datasets.lifecycle import DatasetErrorfrom overbae.tasks.datasets import land-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("capacity")]def queue(project):diff --git a/tests/test_langfuse_adapter.py b/tests/test_langfuse_adapter.pyindex 7c20517a..4ef8d422 100644--- a/tests/test_langfuse_adapter.py+++ b/tests/test_langfuse_adapter.py@@ -6,7 +6,7 @@ from factories import make_connectorfrom overbae.services.connectors.langfuse.adapter import LangfuseAdapter-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("vendor-connectors")]_START = datetime(2026, 8, 19, 12, 0, tzinfo=UTC)diff --git a/tests/test_langfuse_capabilities.py b/tests/test_langfuse_capabilities.pyindex 8828903e..960f8e7c 100644--- a/tests/test_langfuse_capabilities.py+++ b/tests/test_langfuse_capabilities.py@@ -1,8 +1,12 @@"""Per-subtree capability-key assignment for Langfuse observation trees."""+import pytest+from overbae.services.connectors.capabilities import assign_capability_keys, extract_signal_valuefrom overbae.services.connectors.langfuse.client import LangFuseObservation+pytestmark = pytest.mark.covers("vendor-connectors")+def _obs(**kwargs) -> LangFuseObservation:defaults = {diff --git a/tests/test_langfuse_capability_traces.py b/tests/test_langfuse_capability_traces.pyindex 53aae754..2f327453 100644--- a/tests/test_langfuse_capability_traces.py+++ b/tests/test_langfuse_capability_traces.py@@ -1,5 +1,6 @@from types import SimpleNamespace+import pytestfrom fakes.ledgerline import (langchain_style_trace,observation,@@ -13,6 +14,8 @@ from overbae.services.connectors.mapping import observations_to_span_dicts as _tfrom overbae.services.connectors.schema import CONNECTOR_CAPABILITY_KEY_ATTRfrom overbae.services.connectors.spans import span_id_for, trace_id_for+pytestmark = pytest.mark.covers("vendor-connectors")+# The fixture's capabilities, named the way the wizard now marks them._CAPABILITY_NAMES = ["scan-inbox", "triage-invoices", "plan-payments", "triage-email"]diff --git a/tests/test_langfuse_client.py b/tests/test_langfuse_client.pyindex 4e1771e7..8cb8d097 100644--- a/tests/test_langfuse_client.py+++ b/tests/test_langfuse_client.py@@ -5,6 +5,8 @@ import pytestfrom overbae.services.connectors.langfuse.client import LangFuseClient, LangFuseErrorfrom overbae.services.connectors.windows import TimeWindow, plan_windows+pytestmark = pytest.mark.covers("vendor-connectors")+_WINDOW = TimeWindow(start=datetime(2026, 1, 1, tzinfo=UTC), end=datetime(2026, 1, 2, tzinfo=UTC))diff --git a/tests/test_langfuse_mapping.py b/tests/test_langfuse_mapping.pyindex 3d44e9ad..ceb3cdf1 100644--- a/tests/test_langfuse_mapping.py+++ b/tests/test_langfuse_mapping.py@@ -10,6 +10,8 @@ from overbae.services.connectors.schema import ()from overbae.services.connectors.spans import span_id_for+pytestmark = pytest.mark.covers("vendor-connectors")+def _cred(**fields):return make_connector("langfuse", **fields)diff --git a/tests/test_langsmith_adapter.py b/tests/test_langsmith_adapter.pyindex c8b83e55..a1a8df68 100644--- a/tests/test_langsmith_adapter.py+++ b/tests/test_langsmith_adapter.py@@ -49,7 +49,7 @@ def _start(call) -> datetime:return datetime.fromisoformat(call.json["start_time"].replace("Z", "+00:00"))-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("vendor-connectors")]def test_discovery_stays_in_the_cheap_six_day_tier_even_when_the_wizard_asks_for_thirty(api):diff --git a/tests/test_langsmith_client.py b/tests/test_langsmith_client.pyindex 006e5920..2a5f64f0 100644--- a/tests/test_langsmith_client.py+++ b/tests/test_langsmith_client.py@@ -8,6 +8,8 @@ from overbae.services.connectors.langsmith.client import (validate_project_id,)+pytestmark = pytest.mark.covers("vendor-connectors")+_PROJECT = "11111111-1111-1111-1111-111111111111"_MIN = datetime(2026, 1, 2, tzinfo=UTC)diff --git a/tests/test_langsmith_mapping.py b/tests/test_langsmith_mapping.pyindex 042a9a58..dda3cf3b 100644--- a/tests/test_langsmith_mapping.py+++ b/tests/test_langsmith_mapping.py@@ -16,6 +16,8 @@ from overbae.services.connectors.schema import ()from overbae.services.connectors.spans import span_id_for+pytestmark = pytest.mark.covers("vendor-connectors")+_ROOT = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa1"_CHILD = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa2"_TRACE = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa0"diff --git a/tests/test_legacy_eval_migration.py b/tests/test_legacy_eval_migration.pydeleted file mode 100644index b91ea956..00000000--- a/tests/test_legacy_eval_migration.py+++ /dev/null@@ -1,136 +0,0 @@-from importlib import import_module-from types import SimpleNamespace--from test_innermind_migration import scratch_database as scratch_database--migration = import_module("overbae.migrations.0016_innermind")---def test_legacy_sample_preserves_generated_output_and_evidence():- sample = SimpleNamespace(- pk="sample-1",- variant_id="variant-1",- row_index=7,- source_trace_id="trace-1",- trajectory={"final_output": "answer", "metadata": {"model": "old-model"}},- structured={"turns": []},- expected={"answer": "reference"},- context_coverage=0.75,- error="",- degraded=False,- degraded_reason="",- celery_task_id="task-1",- )-- row = migration.legacy_sample_values(sample)-- assert row["output"] == "answer"- assert row["metadata"]["model"] == "old-model"- assert row["metadata"]["legacy_sample"]["expected"] == {"answer": "reference"}- assert row["metadata"]["legacy_sample"]["structured"] == {"turns": []}- assert row["source_trace_id"] == "trace-1"---def test_legacy_scores_keep_outcomes_and_checklist_evidence():- scores = [- SimpleNamespace(- name="Task Success",- outcome="scored",- value=0.8,- passed=True,- reasoning="Mostly correct",- scope="final_output",- sub_scores=[{"id": "check-1", "verdict": True}],- ),- SimpleNamespace(- name="Evidence",- outcome="error",- value=None,- passed=None,- reasoning="Judge unavailable",- scope="final_output",- sub_scores=[],- ),- ]-- value, metrics = migration.legacy_score_values(scores)-- assert value == 0.8- assert metrics["Task Success"]["score"] == 0.8- assert metrics["Task Success"]["sub_scores"] == scores[0].sub_scores- assert metrics["Evidence"]["error"] == "Judge unavailable"- assert metrics["Evidence"]["score"] is None---def test_cutover_preserves_variants_and_samples_without_dataset_indices(- scratch_database, django_db_blocker-):- from django.db import connections- from django.db.backends.postgresql.base import DatabaseWrapper- from django.db.migrations.executor import MigrationExecutor- from django.test import override_settings-- original = connections["default"]- database = DatabaseWrapper(- {**original.settings_dict, "NAME": scratch_database}, alias="default"- )- with django_db_blocker.unblock(), override_settings(MIGRATION_MODULES={}):- connections["default"] = database- try:- executor = MigrationExecutor(database)- before = [("overbae", "0015_workshop_execution_clock")]- executor.migrate(before)- old = executor.loader.project_state(before).apps- project = old.get_model("overbae", "Project").objects.create(- name="Migration", slug="migration"- )- run = old.get_model("overbae", "EvalRun").objects.create(- project=project, name="Legacy", status="completed"- )- variants = [- old.get_model("overbae", "EvalVariant").objects.create(- run=run, label=label, order=i- )- for i, label in enumerate(["Baseline", "Candidate"])- ]- for variant in variants:- for i, index in enumerate([0, 0, None]):- sample = old.get_model("overbae", "EvalSample").objects.create(- run=run,- variant=variant,- row_index=index,- trajectory={"final_output": f"{variant.label}-{i}"},- )- old.get_model("overbae", "Score").objects.create(- project=project,- run=run,- variant=variant,- sample=sample,- name="Correct",- outcome="scored",- value=0.8,- )- executor = MigrationExecutor(database)- target = [("overbae", "0016_innermind")]- executor.migrate(target)- current = executor.loader.project_state(target).apps- runs = current.get_model("overbae", "EvalRun").objects.all()- assert runs.count() == 2- for migrated_run in runs:- rows = list(- current.get_model("overbae", "EvalRunRow").objects.filter(run=migrated_run)- )- assert len(rows) == 3- assert len({row.row_index for row in rows}) == 3- assert {row.output for row in rows} == {- f"{migrated_run.params['label']}-{i}" for i in range(3)- }- assert [row.metadata["legacy_sample"]["row_index"] for row in rows] == [0, 0, None]- scores = current.get_model("overbae", "EvalScore").objects.filter(run=migrated_run)- assert set(scores.values_list("source_id", flat=True)) == {- f"None:{row.row_index}" for row in rows- }- assert migrated_run.summary["rows"] == 3- finally:- database.close()- connections["default"] = originaldiff --git a/tests/test_live_scoring_admission.py b/tests/test_live_scoring_admission.pyindex 41e2dde1..b9ded65e 100644--- a/tests/test_live_scoring_admission.py+++ b/tests/test_live_scoring_admission.py@@ -9,7 +9,7 @@ from django.utils import timezonefrom overbae.innermind import admissionfrom overbae.models import LiveScoringWork, Project-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("capacity")]def project():diff --git a/tests/test_llm_and_modal_billing.py b/tests/test_llm_and_modal_billing.pyindex b11ceb14..71bc437e 100644--- a/tests/test_llm_and_modal_billing.py+++ b/tests/test_llm_and_modal_billing.py@@ -15,7 +15,7 @@ from overbae.services.billing_ledger import balance_usd, charge_llm_usagefrom overbae.services.finetuning_runner import PollSnapshotfrom overbae.tasks.finetuning import _transition, observe_finetuning_job-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]User = get_user_model()diff --git a/tests/test_llm_call_datasets.py b/tests/test_llm_call_datasets.pyindex 29baad2e..39167e51 100644--- a/tests/test_llm_call_datasets.py+++ b/tests/test_llm_call_datasets.py@@ -18,7 +18,7 @@ from overbae.services.datasets.land import LandErrorfrom overbae.services.datasets.llm_calls import call_record, hash_split, shapefrom overbae.services.finetuning_validator import validate_rows-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("data-logic")]_TOOLS = [{diff --git a/tests/test_llm_deadlines.py b/tests/test_llm_deadlines.pyindex b1f7de75..e3c32afd 100644--- a/tests/test_llm_deadlines.py+++ b/tests/test_llm_deadlines.py@@ -9,6 +9,8 @@ import pytestfrom overbae.core.llms import ModelSpec, call_llm+pytestmark = pytest.mark.covers("llm-gateway")+@pytest.fixturedef heartbeat_provider():diff --git a/tests/test_llm_request_shape.py b/tests/test_llm_request_shape.pyindex 027553ef..dee15413 100644--- a/tests/test_llm_request_shape.py+++ b/tests/test_llm_request_shape.py@@ -6,6 +6,8 @@ from pydantic import BaseModelfrom overbae.core.llms import call_llm, call_llm_tools+pytestmark = pytest.mark.covers("llm-gateway")+class _Answer(BaseModel):answer: strdiff --git a/tests/test_llms.py b/tests/test_llms.pyindex 6ee53729..5c8ab34d 100644--- a/tests/test_llms.py+++ b/tests/test_llms.py@@ -10,6 +10,8 @@ from overbae.core.llms import ()from overbae.core.model_registry import CATALOG, MODELS_BY_NAME, reasoning_of+pytestmark = pytest.mark.covers("llm-gateway")+def test_reasoning_metadata_reads_from_the_registry():assert reasoning_of("gpt-5-mini").adaptive is Truediff --git a/tests/test_local_auth.py b/tests/test_local_auth.pyindex 03520522..7813674a 100644--- a/tests/test_local_auth.py+++ b/tests/test_local_auth.py@@ -18,7 +18,7 @@ from overbae.models import (User,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("authentication")]@pytest.fixture(autouse=True)diff --git a/tests/test_mcp_account_access.py b/tests/test_mcp_account_access.pyindex 9d7c2549..f90d6478 100644--- a/tests/test_mcp_account_access.py+++ b/tests/test_mcp_account_access.py@@ -4,12 +4,13 @@ import jsonimport uuidimport pytest+from mcp_fixtures import asgi_dbfrom starlette.testclient import TestClientfrom overbae.models import APIToken, Project, ProjectMembership, Userfrom overbae.services.mcp.server import create_mcp_application-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("tenancy")]def account():@@ -34,6 +35,7 @@ def rpc(client, raw, method, params=None):).json()+@asgi_dbdef test_account_discovers_projects_and_reads_each_without_shared_selection():_, projects, raw = account()with TestClient(create_mcp_application()) as client:@@ -55,6 +57,7 @@ def test_account_discovers_projects_and_reads_each_without_shared_selection():assert missing["structuredContent"]["error"]["code"] == "project_required"+@asgi_dbdef test_explicit_project_is_enforced_for_tools_resources_and_membership_revocation():user, projects, raw = account()with TestClient(create_mcp_application()) as client:@@ -93,6 +96,7 @@ def test_explicit_project_is_enforced_for_tools_resources_and_membership_revocatassert "error" in resource+@asgi_dbdef test_project_key_cannot_expand_access_to_another_membership():user, projects, _ = account()raw, _ = APIToken.create_for_user(user, project=projects[0])@@ -115,6 +119,7 @@ def test_project_key_cannot_expand_access_to_another_membership():assert not result.get("isError")+@asgi_dbdef test_account_read_key_cannot_call_write_tools():user, projects, _ = account()raw, _ = APIToken.create_for_user(user, permission=["read"])diff --git a/tests/test_mcp_analytics.py b/tests/test_mcp_analytics.pyindex a954884b..d3165603 100644--- a/tests/test_mcp_analytics.py+++ b/tests/test_mcp_analytics.py@@ -8,6 +8,7 @@ from http.server import BaseHTTPRequestHandler, HTTPServerimport pytestfrom mcp.server.lowlevel import Server+from mcp_fixtures import asgi_dbfrom posthog import Posthogfrom posthog.mcp import instrumentfrom starlette.testclient import TestClient@@ -15,7 +16,7 @@ from starlette.testclient import TestClientfrom overbae.models import APIToken, Project, ProjectMembership, Userfrom overbae.services.mcp import server-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("privacy")]MCP_URL = "/api/mcp/"INJECTED_ARGUMENTS = {"context", "conversation_id", "llm_model"}@@ -87,6 +88,7 @@ def _rpc(client, headers, method, params=None, request_id=1):return response+@asgi_dbdef test_every_tool_call_reaches_posthog_as_metadata_only(instrumented):user, project, headers = _member(project_key=False)expected = {}@@ -160,6 +162,7 @@ def test_every_tool_call_reaches_posthog_as_metadata_only(instrumented):assert events["$mcp_resource_read"]["properties"]["project_id"] == str(project.id)+@asgi_dbdef test_project_key_events_carry_the_key_project(instrumented):_, project, headers = _member(project_key=True)@@ -170,6 +173,7 @@ def test_project_key_events_carry_the_key_project(instrumented):assert event["properties"]["project_id"] == str(project.id)+@asgi_dbdef test_failed_ingest_does_not_fail_tool_calls(instrumented):instrumented.status = 500_, _, headers = _member(project_key=True)diff --git a/tests/test_mcp_api_keys.py b/tests/test_mcp_api_keys.pyindex 75edc36f..b57aeed0 100644--- a/tests/test_mcp_api_keys.py+++ b/tests/test_mcp_api_keys.py@@ -4,20 +4,19 @@ choices, and a plaintext secret that is stored or returned twice."""from __future__ import annotations-import asyncioimport jsonfrom datetime import timedeltaimport pytestfrom factories import make_project, make_user+from mcp_fixtures import call_toolfrom overbae.models import APITokenfrom overbae.models.iam import API_KEY_EXPIRY_DAYS-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContextfrom overbae.services.mcp.contracts.projects import CreateApiKeyInput-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("authentication")]def _context(*, account=False, permission=("read", "write"), guest=False):@@ -34,7 +33,7 @@ def _context(*, account=False, permission=("read", "write"), guest=False):def _call(context, **arguments):- return asyncio.run(CATALOG.call("create_api_key", arguments, context))+ return call_tool("create_api_key", arguments, context)def test_expiry_choices_match_the_console_dialog():diff --git a/tests/test_mcp_authorization.py b/tests/test_mcp_authorization.pyindex 2b5f2076..2006271a 100644--- a/tests/test_mcp_authorization.py+++ b/tests/test_mcp_authorization.py@@ -5,12 +5,13 @@ from datetime import timedeltaimport pytestfrom django.utils import timezone+from mcp_fixtures import asgi_dbfrom starlette.testclient import TestClientfrom overbae.models import APIToken, Project, ProjectMembership, Userfrom overbae.services.mcp.server import create_mcp_application-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("authentication")]MCP_URL = "/api/mcp/"@@ -51,12 +52,14 @@ def _call(raw_key: str, headers: dict[str, str] | None = None):)+@asgi_dbdef test_requires_api_key_and_rejects_jwt():response = _call("not-a-key")assert response.status_code == 401assert response.json()["error"]["code"] == "authentication_failed"+@asgi_dbdef test_unconfigured_oauth_does_not_advertise_a_bearer_challenge(settings):settings.MCP_SERVER_URL = ""with TestClient(create_mcp_application()) as client:@@ -75,6 +78,7 @@ def test_unconfigured_oauth_does_not_advertise_a_bearer_challenge(settings):assert "bearer" not in response.headers.get("www-authenticate", "").casefold()+@asgi_dbdef test_rejects_account_scope_with_project_binding():raw, _ = _token(scope={"scope": "account", "permission": ["read", "write"]})response = _call(raw)@@ -82,6 +86,7 @@ def test_rejects_account_scope_with_project_binding():assert response.json()["error"]["code"] == "project_required"+@asgi_dbdef test_rejects_inactive_and_expired_keys():raw, token = _token()token.is_active = False@@ -98,6 +103,7 @@ def test_rejects_inactive_and_expired_keys():assert expired.json()["error"]["code"] == "authentication_failed"+@asgi_dbdef test_enforces_allowed_ips():raw, _ = _token(allowed_ips=["203.0.113.10"])response = _call(raw)@@ -105,6 +111,7 @@ def test_enforces_allowed_ips():assert response.json()["error"]["code"] == "authentication_failed"+@asgi_dbdef test_rejects_unknown_permissions():raw, token = _token()token.scope = {@@ -119,6 +126,7 @@ def test_rejects_unknown_permissions():assert response.json()["error"]["code"] == "permission_denied"+@asgi_dbdef test_accepts_bearer_api_key():raw, _ = _token()response = _call(raw, {"Authorization": f"Bearer {raw}"})diff --git a/tests/test_mcp_billing.py b/tests/test_mcp_billing.pyindex c31ce8d6..82942a62 100644--- a/tests/test_mcp_billing.py+++ b/tests/test_mcp_billing.py@@ -3,6 +3,7 @@ from decimal import Decimalimport pytestfrom django.utils import timezone+from mcp_fixtures import asgi_dbfrom starlette.testclient import TestClientfrom test_mcp_account_access import account, rpc@@ -10,7 +11,7 @@ from overbae.models import APIToken, BillingService, BillingTelemetryfrom overbae.services.billing_ledger import append_entryfrom overbae.services.mcp.server import create_mcp_application-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [asgi_db, pytest.mark.covers("ledger")]def report(client, key, **arguments):diff --git a/tests/test_mcp_catalog.py b/tests/test_mcp_catalog.pyindex a8e0c2bf..18a6e8a1 100644--- a/tests/test_mcp_catalog.py+++ b/tests/test_mcp_catalog.py@@ -9,6 +9,8 @@ from overbae.models import APIToken, Project, Userfrom overbae.services.mcp.catalog import CatalogError, ToolCatalog, ToolDefinitionfrom overbae.services.mcp.context import MCPContext+pytestmark = pytest.mark.covers("mcp-surface")+class ReadInput(BaseModel):query: strdiff --git a/tests/test_mcp_connector_job_poll.py b/tests/test_mcp_connector_job_poll.pyindex 7e15b470..3bfd0209 100644--- a/tests/test_mcp_connector_job_poll.py+++ b/tests/test_mcp_connector_job_poll.py@@ -1,28 +1,20 @@from __future__ import annotations-import asyncioimport jsonimport uuidimport pytestfrom django.utils import timezone-from mcp_fixtures import mcp_context+from mcp_fixtures import call_tool, mcp_contextfrom overbae.models import ConnectorCredential, Project-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]def _call(context: MCPContext, connector_id: str):- return asyncio.run(- CATALOG.call(- "get_job",- {"kind": "connector_sync", "id": connector_id},- context,- )- )+ return call_tool("get_job", {"kind": "connector_sync", "id": connector_id}, context)def test_connector_sync_get_job_uses_connector_receipt_id_and_resource():diff --git a/tests/test_mcp_connectors.py b/tests/test_mcp_connectors.pyindex d6b1c674..400ceca7 100644--- a/tests/test_mcp_connectors.py+++ b/tests/test_mcp_connectors.py@@ -1,14 +1,14 @@from __future__ import annotations-import asyncioimport jsonimport uuidfrom datetime import timedeltaimport pytest+from asgiref.sync import async_to_syncfrom django.utils import timezonefrom fakes.vendors import LangfuseAPI, Step-from mcp_fixtures import mcp_context+from mcp_fixtures import call_tool, mcp_contextfrom rest_framework.test import APIClientfrom overbae.models import (@@ -24,13 +24,12 @@ from overbae.services.connectors.schema import CONNECTOR_CREDENTIAL_ID_ATTRfrom overbae.services.connectors.sync import (boundary_import_key,prepare_connector_sync,- reset_connector_import,)from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext, bind_contextfrom overbae.services.mcp.resources import read_resource, resource_templates-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("vendor-connectors")]@pytest.fixture(autouse=True)@@ -41,7 +40,7 @@ def langfuse(fake_llm) -> LangfuseAPI:def _call(name: str, arguments: dict, context: MCPContext):- return asyncio.run(CATALOG.call(name, arguments, context))+ return call_tool(name, arguments, context)def _connector(@@ -67,6 +66,7 @@ def _connector(return connector[email protected]("privacy")def test_catalog_has_three_connector_tools_without_secret_schema_fields():names = {definition.name for definition in CATALOG.definitions()}connector_names = {name for name in names if "connector" in name}@@ -126,10 +126,6 @@ def _nested_agent(langfuse: LangfuseAPI) -> None:_record(langfuse, "run_ledgerline", "adjudicate_claim", "adjudicate_tool_loop", "get_fx_rate")-def _inbox(langfuse: LangfuseAPI) -> None:- _record(langfuse, "run_ledgerline", "run_invoice_agent", "analyze_email")--def test_inspect_without_configured_connectors_returns_cli_action():context = mcp_context()@@ -151,6 +147,7 @@ def test_inspect_without_configured_connectors_returns_cli_action():_assert_available_types(result.structuredContent)[email protected]("authentication")def test_read_only_key_hides_and_denies_connector_writes():context = mcp_context()connector = _connector(context)@@ -164,6 +161,7 @@ def test_read_only_key_hides_and_denies_connector_writes():assert result.structuredContent["error"]["code"] == "permission_denied"[email protected]("tenancy")def test_connector_lookup_is_project_scoped():context = mcp_context(permission=["read", "write"])other = Project.objects.create(name="Other", slug=f"other-{uuid.uuid4().hex[:8]}")@@ -263,23 +261,7 @@ def test_configure_uses_existing_capabilities_and_rejects_unknown_targets():assert auto_create.structuredContent["error"]["code"] == "invalid_input"-def test_sync_uses_neutral_dispatcher_and_returns_poll_resource(queued):- context = mcp_context(permission=["read", "write"])- connector = _connector(context)-- result = _call("sync_connector", {"connector": str(connector.id)}, context)-- assert result.isError is False- assert queued == [str(connector.id)]- connector.refresh_from_db()- assert connector.sync_status == ConnectorCredential.SyncStatus.BACKFILLING- assert result.structuredContent["queued"] is True- assert result.structuredContent["job"]["kind"] == "connector_sync"- assert result.structuredContent["poll_hint"]["resource"]["uri"] == (- f"overmind://connectors/{connector.id}"- )--[email protected]("privacy")def test_provider_exceptions_are_redacted(langfuse):context = mcp_context(permission=["read", "write"])connector = _connector(context)@@ -304,6 +286,7 @@ def test_provider_exceptions_are_redacted(langfuse):assert "provider-secret" not in encoded[email protected]("privacy")def test_connector_resource_is_project_scoped_and_secret_free():context = mcp_context()connector = _connector(context)@@ -319,7 +302,7 @@ def test_connector_resource_is_project_scoped_and_secret_free():contents = list(await read_resource(f"overmind://connectors/{connector.id}"))return json.loads(contents[0].content)- resource = asyncio.run(read())+ resource = async_to_sync(read)()encoded = json.dumps(resource)assert resource["kind"] == "connector"assert resource["sync_runs"][0]["has_error"] is True@@ -354,25 +337,6 @@ def test_list_shows_keyed_drafts_and_hides_keyless_wizard_rows():_assert_available_types(result.structuredContent)-def test_inspect_keyed_draft_can_request_source_projects():- context = mcp_context()- connector = _connector(context, configured=False)-- result = _call(- "inspect_connectors",- {"connector": str(connector.id), "include_source_projects": True},- context,- )- details = result.structuredContent["connector"]- action = result.structuredContent["human_action"]-- assert result.isError is False- assert details["provider_status"] == "available"- assert details["source_projects"] == [{"id": "lf-project", "name": "support-desk"}]- assert action["code"] == "connector_config_required"- assert action["action"] == "configure_connector"--def test_configure_first_config_defaults_lookback_and_leaves_auto_sync_off():context = mcp_context(permission=["read", "write"])connector = _connector(context, configured=False)@@ -394,21 +358,6 @@ def test_configure_first_config_defaults_lookback_and_leaves_auto_sync_off():assert connector.auto_sync_enabled is False-def test_configure_explicit_null_lookback_stays_unbounded():- context = mcp_context(permission=["read", "write"])- connector = _connector(context, configured=False)-- result = _call(- "configure_connector",- {"connector": str(connector.id), "lookback_days": None},- context,- )- connector.refresh_from_db()-- assert result.isError is False- assert connector.active_config().lookback_days is None--def test_sync_without_config_returns_config_required():context = mcp_context(permission=["read", "write"])connector = _connector(context, configured=False)@@ -464,37 +413,7 @@ def test_configure_and_sync_without_keys_still_require_cli():assert action["resource"] == "overmind://connector-setup"-def test_create_stamps_verified_at_on_saved_and_reconnected_row():- context = mcp_context()- raw, _ = APIToken.create_for_user(context.user, project=context.project)- client = APIClient()- client.credentials(HTTP_X_API_KEY=raw)- body = {- "project": str(context.project.id),- "name": "langfuse",- "connector_type": "langfuse",- "api_key": "pk-test",- "api_secret": "sk-test",- }-- created = client.post("/api/connector-credentials/", body, format="json")- assert created.status_code == 201, created.data- connector = ConnectorCredential.objects.get(id=created.data["id"])- assert connector.verified_at is not None- assert connector.api_version == "v2"-- connector.verified_at = None- connector.api_version = ConnectorCredential.ApiVersion.UNKNOWN- connector.save(update_fields=["verified_at", "api_version", "updated_at"])-- again = client.post("/api/connector-credentials/", body, format="json")- assert again.status_code == 201, again.data- assert again.data["id"] == str(connector.id)- connector.refresh_from_db()- assert connector.verified_at is not None- assert connector.api_version == "v2"--[email protected]("tenancy")def test_create_rejects_project_outside_api_key_scope():context = mcp_context()other = Project.objects.create(name="Other", slug=f"other-{uuid.uuid4().hex[:8]}")@@ -518,33 +437,6 @@ def test_create_rejects_project_outside_api_key_scope():assert "scoped to another project" in str(response.data)-def test_mapping_confirm_on_the_first_call_only_stages():- context = mcp_context(permission=["read", "write"])- connector = _connector(context, mapping_confirmed=False)- capability = Capability.objects.create(- project=context.project,- name="Support",- slug=f"support-{uuid.uuid4().hex[:6]}",- )-- result = _call(- "configure_connector",- {- "connector": str(connector.id),- "capability_mapping": {"assignments": {"support": str(capability.id)}},- "confirm_mapping": True,- },- context,- )- connector.refresh_from_db()-- assert result.structuredContent["mapping_pending"] is True- assert result.structuredContent["human_action"]["action"] == "approve_mapping"- assert connector.capability_mapping == {}- assert connector.capability_mapping_confirmed is False- assert connector.pending_capability_mapping["assignments"] == {"support": str(capability.id)}--def test_sync_waits_for_mapping_approval(queued):context = mcp_context(permission=["read", "write"])connector = _connector(context, mapping_confirmed=False)@@ -583,39 +475,6 @@ def test_empty_mapping_can_be_approved_then_synced(queued):assert queued == [str(connector.id)]-def test_inspect_returns_parent_only_suggested_boundaries(langfuse):- context = mcp_context()- connector = _connector(context)- capability = Capability.objects.create(- project=context.project,- name="Ledgerline Adjudicator",- slug="ledgerline-adjudicator",- entrypoint_fn="adjudicate_claim",- improvement_metadata={"tool_spec": [{"name": "get_fx_rate"}]},- )- _nested_agent(langfuse)-- result = _call(- "inspect_connectors",- {"connector": str(connector.id), "include_source_projects": True},- context,- )- suggested = result.structuredContent["suggested_boundaries"]- nested = suggested[0]["nested_names"]-- assert result.isError is False- assert [item["name"] for item in suggested] == ["adjudicate_claim"]- assert suggested[0]["capability_id"] == str(capability.id)- assert suggested[0]["alternatives"] == []- assert "get_fx_rate" in nested- assert "adjudicate_tool_loop" in nested- assert "get_fx_rate" not in [item["name"] for item in suggested]- assert "run_ledgerline" in result.structuredContent["unmapped_roots"]- assert any(- shape["name"] == "get_fx_rate" for shape in result.structuredContent["observation_shapes"]- )--def test_configure_drops_nested_names_from_the_staged_mapping(langfuse):context = mcp_context(permission=["read", "write"])connector = _connector(context, mapping_confirmed=False)@@ -718,81 +577,6 @@ def test_configure_keeps_fallback_and_does_not_store_auto_create():assert "auto_create" not in pending-def test_configure_keeps_unmapped_root_and_nested_only_boundaries(langfuse):- context = mcp_context(permission=["read", "write"])- connector = _connector(context, mapping_confirmed=False)- triage = Capability.objects.create(- project=context.project,- name="Invoice triage",- slug="invoice-triage",- entrypoint_fn="run_invoice_agent",- improvement_metadata={"modes": [{"name": "analyze_email"}]},- )- _inbox(langfuse)-- nested = _call(- "configure_connector",- {- "connector": str(connector.id),- "capability_mapping": {- "source": "observation_name",- "names": ["analyze_email"],- "assignments": {"analyze_email": str(triage.id)},- },- },- context,- )- connector.refresh_from_db()-- assert nested.isError is False- assert connector.pending_capability_mapping["names"] == ["analyze_email"]- assert nested.structuredContent["dropped_nested_names"] == []-- root = _call(- "configure_connector",- {- "connector": str(connector.id),- "capability_mapping": {- "source": "observation_name",- "names": ["run_ledgerline"],- "assignments": {"run_ledgerline": str(triage.id)},- },- },- context,- )- connector.refresh_from_db()-- assert root.isError is False- assert connector.pending_capability_mapping["names"] == ["run_ledgerline"]---def test_inspect_lists_nested_capability_matches_as_alternatives(langfuse):- context = mcp_context()- connector = _connector(context)- capability = Capability.objects.create(- project=context.project,- name="Invoice triage",- slug="invoice-triage",- entrypoint_fn="run_invoice_agent",- improvement_metadata={"modes": [{"name": "analyze_email"}]},- )- _inbox(langfuse)-- result = _call(- "inspect_connectors",- {"connector": str(connector.id), "include_source_projects": True},- context,- )- suggested = result.structuredContent["suggested_boundaries"]-- assert result.isError is False- assert [item["name"] for item in suggested] == ["run_invoice_agent"]- assert suggested[0]["capability_id"] == str(capability.id)- assert suggested[0]["alternatives"] == ["analyze_email"]- assert "analyze_email" in suggested[0]["nested_names"]- assert "run_ledgerline" in result.structuredContent["unmapped_roots"]--def test_sync_reports_recarving_when_boundary_names_changed(queued):context = mcp_context(permission=["read", "write"])connector = _connector(context)@@ -843,50 +627,3 @@ def test_prepare_connector_sync_adopts_empty_key_and_wipes_on_name_change():connector.refresh_from_db()assert connector.sync_cursor == {}assert connector.total_traces_imported == 0---def test_prepare_connector_sync_skips_wipe_when_only_assignments_change():- context = mcp_context()- connector = _connector(context)- mapping = {- "source": "observation_name",- "names": ["analyze_email"],- "assignments": {"analyze_email": str(uuid.uuid4())},- }- connector.capability_mapping = mapping- connector.imported_boundary_key = boundary_import_key(- {"source": "observation_name", "names": ["analyze_email"]}- )- connector.save(update_fields=["capability_mapping", "imported_boundary_key", "updated_at"])- Span.objects.create(- span_id="c" * 16,- trace_id="d" * 32,- project=context.project,- name="analyze_email",- resource_attrs={CONNECTOR_CREDENTIAL_ID_ATTR: str(connector.id)},- )-- assert prepare_connector_sync(connector) is False- assert Span.objects.filter(span_id="c" * 16).exists()---def test_reset_connector_import_deletes_only_that_credential_spans():- context = mcp_context()- connector = _connector(context)- other = _connector(context)- Span.objects.create(- span_id="e" * 16,- trace_id="f" * 32,- project=context.project,- resource_attrs={CONNECTOR_CREDENTIAL_ID_ATTR: str(connector.id)},- )- Span.objects.create(- span_id="g" * 16,- trace_id="h" * 32,- project=context.project,- resource_attrs={CONNECTOR_CREDENTIAL_ID_ATTR: str(other.id)},- )-- assert reset_connector_import(connector) == 1- assert not Span.objects.filter(span_id="e" * 16).exists()- assert Span.objects.filter(span_id="g" * 16).exists()diff --git a/tests/test_mcp_data_first.py b/tests/test_mcp_data_first.pyindex eae0ac44..96e850cb 100644--- a/tests/test_mcp_data_first.py+++ b/tests/test_mcp_data_first.py@@ -1,15 +1,14 @@-import asynciofrom unittest.mock import patchimport pytest+from mcp_fixtures import call_toolfrom test_data_first_workflow import workspacefrom overbae.models import APIToken, DataPartitionPlan, Projectfrom overbae.services.decision_providers import catalog-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]def test_agent_creates_and_inspects_project_scoped_partition_without_repository():@@ -26,18 +25,14 @@ def test_agent_creates_and_inspects_project_scoped_partition_without_repository("recipe": {"seed": 12, "fractions": {"train": 0.8, "final": 0.2}, "group_by": ["group_id"]},}with patch("overbae.tasks.data_partitions.build_plan.delay"):- result = asyncio.run(CATALOG.call("create_data_partition", arguments, context))+ result = call_tool("create_data_partition", arguments, context)assert not result.isError, resultplan = DataPartitionPlan.objects.get(project=project)- result = asyncio.run(- CATALOG.call("get_job", {"kind": "data_partition", "id": str(plan.pk)}, context)- )+ result = call_tool("get_job", {"kind": "data_partition", "id": str(plan.pk)}, context)assert not result.isError, resultforeign = Project.objects.create(name="Foreign", slug="foreign-partitions")foreign_context = MCPContext(user=context.user, token=context.token, project=foreign)- denied = asyncio.run(- CATALOG.call("get_job", {"kind": "data_partition", "id": str(plan.pk)}, foreign_context)- )+ denied = call_tool("get_job", {"kind": "data_partition", "id": str(plan.pk)}, foreign_context)assert denied.isError@@ -48,7 +43,7 @@ def test_decision_catalog_reports_eligibility_without_claiming_hardware_qualifictoken=APIToken(scope={"scope": "project", "permission": ["read"]}),project=project,)- result = asyncio.run(CATALOG.call("list_decision_models", {}, context))+ result = call_tool("list_decision_models", {}, context)assert not result.isError, resultoptions = catalog(project)assert any(p["kind"] == "foundation" for p in options)diff --git a/tests/test_mcp_dataset_recovery.py b/tests/test_mcp_dataset_recovery.pyindex 2fde071c..55e1810f 100644--- a/tests/test_mcp_dataset_recovery.py+++ b/tests/test_mcp_dataset_recovery.py@@ -1,18 +1,16 @@from __future__ import annotations-import asyncioimport uuidimport pytestfrom django.utils import timezone-from mcp_fixtures import mcp_context+from mcp_fixtures import call_tool, mcp_contextfrom overbae.models import Dataset, DatasetImport, DatasetLandingWorkfrom overbae.services.datasets import files, imports-from overbae.services.mcp.catalog import CATALOGfrom overbae.tasks import datasets as dataset_tasks-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("recovery")]def test_retained_first_upload_into_an_existing_draft_recovers_through_mcp():@@ -44,11 +42,11 @@ def test_retained_first_upload_into_an_existing_draft_recovers_through_mcp():"attachment_request": attachment_request,},)- inspected = asyncio.run(CATALOG.call("inspect_dataset", {"dataset": str(dataset.pk)}, context))+ inspected = call_tool("inspect_dataset", {"dataset": str(dataset.pk)}, context)assert not inspected.isErroraction = inspected.structuredContent["next_actions"][0]assert action["tool"] == "resume_dataset_import"- recovered = asyncio.run(CATALOG.call(action["tool"], action["arguments"], context))+ recovered = call_tool(action["tool"], action["arguments"], context)assert not recovered.isError, recovered.structuredContentdataset.refresh_from_db()assert dataset.state == "idle" and dataset.source.rows == 2@@ -93,13 +91,13 @@ def test_inspection_leads_to_source_recovery_through_existing_tool(monkeypatch,target.refresh_from_db()assert target.state == Dataset.State.ERROR- inspected = asyncio.run(CATALOG.call("inspect_dataset", {"dataset": str(target.pk)}, context))+ inspected = call_tool("inspect_dataset", {"dataset": str(target.pk)}, context)assert not inspected.isError, inspected.structuredContentactions = inspected.structuredContent["next_actions"]assert len(actions) == 1action = actions[0]assert action["tool"] == "resume_dataset_import"- recovered = asyncio.run(CATALOG.call(action["tool"], action["arguments"], context))+ recovered = call_tool(action["tool"], action["arguments"], context)assert not recovered.isError, recovered.structuredContentassert recovered.structuredContent["dataset"]["id"] == str(target.pk)@@ -131,7 +129,7 @@ def test_inspection_does_not_suggest_a_refused_action_after_import_attempts_are_queued_at=timezone.now(),)- inspected = asyncio.run(CATALOG.call("inspect_dataset", {"dataset": str(dataset.pk)}, context))+ inspected = call_tool("inspect_dataset", {"dataset": str(dataset.pk)}, context)assert not inspected.isError, inspected.structuredContentassert inspected.structuredContent["next_actions"] == []diff --git a/tests/test_mcp_datasets.py b/tests/test_mcp_datasets.pyindex 00990b53..6b0baaa0 100644--- a/tests/test_mcp_datasets.py+++ b/tests/test_mcp_datasets.py@@ -1,11 +1,11 @@from __future__ import annotations-import asyncioimport jsonimport uuidfrom datetime import timedeltaimport pytest+from mcp_fixtures import call_toolfrom overbae.models import (APIToken,@@ -17,27 +17,11 @@ from overbae.models import (Span,User,)-from overbae.services.datasets import land, paths, store+from overbae.services.datasets import paths, storefrom overbae.services.mcp import tools_datasets-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext-pytestmark = pytest.mark.django_db(transaction=True)---def test_start_dataset_preserves_brief_and_exposes_source_handoff():- context = _context()- result = _call(- "start_dataset", {"brief": "Explore source documents before choosing a task."}, context- )- assert not result.isError, result.structuredContent- dataset_id = result.structuredContent["dataset"]["id"]- inspected = _call("inspect_dataset", {"dataset": dataset_id}, context)- assert not inspected.isError, inspected.structuredContent- detail = inspected.structuredContent- assert detail["brief"] == "Explore source documents before choosing a task."- assert detail["source_kind"] == "pending" and detail["capability"] is None- assert detail["human_action"]["arguments"]["dataset"] == dataset_id+pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]def _context(*, permission: str | list[str] = ("read", "write")) -> MCPContext:@@ -60,7 +44,7 @@ def _context(*, permission: str | list[str] = ("read", "write")) -> MCPContext:def _call(name: str, arguments: dict, context: MCPContext):- return asyncio.run(CATALOG.call(name, arguments, context))+ return call_tool(name, arguments, context)def _dataset(context: MCPContext, name: str = "Eval", **kwargs) -> Dataset:@@ -115,32 +99,6 @@ def test_list_datasets_is_project_scoped_filtered_paginated_and_uses_uuids():uuid.UUID(result.structuredContent["datasets"][0]["id"])-def test_inspection_exposes_the_workshops_source_families_and_consumer_requirements():- context = _context()- dataset = _dataset(context)- land.land_rows(- dataset,- [- {- "input": {- "messages": [- {"role": "system", "content": prompt},- {"role": "user", "content": "evidence"},- ]- },- "expected_output": {"answer": "supported"},- }- for prompt in ["Extract fields"] * 25 + ["Apply rules"] * 5- ],- )- result = _call("inspect_dataset", {"dataset": str(dataset.id)}, context)- assert not result.isError- preparation = result.structuredContent["preparation_context"]- assert preparation["profiles"]["source"]["rows_scanned"] == 30- assert [family["rows"] for family in preparation["profiles"]["source"]["families"]] == [25, 5]- assert "not the application" in preparation["consumers"]["model_evaluation"]["execution"]--def test_inspect_is_bounded_ordered_and_refuses_an_ambiguous_name(monkeypatch):context = _context()dataset = _dataset(@@ -182,24 +140,6 @@ def test_inspect_is_bounded_ordered_and_refuses_an_ambiguous_name(monkeypatch):assert "use the dataset id" in twice.structuredContent["error"]["message"]- ("state", "tool"),- [- (Dataset.State.LANDING, "get_job"),- (Dataset.State.RUNNING, "get_job"),- (Dataset.State.ERROR, "inspect_dataset_workbench"),- ],-)-def test_inspect_next_action_follows_dataset_state(state: str, tool: str):- context = _context()- dataset = _dataset(context, state=state, error="/private/tmp/secret.parquet")-- result = _call("inspect_dataset", {"dataset": str(dataset.id)}, context)-- assert result.structuredContent["next_actions"][0]["tool"] == tool- assert "/private/tmp" not in json.dumps(result.structuredContent)--def test_query_is_project_and_cell_scoped_read_only_and_capped(monkeypatch):context = _context()dataset = _dataset(context)@@ -238,20 +178,6 @@ def test_query_is_project_and_cell_scoped_read_only_and_capped(monkeypatch):assert write.structuredContent["error"]["code"] == "query_invalid"-def _root_span(project, trace_id: str) -> Span:- return Span.objects.create(- span_id=uuid.uuid4().hex[:16],- trace_id=trace_id,- project=project,- span_type="entry_point",- name="run",- start_time_ns=1,- end_time_ns=2,- duration_ns=1,- attributes={"overmind.input.data": trace_id, "overmind.output.data": "answer"},- )--def test_trace_creation_refuses_unknown_filters_mixed_sources_and_empty_selections():context = _context()unknown = _call(@@ -276,81 +202,6 @@ def test_trace_creation_refuses_unknown_filters_mixed_sources_and_empty_selectioassert Dataset.objects.filter(project=context.project).count() == 0[email protected]("split", [False, True])[email protected]("choice", ["automatic", "none", "selected"])-def test_trace_creation_respects_the_capability_choice(split, choice):- context = _context()- matched = Capability.objects.create(project=context.project, name="Matched", slug="matched")- selected = Capability.objects.create(project=context.project, name="Selected", slug="selected")- trace_ids = [uuid.uuid4().hex for _ in range(4)]- for trace_id in trace_ids:- span = _root_span(context.project, trace_id)- span.capability = matched- span.save(update_fields=["capability"])- arguments = {"name": "Choice", "trace_ids": trace_ids}- if choice != "automatic":- arguments["capability"] = None if choice == "none" else str(selected.id)- if split:- arguments["split"] = {"eval_percent": 30, "position": "tail"}- result = _call("create_dataset_from_traces", arguments, context)- assert result.isError is False, result.structuredContent- body = result.structuredContent- ids = [body["dataset"]["id"]]- if split:- ids.append(body["eval_dataset"]["id"])- expected = {"automatic": matched.id, "none": None, "selected": selected.id}[choice]- for dataset in Dataset.objects.filter(pk__in=ids):- assert dataset.state == Dataset.State.IDLE, dataset.error- assert dataset.capability_id == expected- assert dataset.capability_rank[0]["capability_id"] == str(matched.id)---def test_trace_creation_returns_a_dataset_run_receipt(monkeypatch):- context = _context()- Capability.objects.create(project=context.project, name="Support", slug="support")- _root_span(context.project, "b" * 32)- sources = []-- def create_dataset(**kwargs):- sources.append(kwargs["source"])- return _dataset(- context,- kwargs["name"],- capability=kwargs.get("capability"),- intent=kwargs.get("intent") or Dataset.Intent.PENDING,- state=Dataset.State.LANDING,- )-- monkeypatch.setattr(tools_datasets.dispatch, "create_dataset", create_dataset)-- traces = _call(- "create_dataset_from_traces",- {"name": "Trace set", "trace_ids": ["b" * 32]},- context,- )- for result in (traces,):- body = result.structuredContent- assert body["job"]["kind"] == "dataset_run"- assert body["job"]["id"] == body["dataset"]["id"]- assert body["job"]["resource"]["uri"] == (- f"overmind://jobs/dataset_run/{body['dataset']['id']}"- )- assert body["dataset"]["resource"]["uri"] in {- link["uri"] for link in body["resource_links"]- }- assert body["traces"] == 1- assert sources == [{"traces": {"trace_ids": ["b" * 32]}}]---def test_dataset_tool_text_is_complete_structured_json():- context = _context()- _dataset(context)-- result = _call("list_datasets", {}, context)-- assert json.loads(result.content[0].text) == result.structuredContent--def test_list_and_inspect_map_legacy_ft_intent():context = _context()dataset = _dataset(context, name="Old train", intent="ft")diff --git a/tests/test_mcp_evaluation_reports.py b/tests/test_mcp_evaluation_reports.pyindex ed66983f..0ab44a6b 100644--- a/tests/test_mcp_evaluation_reports.py+++ b/tests/test_mcp_evaluation_reports.py@@ -1,6 +1,7 @@import jsonimport pytest+from mcp_fixtures import asgi_dbfrom rest_framework.test import APIClientfrom starlette.testclient import TestClientfrom test_data_first_workflow import workspace@@ -10,45 +11,7 @@ from overbae.models import APIToken, NativeEvaluationPlan, Projectfrom overbae.services.mcp.server import create_mcp_applicationfrom overbae.services.native_evaluation import directory-pytestmark = pytest.mark.django_db(transaction=True)--[email protected]("pending", [{}, {"receipt": None}])-def test_pending_evaluation_receipts_remain_readable_until_completion(pending):- plan, key = completed_report()- plan.state = "running"- plan.results = {}- plan.calls = {"calibration_candidate": {"id": "existing-call", "state": "running", **pending}}- plan.save(update_fields=["state", "results", "calls"])- with TestClient(create_mcp_application()) as client:- for complete in (False, True):- if complete:- plan.calls["calibration_candidate"].update(- state="completed",- receipt={"decisions": 210, "predictions_sha256": "sealed", "tokens": [1, 2]},- )- plan.save(update_fields=["calls"])- job = call(client, key, "get_job", {"kind": "native_evaluation", "id": str(plan.pk)})- observed = job["progress"]["calls"]["calibration_candidate"]- assert observed["id"] == "existing-call"- assert observed["state"] == ("completed" if complete else "running")- assert observed["receipt"] == (- {"decisions": 210, "predictions_sha256": "sealed"} if complete else None- )- resource = client.post(- "/api/mcp/",- json={- "jsonrpc": "2.0",- "id": 3,- "method": "resources/read",- "params": {"uri": job["resource"]["uri"]},- },- headers={"X-Api-Key": key, "Accept": "application/json"},- ).json()["result"]- assert (- json.loads(resource["contents"][0]["text"])["calls"]["calibration_candidate"]- == observed- )+pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]def completed_report():@@ -97,6 +60,7 @@ def completed_report():return plan, key+@asgi_dbdef test_mcp_summary_counts_every_benchmark_and_links_complete_project_scoped_reports():plan, key = completed_report()with TestClient(create_mcp_application()) as client:@@ -133,18 +97,3 @@ def test_mcp_summary_counts_every_benchmark_and_links_complete_project_scoped_re)api.credentials(HTTP_X_API_KEY=foreign_key)assert api.get(progress["report"]["json_path"]).status_code == 404--[email protected]("format", ["json", "md"])-def test_report_format_downloads_without_renderer_negotiation_failure(format):- plan, key = completed_report()- api = APIClient()- api.credentials(HTTP_X_API_KEY=key)- path = f"/api/native-evaluations/{plan.pk}/report/?format={format}"- response = api.get(path)- assert response.status_code == 200- assert b"source-104" in b"".join(response.streaming_content)- plan.state = "running"- plan.save(update_fields=["state"])- assert api.get(path).status_code == 400- assert api.get(f"/api/native-evaluations/{plan.pk}/report/?format=invalid").status_code == 400diff --git a/tests/test_mcp_evaluations.py b/tests/test_mcp_evaluations.pyindex ee74be86..bdda044f 100644--- a/tests/test_mcp_evaluations.py+++ b/tests/test_mcp_evaluations.py@@ -1,13 +1,13 @@from __future__ import annotations-import asyncioimport jsonimport uuidimport pytest+from asgiref.sync import async_to_syncfrom factories import make_matrix_rowfrom mcp.shared.exceptions import McpError-from mcp_fixtures import mcp_context+from mcp_fixtures import call_tool, mcp_contextfrom overbae.innermind import runsfrom overbae.models import (@@ -23,9 +23,8 @@ from overbae.services.datasets import paths, storefrom overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext, bind_contextfrom overbae.services.mcp.resources import read_resource-from overbae.tasks.innermind import run_eval_run-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]EVALUATION_TOOLS = {"create_eval_matrix_row",@@ -39,12 +38,12 @@ EXACT_MATCH = "def evaluate(span):\n return span.output == span.expected\n"def _call(name: str, arguments: dict, context: MCPContext):- return asyncio.run(CATALOG.call(name, arguments, context))+ return call_tool(name, arguments, context)def _read(context: MCPContext, uri: str) -> dict:with bind_context(context):- return json.loads(asyncio.run(read_resource(uri))[0].content)+ return json.loads(async_to_sync(read_resource)(uri)[0].content)def _dataset(context: MCPContext, rows: int = 2) -> Dataset:@@ -74,6 +73,7 @@ def _writer() -> MCPContext:return mcp_context(permission=["read", "write"])[email protected]("authentication")def test_catalog_exposes_evaluation_tools_and_hides_writes_from_readers():assert {definition.name for definition in CATALOG.definitions()} >= EVALUATION_TOOLSreadable = {tool.name for tool in CATALOG.tools(frozenset({"read"}))}@@ -137,6 +137,7 @@ def test_matrix_rows_are_created_and_deleted_but_never_edited():assert missing.structuredContent["error"]["code"] == "eval_matrix_row_not_found"[email protected]("tenancy")def test_matrix_rows_cannot_be_deleted_across_projects():context = _writer()other = _writer()@@ -166,99 +167,11 @@ def test_eval_sets_are_project_scoped_and_can_be_activated():assert [entry["name"] for entry in resource["rows"]] == ["Accuracy"]other = _writer()with bind_context(other), pytest.raises(McpError):- asyncio.run(read_resource(result.structuredContent["resource_links"][0]["uri"]))+ async_to_sync(read_resource)(result.structuredContent["resource_links"][0]["uri"])foreign = _call("create_eval_set", {"name": "Foreign", "rows": [str(row.id)]}, other)assert foreign.structuredContent["error"]["code"] == "eval_matrix_row_not_found"-def test_readiness_reports_advisory_context_without_blocking(fake_llm):- fake_llm.limits["openai/gpt-4.1"] = 1000- context = mcp_context()- dataset = _dataset(context)- make_matrix_row(- context.project, "Exact", type=EvalMatrix.Type.DETERMINISTIC, source=EXACT_MATCH- )-- result = _call(- "check_evaluation_readiness",- {- "dataset": str(dataset.pk),- "targets": [{"mode": "generate", "label": "Candidate", "model_name": "gpt-4.1"}],- },- context,- )-- output = result.structuredContent- [check] = output["context_checks"]- assert (check["role"], check["label"], check["status"]) == (- "generation",- "Candidate",- "warning",- )- assert check["context_window"] == 1000- assert output["matrix"] == [{"name": "Exact", "type": "deterministic"}]- assert output["ready"] is True---def test_readiness_without_matrix_rows_is_not_ready():- context = mcp_context()- dataset = _dataset(context)-- output = _call(- "check_evaluation_readiness",- {"dataset": str(dataset.pk), "targets": [{"mode": "recorded"}]},- context,- ).structuredContent-- assert output["ready"] is False- assert output["matrix"] == []---def test_run_evaluation_queues_one_run_per_target_in_one_group(monkeypatch):- queued = []- monkeypatch.setattr(run_eval_run, "delay", lambda **kw: queued.append(kw) or _Result())- context = _writer()- dataset = _dataset(context)- make_matrix_row(- context.project, "Exact", type=EvalMatrix.Type.DETERMINISTIC, source=EXACT_MATCH- )-- result = _call(- "run_evaluation",- {- "name": "Backtest",- "dataset": str(dataset.pk),- "judge_model": "claude-haiku-4-5",- "targets": [- {"mode": "recorded", "label": "Recorded", "is_baseline": True},- {"mode": "generate", "label": "Mini", "model_name": "openai/gpt-5-mini"},- ],- },- context,- )-- output = result.structuredContent- assert [(run["label"], run["mode"], run["is_baseline"]) for run in output["runs"]] == [- ("Recorded", "recorded", True),- ("Mini", "generate", False),- ]- created = EvalRun.objects.filter(group=output["group"])- assert created.count() == 2- assert set(created.values_list("judge_model", flat=True)) == {"claude-haiku-4-5"}- assert {kw["eval_run_id"] for kw in queued} == {run["id"] for run in output["runs"]}- resource = _read(context, output["runs"][1]["resource"]["uri"])- assert resource["matrix"] == [{"name": "Exact", "type": "deterministic"}]- assert _call("run_evaluation", {**_run_args(dataset)}, _writer()).isError---def _run_args(dataset) -> dict:- return {"name": "x", "dataset": str(dataset.pk), "targets": [{"mode": "recorded"}]}---class _Result:- id = "task"--def _completed_run(context, dataset, label, row_scores, *, group, is_baseline=False) -> EvalRun:row = make_matrix_row(context.project, f"Exact {label}")run = runs.create_run(diff --git a/tests/test_mcp_finetuning.py b/tests/test_mcp_finetuning.pyindex 995ab81c..70741086 100644--- a/tests/test_mcp_finetuning.py+++ b/tests/test_mcp_finetuning.py@@ -1,21 +1,19 @@from __future__ import annotations-import asyncioimport jsonimport uuidfrom types import SimpleNamespacefrom unittest.mock import Mock-import pandas as pdimport pytest+from asgiref.sync import async_to_syncfrom conftest import TRAIN_ROWS, frozen_dataset-from mcp_fixtures import training_setup+from mcp_fixtures import call_tool, training_setupfrom modal_shared.preparation import preparation_failurefrom overbae.core.errors import InputValidationErrorfrom overbae.models import (APIToken,- Cell,Dataset,DeployedModel,FinetuningJob,@@ -24,14 +22,12 @@ from overbae.models import (TrainingPreparation,User,)-from overbae.services.datasets import paths, store-from overbae.services.finetuning_validator import ValidationResultfrom overbae.services.mcp import tools_finetuningfrom overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext, bind_contextfrom overbae.services.mcp.resources import read_resource-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]def _context(*, permission: str | list[str] = "read") -> MCPContext:@@ -50,9 +46,10 @@ def _context(*, permission: str | list[str] = "read") -> MCPContext:def _call(name: str, arguments: dict, context: MCPContext):- return asyncio.run(CATALOG.call(name, arguments, context))+ return call_tool(name, arguments, context)[email protected]("privacy")@pytest.mark.parametrize("tool", ["prepare_training_data", "retry_deployment"])@pytest.mark.parametrize("known", [True, False])def test_preparation_and_deployment_errors_are_safe_for_agents(monkeypatch, tool, known):@@ -87,47 +84,7 @@ def test_preparation_and_deployment_errors_are_safe_for_agents(monkeypatch, toolassert result.structuredContent["error"]["code"] == "internal_error"-def _ok_cell(dataset, *, intent, rows=2, title="source", position=0, active=True, fits=True):- cell = Cell.objects.create(- dataset=dataset,- position=position,- title=title,- state=Cell.State.OK,- rows=rows,- fingerprint=f"fp-{position}-{uuid.uuid4().hex[:8]}",- intent_report={intent: {"ok": fits, "reason": "" if fits else "not a fit"}},- capability_report={"ok": True, "reason": ""},- stats={"num_examples": rows, "max_token_length": 8},- )- if active:- dataset.active = cell- dataset.save(update_fields=["active"])- path = paths.cell_path(dataset.id, cell.id)- store.write_frame(- path,- pd.DataFrame(- [- {- "source_row": i,- "messages": [- {"role": "user", "content": f"q{i}"},- {"role": "assistant", "content": f"a{i}"},- ],- }- if intent == "train"- else {"source_row": i, "input": f"q{i}", "expected_output": f"a{i}"}- for i in range(rows)- ]- ),- )- cell.fingerprint = store.file_sha256(path)- cell.save(update_fields=["fingerprint"])- from conftest import review_fixture-- review_fixture(dataset, cell)- return cell--[email protected]("authentication")def test_catalog_has_finetuning_tools_and_read_only_keys_hide_writes():names = {"check_finetune_readiness",@@ -180,7 +137,7 @@ def test_exact_preparation_has_pollable_project_scoped_receipt(settings, monkeyp)return json.loads(contents[0].content)- assert asyncio.run(resource())["status"] == "queued"+ assert async_to_sync(resource)()["status"] == "queued"failure = preparation_failure("worker_out_of_date")TrainingPreparation.objects.filter(pk=receipt["id"]).update(state="failed", report=failure, error=failure["error"]@@ -190,7 +147,7 @@ def test_exact_preparation_has_pollable_project_scoped_receipt(settings, monkeypassert failed.structuredContent["status"] == "failed"assert failed.structuredContent["job_error"] == failure["error"]assert failed.structuredContent["progress"] == failure- assert asyncio.run(resource())["error"] == failure["error"]+ assert async_to_sync(resource)()["error"] == failure["error"]other = _context()denied = _call("get_job", {"kind": receipt["kind"], "id": receipt["id"]}, other)assert denied.isError@@ -265,6 +222,7 @@ def test_readiness_classifies_selected_capability_and_defers_to_data_for_none(faassert definition.cost_class == "llm"[email protected]("tenancy")def test_cross_project_references_are_not_resolved():context = _context()other = _context()@@ -297,219 +255,6 @@ def test_cross_project_references_are_not_resolved():assert active.structuredContent["error"]["code"] == "capability_not_found"-def test_estimate_uses_existing_estimator_without_creating_a_job(monkeypatch):- context = _context()- dataset = Dataset.objects.create(- project=context.project,- name="Train",- intent=Dataset.Intent.TRAIN,- )- cell = _ok_cell(dataset, intent="train", rows=4)- calls = {}-- def estimate(dataset_id, **kwargs):- calls.update(dataset_id=dataset_id, kwargs=kwargs)- return {- "cost_estimate": {"usd": 1.25},- "time_estimate": {"seconds": 60, "human": "1 min"},- "trained_tokens": 1000,- }-- monkeypatch.setattr(tools_finetuning, "estimate_for_hyperparams", estimate)- result = _call(- "estimate_finetune",- {- "dataset": str(dataset.id),- "base_model": "Qwen/Qwen2.5-7B-Instruct",- "n_epochs": 4,- "use_lora": False,- },- context,- )- assert result.isError is False, result.structuredContent- assert calls == {- "dataset_id": str(dataset.id),- "kwargs": {- "base_model": "Qwen/Qwen2.5-7B-Instruct",- "n_epochs": 4,- "use_lora": False,- "cell": cell,- "validation_cell": None,- "validation_enabled": True,- "validation_split_ratio": 0.2,- "split_method": "random",- "hyperparameters": {"monitoring": result.structuredContent["monitoring"]["policy"]},- },- }- assert result.structuredContent["trained_tokens"] == 1000- assert result.structuredContent["cell"]["id"] == str(cell.id)- assert result.structuredContent["cell"]["rows"] == 4- assert not FinetuningJob.objects.filter(project=context.project).exists()--[email protected]("capability_choice", ["selected", "omitted", "none"])[email protected]("unassigned_set", [False, True])[email protected]("disable_evals", [False, True])-def test_start_uses_serializer_and_worker_task(- monkeypatch, capability_choice, unassigned_set, disable_evals-):- context = _context(permission=["read", "write"])- capability, train, _evaluation, _eval_set = training_setup(context)- if unassigned_set:- _eval_set.capability = None- _eval_set.save(update_fields=["capability"])- calls = {}- monkeypatch.setattr(- tools_finetuning,- "validate_dataset",- lambda *_args, **_kwargs: ValidationResult(True, "conversational", 1),- )- monkeypatch.setattr(- tools_finetuning,- "stamp_hyperparameters_for_model",- lambda *_args: {"training_type": {"type": "Lora"}},- )- monkeypatch.setattr("overbae.api.credit_gate.require_credits", lambda _user: None)- monkeypatch.setattr(- "overbae.tasks.finetuning.run_finetuning.apply_async",- lambda **kwargs: calls.update(kwargs=kwargs) or SimpleNamespace(id="celery-ft"),- )-- result = _call(- "start_finetune",- {- "dataset": str(train.id),- **(- {"capability": str(capability.id)}- if capability_choice == "selected"- else {"capability": None}- if capability_choice == "none"- else {}- ),- "base_model": "Qwen/Qwen2.5-7B-Instruct",- **({"baseline_model": capability.model} if capability_choice == "selected" else {}),- **(- {- "eval_incumbent_before": False,- "eval_incumbent_after": False,- "eval_model_before": False,- "eval_model_after": False,- }- if disable_evals- else {}- ),- },- context,- )- assert result.isError is False, result.structuredContent- job = FinetuningJob.objects.get(project=context.project)- assert job.capability_id == (capability.id if capability_choice == "selected" else None)- if capability_choice == "selected":- assert job.baseline_model == capability.model- assert job.eval_dataset_id == (None if disable_evals else _evaluation.id)- assert job.eval_set_id == (None if disable_evals else _eval_set.id)- if disable_evals:- assert not any(- (- job.eval_incumbent_before,- job.eval_incumbent_after,- job.eval_model_before,- job.eval_model_after,- )- )- assert calls["kwargs"] == {"kwargs": {"job_id": str(job.id)}}- assert result.structuredContent["finetune"]["resource"]["uri"] == (- f"overmind://finetunes/{job.id}"- )- assert result.structuredContent["job"]["resource"]["uri"] == (- f"overmind://jobs/finetune/{job.id}"- )- assert job.cell_id == train.active_cell.id- assert result.structuredContent["cell"]["id"] == str(job.cell_id)- train.active_cell.refresh_from_db()- assert train.active_cell.used_at is not None--- "deployment_status",- [DeployedModel.Status.FAILED, DeployedModel.Status.DELETED],-)-def test_retry_returns_resource_and_dispatches_for_recoverable_deployment(- monkeypatch, deployment_status-):- context = _context(permission=["read", "write"])- _, train, _, _ = training_setup(context)- job = FinetuningJob.objects.create(- project=context.project,- dataset=train,- base_model="Qwen/Qwen2.5-7B-Instruct",- status=FinetuningJob.Status.SUCCEEDED,- remote_job_id="remote",- )- deployment = DeployedModel.objects.create(- project=context.project,- finetuning_job=job,- status=deployment_status,- model_id=f"ft-retry-{deployment_status}",- error_message="previous deployment failure",- )- monkeypatch.setattr("overbae.api.credit_gate.require_credits", lambda _user: None)- calls = {}- monkeypatch.setattr(- "overbae.tasks.model_deployment.register_finetuned_model.delay",- lambda **kwargs: calls.update(kwargs=kwargs),- )- result = _call("retry_deployment", {"deployment": deployment.model_id}, context)- assert result.isError is False, result.structuredContent- assert calls == {} # the database outbox does not depend on a broker acknowledgement- deployment.refresh_from_db()- assert deployment.status == DeployedModel.Status.QUEUED- assert deployment.error_message == ""- assert result.structuredContent["retry"]["kind"] == "deployment"- assert result.structuredContent["retry"]["status"] == DeployedModel.Status.QUEUED- assert result.structuredContent["retry"]["resource"]["uri"] == (- f"overmind://jobs/deployment/{deployment.id}"- )- assert result.structuredContent["deployment"]["resource"]["uri"] == (- f"overmind://deployments/{deployment.id}"- )--- "deployment_status",- [- DeployedModel.Status.QUEUED,- DeployedModel.Status.QUANTIZING,- DeployedModel.Status.DEPLOYING,- DeployedModel.Status.WARMING,- DeployedModel.Status.READY,- DeployedModel.Status.DELETING,- ],-)-def test_retry_rejects_ready_or_in_flight_deployment(deployment_status):- context = _context(permission=["read", "write"])- train = Dataset.objects.create(- project=context.project, name="Train", intent=Dataset.Intent.TRAIN- )- job = FinetuningJob.objects.create(- project=context.project,- dataset=train,- base_model="Qwen/Qwen2.5-7B-Instruct",- status=FinetuningJob.Status.SUCCEEDED,- )- deployment = DeployedModel.objects.create(- project=context.project,- finetuning_job=job,- model_id=f"ft-no-retry-{deployment_status}",- status=deployment_status,- )-- result = _call("retry_deployment", {"deployment": str(deployment.id)}, context)-- assert result.isError is True- assert result.structuredContent["error"]["code"] == "deployment_not_ready"--def test_retry_rejects_deployment_without_usable_finetune_job():context = _context(permission=["read", "write"])train = Dataset.objects.create(@@ -534,44 +279,6 @@ def test_retry_rejects_deployment_without_usable_finetune_job():assert result.structuredContent["error"]["code"] == "finetune_not_ready"-def test_retry_remains_durable_when_broker_is_unavailable(monkeypatch):- context = _context(permission=["read", "write"])- _, train, _, _ = training_setup(context)- job = FinetuningJob.objects.create(- project=context.project,- dataset=train,- base_model="Qwen/Qwen2.5-7B-Instruct",- status=FinetuningJob.Status.SUCCEEDED,- )- deployment = DeployedModel.objects.create(- project=context.project,- finetuning_job=job,- model_id="ft-dispatch-failure",- status=DeployedModel.Status.FAILED,- error_message="previous failure",- )- monkeypatch.setattr("overbae.api.credit_gate.require_credits", lambda _user: None)-- job.remote_job_id = "remote"- job.save(update_fields=["remote_job_id"])-- def fail_dispatch(**_kwargs):- raise RuntimeError("broker unavailable")-- monkeypatch.setattr(- "overbae.tasks.model_deployment.register_finetuned_model.delay",- fail_dispatch,- )-- result = _call("retry_deployment", {"deployment": str(deployment.id)}, context)-- assert result.isError is False- deployment.refresh_from_db()- assert deployment.status == DeployedModel.Status.QUEUED- assert deployment.deployment_stage == "base"- assert deployment.error_message == ""--def test_set_active_model_validates_ready_same_project_and_clear(monkeypatch):context = _context(permission=["read", "write"])capability, train, _, _ = training_setup(context)@@ -629,7 +336,7 @@ def test_benchmark_tool_and_capability_resource_preserve_serving():contents = list(await read_resource(f"overmind://capabilities/{capability.id}"))return json.loads(contents[0].content)- state = asyncio.run(resource())+ state = async_to_sync(resource)()assert state["benchmark_model"]["id"] == str(benchmark.id)assert [candidate["id"] for candidate in state["benchmark_candidates"]] == [str(benchmark.id)]result = _call("set_benchmark_model", {"capability": str(capability.id)}, context)@@ -659,6 +366,7 @@ def test_benchmark_tool_rejects_infrastructure_and_foreign_projects():assert capability.benchmark_model_id is None[email protected]("privacy")def test_run_inference_redacts_service_errors(monkeypatch):context = _context(permission=["read", "write"])deployment = DeployedModel.objects.create(@@ -687,6 +395,7 @@ def test_run_inference_redacts_service_errors(monkeypatch):assert "provider secret" not in str(result.structuredContent)[email protected]("privacy")def test_start_rejects_credential_shaped_hyperparameter_keys():context = _context(permission=["read", "write"])capability, train, _, _ = training_setup(context)@@ -705,45 +414,6 @@ def test_start_rejects_credential_shaped_hyperparameter_keys():assert not FinetuningJob.objects.filter(project=context.project).exists()-def test_model_swap_prompt_returns_prompt_and_capability_refs(monkeypatch):- context = _context(permission=["read", "write"])- capability, train, _, _ = training_setup(context)- job = FinetuningJob.objects.create(- project=context.project,- capability=capability,- dataset=train,- base_model="Qwen/Qwen2.5-7B-Instruct",- status=FinetuningJob.Status.SUCCEEDED,- )- DeployedModel.objects.create(- project=context.project,- finetuning_job=job,- model_id="ft-pr",- status=DeployedModel.Status.READY,- )- monkeypatch.setattr(- "overbae.services.model_swap_prompt.model_swap_prompt_for_job",- lambda _job, pin=False, base_url="": (- {- "prompt": "Point the client at the new model.",- "pin": pin,- "capability_id": str(capability.id),- "capability_name": capability.name,- "old_model": "gpt-4o-mini",- "new_model": "ft-pr",- },- None,- ),- )- result = _call("get_model_swap_prompt", {"finetune": str(job.id)}, context)- assert result.isError is False, result.structuredContent- body = result.structuredContent- assert body["prompt"] == "Point the client at the new model."- assert body["old_model"] == "gpt-4o-mini"- assert body["new_model"] == "ft-pr"- assert body["capability_id"] == str(capability.id)--def test_model_swap_prompt_reports_why_it_is_unavailable(monkeypatch):context = _context(permission=["read", "write"])capability, train, _, _ = training_setup(context)@@ -766,135 +436,6 @@ def test_model_swap_prompt_reports_why_it_is_unavailable(monkeypatch):assert result.structuredContent["error"]["code"] == "model_swap_prompt_not_ready"-def test_deployment_resource_has_url_and_bounded_metrics():- context = _context()- deployment = DeployedModel.objects.create(- project=context.project,- model_id="ft-resource",- status=DeployedModel.Status.READY,- inference_url="https://inference.example/models/ft-resource",- )-- async def read():- with bind_context(context):- values = await read_resource(f"overmind://deployments/{deployment.id}")- return values[0].content-- import json-- resource = json.loads(asyncio.run(read()))- assert resource["inference_url"] == deployment.inference_url- assert resource["metrics"]["request_count"] == 0---def test_finetune_resource_bounds_progress_without_checkpoint_urls():- context = _context()- job = FinetuningJob.objects.create(- project=context.project,- dataset=Dataset.objects.create(- project=context.project,- name="Train",- intent=Dataset.Intent.TRAIN,- ),- base_model="Qwen/Qwen2.5-7B-Instruct",- progress={- "percent": 50,- "metrics": {"loss": [1.0, 0.5]},- "checkpoints": [{"url": "https://signed.example/checkpoint"}],- },- )-- async def read():- with bind_context(context):- values = await read_resource(f"overmind://finetunes/{job.id}")- return values[0].content-- import json-- resource = json.loads(asyncio.run(read()))- assert resource["progress"]["percent"] == 50- assert resource["loss"] == [1.0, 0.5]- assert "checkpoints" not in resource["progress"]- assert "signed.example" not in json.dumps(resource)---def test_readiness_reports_chosen_cell_rows_and_contract_failure(monkeypatch):- context = _context()- dataset = Dataset.objects.create(- project=context.project, name="Train", intent=Dataset.Intent.TRAIN- )- cell = _ok_cell(dataset, intent="train", rows=7, fits=False)- monkeypatch.setattr(- tools_finetuning,- "finetune_prerequisite_report",- lambda *_args, **_kwargs: {- "missing": [],- "catalog": {},- "n_candidates": 0,- "recommendations": [],- "has_tool_calling": False,- "excluded": [],- },- )- result = _call("check_finetune_readiness", {"dataset": str(dataset.id)}, context)- assert result.isError is False- output = result.structuredContent- assert output["ready"] is False- assert output["dataset"]["cell"]["id"] == str(cell.id)- assert output["dataset"]["cell"]["rows"] == 7- assert output["dataset"]["cell"]["fits"] is False- assert any("training dataset" in item for item in output["missing"])---def test_start_uses_explicit_cell_not_active(monkeypatch):- context = _context(permission=["read", "write"])- capability, train, _evaluation, _eval_set = training_setup(context)- extra = _ok_cell(train, intent="train", rows=9, title="shaped", position=1, active=False)- called = {}-- def fake_launch(**kwargs):- called.update(kwargs)- return FinetuningJob.objects.create(- project=context.project,- dataset=train,- capability=capability,- cell=kwargs["cell"],- base_model=kwargs["base_model"],- name="job",- status=FinetuningJob.Status.QUEUED,- )-- monkeypatch.setattr(tools_finetuning, "launch_finetune", fake_launch)- monkeypatch.setattr(- tools_finetuning,- "validate_dataset",- lambda *_args, **_kwargs: ValidationResult(True, "conversational", 1),- )- monkeypatch.setattr(- tools_finetuning,- "stamp_hyperparameters_for_model",- lambda *_args: {"training_type": {"type": "Lora"}},- )- monkeypatch.setattr("overbae.api.credit_gate.require_credits", lambda _user: None)- result = _call(- "start_finetune",- {- "dataset": str(train.id),- "capability": str(capability.id),- "base_model": "Qwen/Qwen2.5-7B-Instruct",- "cell": str(extra.id),- "baseline_model": "ft-selected-benchmark",- },- context,- )- assert result.isError is False, result.structuredContent- assert called["cell"].id == extra.id- assert called["baseline_model"] == "ft-selected-benchmark"- extra.refresh_from_db()- assert extra.used_at is None # The mocked launch skips the atomic creation/freeze service.- assert result.structuredContent["cell"]["id"] == str(extra.id)--def test_activation_receipt_can_be_polled_and_is_project_scoped():context = _context(permission=["read", "write"])capability, _, _, _ = training_setup(context)@@ -968,6 +509,7 @@ def test_native_readiness_uses_explicit_full_cell_and_external_validation_withouassert str(unrelated_eval.id) not in json.dumps(body["selection"])[email protected]("work-once")def test_repeated_launch_key_returns_one_job_and_rejects_changed_recipe(monkeypatch):context = _context(permission=["read", "write"])_, train, _, _ = training_setup(context)@@ -1084,140 +626,6 @@ def test_native_evaluation_is_shared_by_mcp_rest_and_scoped_resources(settings):assert _call("schedule_native_evaluation", arguments, other).isError[email protected]("baseline", [None, True, False])-def test_native_baseline_choice_is_pinned_without_disabling_validation(- baseline, settings, monkeypatch-):- settings.FINETUNING_BACKEND = "modal"- context = _context(permission=["read", "write"])- source = [- {- "decision": {- "state": str(i),- "question": "Choose",- "kind": "choice",- "options": ["A", "B"],- "target_probabilities": [0.2, 0.8],- }- }- for i in range(12)- ]- train = frozen_dataset(context.project, source, contract="train")- dispatch = Mock(return_value=SimpleNamespace(id="baseline-choice"))- monkeypatch.setattr("overbae.tasks.finetuning.run_finetuning.apply_async", dispatch)- monkeypatch.setattr("overbae.api.credit_gate.require_credits", lambda _: None)- recipe = {"training_type": {"type": "Lora"}}- if baseline is not None:- recipe["pre_training_baseline"] = baseline- arguments = {- "dataset": str(train.id),- "base_model": "Qwen/Qwen3.5-4B",- "request_key": "baseline-choice",- "hyperparameters": recipe,- }- quote = _call(- "estimate_finetune", {k: v for k, v in arguments.items() if k != "request_key"}, context- )- assert not quote.isError, quote.structuredContent- assert quote.structuredContent["training_contract"]["pre_training_baseline"] is (- baseline is not False- )- first = _call("start_finetune", arguments, context)- assert not first.isError, first.structuredContent- job = FinetuningJob.objects.get(pk=first.structuredContent["job"]["id"])- enabled = baseline is not False- assert job.validation_enabled is True- assert job.hyperparameters["pre_training_baseline"] is enabled- assert (- job.requested_configuration["configuration"]["hyperparameters"]["pre_training_baseline"]- is enabled- )- repeated = _call("start_finetune", arguments, context)- assert not repeated.isError, repeated.structuredContent- changed = _call(- "start_finetune",- {**arguments, "hyperparameters": {**recipe, "pre_training_baseline": not enabled}},- context,- )- assert changed.isError- assert dispatch.call_count == 1-- async def read():- with bind_context(context):- return list(await read_resource(f"overmind://finetunes/{job.pk}"))-- resource = json.loads(asyncio.run(read())[0].content)- assert resource["record"]["contract"]["pre_training_baseline"] is enabled---def test_native_estimate_reuses_completed_launch_with_implicit_packing(settings, monkeypatch):- settings.FINETUNING_BACKEND = "modal"- context = _context(permission=["read", "write"])- source = [- {- "decision": {- "state": str(i),- "question": "Choose",- "kind": "choice",- "options": ["A", "B"],- "target_probabilities": [0.2, 0.8],- }- }- for i in range(20)- ]- train = frozen_dataset(context.project, source, contract="train")- monkeypatch.setattr(- "overbae.tasks.finetuning.run_finetuning.apply_async",- Mock(return_value=SimpleNamespace(id="forecast")),- )- monkeypatch.setattr("overbae.api.credit_gate.require_credits", lambda _: None)- monkeypatch.setattr("overbae.services.training_forecast.hardware", lambda *_: ("H100", 1))- arguments = {- "dataset": str(train.id),- "base_model": "Qwen/Qwen3.5-0.8B",- "validation_enabled": False,- "hyperparameters": {- "n_epochs": 2,- "max_steps": 10,- "batch_size": 16,- "context_length": 4096,- "training_type": {"type": "Lora"},- },- }- launch = _call("start_finetune", {**arguments, "request_key": "measured-recipe"}, context)- assert not launch.isError, launch.structuredContent- job = FinetuningJob.objects.get(pk=launch.structuredContent["job"]["id"])- assert job.hyperparameters["packing"] is False- job.status = "succeeded"- job.provider = "modal"- job.effective_configuration = {"gpu_type": "H100", "gpu_count": 1}- job.progress = {- "trained_steps": 10,- "total_steps": 10,- "compute_usage": [- {- "usage_id": "measured-worker",- "gpu_type": "H100",- "gpu_count": 1,- "elapsed_seconds": 200,- }- ],- }- job.save()- quote = _call("estimate_finetune", arguments, context)- assert not quote.isError, quote.structuredContent- forecast = quote.structuredContent["forecast"]- assert forecast["evidence_jobs"] == [str(job.pk)], forecast["rejected_measurements"]- assert forecast["evidence"][0]["scaled_seconds"] == pytest.approx(200)- changed = _call(- "estimate_finetune",- {**arguments, "hyperparameters": {**arguments["hyperparameters"], "max_steps": 5}},- context,- )- assert not changed.isError, changed.structuredContent- assert changed.structuredContent["forecast"]["evidence_jobs"] == []--@pytest.mark.parametrize("baseline", ["false", 0, None, {}, []])def test_native_baseline_rejects_non_boolean_choices(baseline, settings, monkeypatch):settings.FINETUNING_BACKEND = "modal"diff --git a/tests/test_mcp_finetuning_receipts.py b/tests/test_mcp_finetuning_receipts.pyindex bc69efc3..51834b33 100644--- a/tests/test_mcp_finetuning_receipts.py+++ b/tests/test_mcp_finetuning_receipts.py@@ -1,12 +1,11 @@from __future__ import annotations-import asyncioimport uuidfrom types import SimpleNamespaceimport pytestfrom django.urls import reverse-from mcp_fixtures import training_setup+from mcp_fixtures import call_tool, training_setupfrom rest_framework.test import APIClientfrom overbae.api.credit_gate import PaymentRequired@@ -20,10 +19,9 @@ from overbae.models import (User,)from overbae.services.finetuning_validator import ValidationResult-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("work-once")]def _context() -> MCPContext:@@ -39,7 +37,7 @@ def _context() -> MCPContext:def _call(name: str, arguments: dict, context: MCPContext):- return asyncio.run(CATALOG.call(name, arguments, context))+ return call_tool(name, arguments, context)@pytest.mark.parametrize("training_type", ["Lora", ["Lora"], 1, {"type": "unknown"}])diff --git a/tests/test_mcp_inference.py b/tests/test_mcp_inference.pyindex 414e40cb..1e75980b 100644--- a/tests/test_mcp_inference.py+++ b/tests/test_mcp_inference.py@@ -9,17 +9,15 @@ from unittest.mock import AsyncMock, Mockimport pytestfrom django.core.cache import cachefrom django.utils import timezone+from mcp_fixtures import asgi_db, call_tool, mcp_contextfrom rest_framework.test import APIClientfrom starlette.testclient import TestClient-from modal_shared.context_budget import DEFAULT_OUTPUT_TOKENSfrom overbae.models import (APIToken,- Capability,DeployedModel,InferenceCall,InferenceRequest,- ModelActivation,Project,ProjectMembership,User,@@ -27,7 +25,7 @@ from overbae.models import (from overbae.services import inference_live, inference_requestsfrom overbae.services.mcp.server import create_mcp_application-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]@pytest.fixture@@ -75,16 +73,7 @@ def infer(serving, **overrides):return result-def provider_response(content="Hello", finish_reason="stop"):- return Mock(- ok=True,- json=lambda: {- "choices": [{"message": {"content": content}, "finish_reason": finish_reason}],- "usage": {"prompt_tokens": 8, "completion_tokens": 12, "total_tokens": 20},- },- )--+@asgi_dbdef test_decision_rest_and_mcp_share_typed_durable_inference(serving, fake_modal):model = serving.modelmodel.inference_contract = "decision"@@ -148,49 +137,7 @@ def test_decision_rest_and_mcp_share_typed_durable_inference(serving, fake_modal)- "budget", [{}, {"max_tokens": None}, {"max_tokens": 4096}, {"max_tokens": 12000}]-)-def test_mcp_and_production_preserve_the_same_output_reservation(serving, monkeypatch, budget):- post = Mock(side_effect=lambda *args, **kwargs: provider_response())- monkeypatch.setattr("overbae.services.inference_client.requests.post", post)- result = infer(serving, **budget)- assert not result.get("isError"), result- request = InferenceRequest.objects.get(pk=result["structuredContent"]["job"]["id"])- mcp_budget = request.payload["max_tokens"]- post.assert_not_called()-- api = APIClient()- api.force_authenticate(user=serving.user, token=serving.token)- response = api.post(- "/api/v1/chat/completions",- {- "model": serving.model.model_id,- "messages": [{"role": "user", "content": "Hello"}],- **budget,- },- format="json",- )- assert response.status_code == 200, response.data- assert mcp_budget == post.call_args.kwargs["json"]["max_tokens"]- assert mcp_budget == (budget.get("max_tokens") or DEFAULT_OUTPUT_TOKENS)- assert post.call_count == 1- assert (- InferenceCall.objects.filter(deployed_model=serving.model, outcome="succeeded").count() == 1- )--[email protected]("budget", [0, -1, True, "8192", 1.5])-def test_mcp_rejects_invalid_output_reservations_before_inference(serving, monkeypatch, budget):- post = Mock()- monkeypatch.setattr("overbae.services.inference_client.requests.post", post)- result = infer(serving, max_tokens=budget)- assert result["isError"]- assert result["structuredContent"]["error"]["code"] == "invalid_input"- post.assert_not_called()- assert not InferenceCall.objects.filter(deployed_model=serving.model).exists()--+@asgi_dbdef test_mcp_context_rejection_is_non_retryable_and_preserves_the_requested_budget(serving, monkeypatch):@@ -226,107 +173,68 @@ def test_mcp_context_rejection_is_non_retryable_and_preserves_the_requested_budgassert InferenceRequest.objects.get(pk=request_id).payload["max_tokens"] == 16000[email protected]("budget", [16384, 20000])-def test_mcp_rejects_impossible_output_budget_without_waking_a_worker(serving, monkeypatch, budget):- post = Mock()- monkeypatch.setattr("overbae.services.inference_client.requests.post", post)- result = infer(serving, max_tokens=budget)- assert result["isError"]- error = result["structuredContent"]["error"]- assert error["code"] == "context_length_exceeded"- assert error["retryable"] is False- post.assert_not_called()+def chat(settings):+ settings.STRIPE_SECRET_KEY = ""+ context = mcp_context(permission=["read", "write"])+ model = DeployedModel.objects.create(+ project=context.project, model_id="ft-mcp-chat", status="ready", max_model_len=16384+ )+ return context, model- "content,finish_reason,truncated,clipped",- [- ("partial", "length", True, False),- ("x" * 32001, "stop", False, True),- ],-)-def test_large_budgets_keep_generation_truncation_separate_from_response_clipping(- serving, monkeypatch, content, finish_reason, truncated, clipped-):- monkeypatch.setattr(- "overbae.services.inference_client.requests.post",- Mock(return_value=provider_response(content, finish_reason)),- )- result = infer(serving, max_tokens=12000)- assert not result.get("isError"), result- request_id = result["structuredContent"]["job"]["id"]- monkeypatch.setattr(inference_requests, "spawn", lambda request: "fc-test")- monkeypatch.setattr(- inference_requests,- "poll",- lambda call_id: (- "complete",- {"content": content, "finish_reason": finish_reason, "latency_ms": 10},- ),+def run_chat(chat, **arguments):+ context, model = chat+ return call_tool(+ "run_inference",+ {+ "deployment": str(model.pk),+ "request_key": uuid.uuid4().hex,+ "messages": [{"role": "user", "content": "Hello"}],+ **arguments,+ },+ context,)- inference_requests.advance(request_id)- inference_requests.advance(request_id)- output = rpc(- serving,- "tools/call",- {"name": "get_job", "arguments": {"kind": "inference_request", "id": request_id}},- )["result"]["structuredContent"]["details"]["result"]- assert output["finish_reason"] == finish_reason- assert output["truncated"] is truncated- assert output["content_clipped"] is clipped- assert output["content"] == content[:32000]++[email protected]("budget", [16384, 20000])+def test_an_output_budget_that_fills_the_context_is_refused_before_a_request_exists(chat, budget):+ error = run_chat(chat, max_tokens=budget).structuredContent["error"]+ assert error["code"] == "context_length_exceeded"+ assert error["retryable"] is False+ assert not InferenceRequest.objects.exists()@pytest.mark.parametrize(- "runners,recent,warming,expected",- [- (1, False, False, "warm"),- (0, False, False, "asleep"),- (0, False, True, "warming"),- (None, False, False, "unknown"),- (None, True, False, "warm"),- (None, False, True, "warming"),- ],+ ("content", "finish_reason", "truncated", "clipped"),+ [("partial", "length", True, False), ("x" * 32001, "stop", False, True)],+ ids=["truncated", "clipped"],)-def test_read_only_mcp_deployment_exposes_current_worker_state(- serving, monkeypatch, runners, recent, warming, expected+def test_a_truncated_generation_and_a_clipped_reply_read_differently(+ chat, fake_modal, content, finish_reason, truncated, clipped):- serving.key, _ = APIToken.create_for_user(- serving.user, project=serving.project, permission=["read"]- )- serving.model.gpu_type = "A100-80GB"- serving.model.weights_path = "/weights/mcp-serving"- serving.model.warming_started_at = timezone.now() if warming else None- serving.model.save()- if recent:- InferenceCall.objects.create(deployed_model=serving.model, project=serving.project)- stats = AsyncMock(- return_value={- "backlog": 0,- "num_running_inputs": 0,- "num_total_runners": runners,- "available": True,- }+ fake_modal.deploy(+ "overmind-inference",+ "inference_request",+ lambda request_id, payload: {+ "content": content,+ "finish_reason": finish_reason,+ "usage": {"prompt_tokens": 1, "completion_tokens": 1},+ "latency_ms": 10,+ },)- if runners is None:- stats.side_effect = RuntimeError("provider secret body")- monkeypatch.setattr(inference_live, "_bounded_worker_stats", stats)- result = rpc(- serving,- "resources/read",- {"uri": f"overmind://deployments/{serving.model.pk}?period=24h&source=application"},- )["result"]- payload = json.loads(result["contents"][0]["text"])- assert payload["status"] == "ready"- assert payload["worker"]["state"] == expected- assert payload["worker"]["available"] is (runners is not None)- assert payload["worker"]["num_total_runners"] == runners- assert payload["worker"]["recently_active"] is recent- assert payload["metrics"]["request_count"] == 0- assert "provider secret" not in json.dumps(payload)- assert stats.await_count == 1--+ job = run_chat(chat, max_tokens=12000).structuredContent["job"]+ inference_requests.advance(job["id"])+ inference_requests.advance(job["id"])+ read = call_tool("get_job", {"kind": "inference_request", "id": job["id"]}, chat[0])+ result = read.structuredContent["details"]["result"]+ assert result["finish_reason"] == finish_reason+ assert result["truncated"] is truncated+ assert result["content_clipped"] is clipped+ assert result["content"] == content[:32000]+++@asgi_dbdef test_worker_resource_checks_project_before_remote_measurements(serving, monkeypatch):foreign = Project.objects.create(name="Other", slug="other-serving")model = DeployedModel.objects.create(@@ -339,12 +247,7 @@ def test_worker_resource_checks_project_before_remote_measurements(serving, monkstats.assert_not_awaited()-def test_activation_metadata_declares_external_verification(serving):- result = rpc(serving, "tools/list", {})["result"]- tool = next(tool for tool in result["tools"] if tool["name"] == "set_active_model")- assert tool["annotations"]["openWorldHint"] is True--+@asgi_dbdef test_job_poll_exposes_deployment_stage_and_status_change_time(serving):now = timezone.now()serving.model.status = "warming"@@ -360,24 +263,3 @@ def test_job_poll_exposes_deployment_stage_and_status_change_time(serving):assert result["progress"]["stage"] == "warm"assert result["progress"]["deadline"] == serving.model.deployment_deadline.isoformat()assert result["updated_at"] == now.isoformat().replace("+00:00", "Z")---def test_activation_poll_exposes_deadline_without_claiming_worker_progress(serving):- now = timezone.now()- capability = Capability.objects.create(project=serving.project, name="Test", slug="test")- activation = ModelActivation.objects.create(- capability=capability,- target=serving.model,- stage="verifying",- started_at=now,- next_poll_at=now + timedelta(seconds=15),- deadline=now + timedelta(minutes=50),- )- result = rpc(- serving,- "tools/call",- {"name": "get_job", "arguments": {"kind": "model_activation", "id": str(activation.id)}},- )["result"]["structuredContent"]- assert result["progress"]["deadline"] == activation.deadline.isoformat()- assert result["progress"]["next_poll_at"] == activation.next_poll_at.isoformat()- assert result["updated_at"] is Nonediff --git a/tests/test_mcp_instrumentation.py b/tests/test_mcp_instrumentation.pyindex 488b13b6..db526d20 100644--- a/tests/test_mcp_instrumentation.py+++ b/tests/test_mcp_instrumentation.py@@ -1,17 +1,15 @@from __future__ import annotations-import asyncioimport uuidimport pytestfrom factories import make_matrix_row-from mcp_fixtures import mcp_context+from mcp_fixtures import call_tool, mcp_context-from overbae.models import Capability, EvalScore, Span-from overbae.services.mcp.catalog import CATALOG+from overbae.models import Capability, Spanfrom overbae.services.mcp.context import MCPContext-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("sdk-wire")]TOOLS = ("get_instrumentation_plan", "verify_instrumentation")@@ -43,61 +41,7 @@ def _span(def _call(name: str, context: MCPContext, arguments: dict):- return asyncio.run(CATALOG.call(name, arguments, context))---def test_catalog_exposes_both_tools_as_read_only():- definitions = {definition.name: definition for definition in CATALOG.definitions()}- assert {tool.name for tool in CATALOG.tools(frozenset({"read"}))} >= set(TOOLS)- for name in TOOLS:- tool = definitions[name].as_mcp_tool()- assert tool.annotations.readOnlyHint is True- assert tool.annotations.destructiveHint is False- assert tool.annotations.openWorldHint is False---def test_plan_places_decorators_from_card_anchors_entry_point_first():- context = mcp_context()- capability = _capability(- context,- anchors=[- {"qualname": "support.tools.lookup", "kind": "tool", "file": "support/tools.py"},- {- "qualname": "support.agent.Agent.run",- "kind": "entry_point",- "file": "support/agent.py#L4",- },- {"qualname": "support.misc.helper", "kind": "unknown", "file": "support/misc.py"},- ],- )-- placements = _call("get_instrumentation_plan", context, {"capability": capability.slug})-- assert placements.isError is False- rows = placements.structuredContent["placements"]- assert [row["kind"] for row in rows] == ["entry_point", "function", "tool"]- assert rows[0]["required_decorator"] == (- f'@overmind.entry_point(capability_id="{capability.id}")'- )- assert rows[0]["target"] == {- "file": "support/agent.py",- "qualname": "support.agent.Agent.run",- "module": "support.agent",- "import_line": "from support.agent import Agent",- }---def test_plan_is_project_wide_without_a_capability():- context = mcp_context()- for name in ("Billing", "Support"):- _capability(context, name, anchors=[{"qualname": f"{name}.run", "kind": "entry_point"}])-- result = _call("get_instrumentation_plan", context, {})-- assert [row["capability"] for row in result.structuredContent["placements"]] == [- "Billing",- "Support",- ]+ return call_tool(name, arguments, context)def test_plan_without_anchors_asks_for_setup():@@ -110,6 +54,7 @@ def test_plan_without_anchors_asks_for_setup():assert output["human_action"]["code"] == "instrumentation_registry_empty"[email protected]("tenancy")def test_plan_and_verify_are_project_isolated():context = mcp_context()foreign = _capability(mcp_context(), "Foreign")@@ -123,62 +68,6 @@ def test_plan_and_verify_are_project_isolated():assert verify.structuredContent["error"]["code"] == "capability_not_found"-def test_verify_passes_a_complete_run_without_writes():- context = mcp_context()- capability = _capability(context)- make_matrix_row(context.project, "Answers", capability=capability)- root = _span(**{"overmind.capability.id": str(capability.id), "input": "hi", "output": "hello"})- counts = (Span.objects.count(), EvalScore.objects.count())-- output = _call("verify_instrumentation", context, {"spans": [root]}).structuredContent-- assert output["ok"] is True- [result] = output["capabilities"]- assert result["capability_id"] == str(capability.id)- assert set(result["checks"].values()) == {"ok"}- assert result["spans"][0]["rows"] == ["Answers"]- assert counts == (Span.objects.count(), EvalScore.objects.count())---def test_verify_names_each_missing_piece():- context = mcp_context()- capability = _capability(context)- Capability.objects.filter(pk=capability.pk).update(- improvement_metadata={"capability_card": {"tool_spec": [{"name": "lookup"}]}}- )- trace_id = uuid.uuid4().hex- spans = [_span(trace_id=trace_id), _span(trace_id=trace_id)]-- output = _call(- "verify_instrumentation", context, {"capability": capability.slug, "spans": spans}- ).structuredContent-- assert output["ok"] is False- [result] = output["capabilities"]- assert {item["check"] for item in result["punch_list"]} == {- "root",- "input",- "output",- "tools",- "scored_rows",- }---def test_verify_treats_an_empty_captured_payload_as_missing():- context = mcp_context()- capability = _capability(context)- make_matrix_row(context.project, "Answers", capability=capability)- root = _span(- **{"overmind.capability.id": str(capability.id), "inputs": "{}", "outputs": '"hello"'}- )-- output = _call("verify_instrumentation", context, {"spans": [root]}).structuredContent-- [result] = output["capabilities"]- assert result["checks"]["input"] == "missing"- assert result["checks"]["output"] == "ok"--def test_verify_reports_malformed_spans_and_rejects_a_json_string():context = mcp_context()@@ -190,16 +79,6 @@ def test_verify_reports_malformed_spans_and_rejects_a_json_string():assert encoded.structuredContent["error"]["code"] == "invalid_input"-def test_verify_bounds_caller_spans():- context = mcp_context()-- at_limit = _call("verify_instrumentation", context, {"spans": [_span() for _ in range(100)]})- too_many = _call("verify_instrumentation", context, {"spans": [{} for _ in range(101)]})-- assert at_limit.isError is False- assert too_many.structuredContent["error"]["code"] == "invalid_input"--def test_verify_grades_an_ingested_trace_beyond_the_caller_bound():context = mcp_context()capability = _capability(context)diff --git a/tests/test_mcp_manifest.py b/tests/test_mcp_manifest.pyindex 807340eb..44238a4c 100644--- a/tests/test_mcp_manifest.py+++ b/tests/test_mcp_manifest.py@@ -2,10 +2,13 @@ from __future__ import annotationsimport json+import pytestfrom mcp_fixtures import EXPECTED_TOOL_NAMES, MAX_MANIFEST_BYTESfrom overbae.services.mcp.catalog import CATALOG+pytestmark = pytest.mark.covers("mcp-surface")+SECRET_INPUT_PARTS = {"access_token","api_key",diff --git a/tests/test_mcp_model_catalog.py b/tests/test_mcp_model_catalog.pyindex 822823f8..e97f6164 100644--- a/tests/test_mcp_model_catalog.py+++ b/tests/test_mcp_model_catalog.py@@ -1,10 +1,10 @@from __future__ import annotations-import asynciofrom unittest.mock import Mockimport pytestfrom django.test import override_settings+from mcp_fixtures import call_toolfrom overbae.models import APIToken, Project, Userfrom overbae.services.finetuning_catalog import fetch_finetuning_model_catalog@@ -12,6 +12,8 @@ from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContextfrom overbae.services.mcp.contracts.model_catalog import GetModelCatalogOutput+pytestmark = pytest.mark.covers("mcp-surface")+@pytest.fixture(autouse=True)def openrouter_catalog(monkeypatch):@@ -29,7 +31,7 @@ def _context(permission: str = "read") -> MCPContext:def _call(arguments: dict, *, permission: str = "read"):- return asyncio.run(CATALOG.call("get_model_catalog", arguments, _context(permission)))+ return call_tool("get_model_catalog", arguments, _context(permission))def test_catalog_metadata_and_input_schema_are_read_only_and_bounded():diff --git a/tests/test_mcp_oauth.py b/tests/test_mcp_oauth.pyindex 8a99d11d..2ea836db 100644--- a/tests/test_mcp_oauth.py+++ b/tests/test_mcp_oauth.py@@ -8,13 +8,14 @@ from urllib.parse import parse_qs, urlsplitimport pytestfrom django.utils import timezone+from mcp_fixtures import asgi_dbfrom rest_framework.test import APIClientfrom starlette.testclient import TestClientfrom overbae.models import MCPOAuthGrant, MCPOAuthToken, Project, ProjectMembership, Userfrom overbae.services.mcp.server import create_mcp_application-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("authentication")]RESOURCE = "http://localhost:8000/api/mcp/"CALLBACK = "https://client.example.test/callback"@@ -98,6 +99,7 @@ def mcp(client, access_token, name="list_projects", arguments=None):)+@asgi_dbdef test_oauth_discovery_consent_project_access_refresh_and_revoke(flow):client, _, _, client_id = flowchallenge = client.post("/api/mcp/")@@ -144,6 +146,7 @@ def test_oauth_discovery_consent_project_access_refresh_and_revoke(flow):assert mcp(client, tokens["access_token"]).status_code == 401+@asgi_db@pytest.mark.parametrize("tampering",[@@ -160,6 +163,7 @@ def test_oauth_rejects_invalid_code_exchange_without_consuming_code(flow, tamperassert client.post("/token", data=payload).status_code == 400+@asgi_dbdef test_refresh_replay_revokes_family_and_disabled_owner_loses_access(flow):client, _, user, client_id = flowtokens = client.post("/token", data=authorize(flow)).json()@@ -178,6 +182,7 @@ def test_refresh_replay_revokes_family_and_disabled_owner_loses_access(flow):assert mcp(client, tokens["access_token"]).status_code == 401+@asgi_dbdef test_oauth_registration_rejects_unsafe_redirects(flow):client, _, _, _ = flowfor uri in [@@ -191,6 +196,7 @@ def test_oauth_registration_rejects_unsafe_redirects(flow):assert result.status_code == 400+@asgi_dbdef test_consent_requires_account_sign_in_and_cannot_be_replayed(flow):client, api, user, client_id = flowresponse = client.get(@@ -230,6 +236,7 @@ def test_consent_requires_account_sign_in_and_cannot_be_replayed(flow):assert api.post("/api/mcp-oauth/consent/", {"request": raw, "approve": True}).status_code == 400+@asgi_dbdef test_expired_codes_tokens_and_wrong_resource_are_rejected(flow):client, _, _, _ = flowpayload = authorize(flow)@@ -243,6 +250,7 @@ def test_expired_codes_tokens_and_wrong_resource_are_rejected(flow):assert mcp(client, tokens["access_token"]).status_code == 401+@asgi_dbdef test_refresh_cannot_expand_scopes_or_change_client(flow):client, _, _, client_id = flowtokens = client.post("/token", data=authorize(flow)).json()@@ -262,6 +270,7 @@ def test_refresh_cannot_expand_scopes_or_change_client(flow):assert client.post("/token", data=payload).status_code == 200+@asgi_dbdef test_connection_refreshes_after_years_until_revoked(flow, monkeypatch):client, _, _, client_id = flowtokens = client.post("/token", data=authorize(flow)).json()diff --git a/tests/test_mcp_observability.py b/tests/test_mcp_observability.pyindex 9c142f85..82efea38 100644--- a/tests/test_mcp_observability.py+++ b/tests/test_mcp_observability.py@@ -1,9 +1,10 @@from __future__ import annotations-import asyncioimport uuidimport pytest+from asgiref.sync import async_to_sync+from mcp_fixtures import call_toolfrom overbae.models import (APIToken,@@ -20,7 +21,7 @@ from overbae.models import (from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]def _context() -> tuple[MCPContext, Capability, Dataset]:@@ -74,7 +75,7 @@ def test_all_tools_return_structured_content_and_project_scoped_rows():results.append(await CATALOG.call(name, args, context))return results- results = asyncio.run(invoke())+ results = async_to_sync(invoke)()for (name, _), result in zip(calls, results, strict=True):assert result.isError is False, (name, result.content, result.structuredContent)assert all(result.structuredContent for result in results)@@ -94,18 +95,6 @@ def test_all_tools_return_structured_content_and_project_scoped_rows():assert dataset_job["id"] == str(dataset.id)-def test_invalid_tool_input_is_safe_and_typed():- context, _, _ = _context()-- async def invoke():- return await CATALOG.call("query_traces", {"unexpected": True}, context)-- result = asyncio.run(invoke())- assert result.isError is True- assert result.structuredContent["error"]["code"] == "invalid_input"- assert "ValidationError" not in result.content[0].text--def test_query_failures_includes_failed_check_when_span_average_passes():context, capability, _ = _context()Span.objects.create(@@ -124,7 +113,7 @@ def test_query_failures_includes_failed_check_when_span_average_passes():},)- result = asyncio.run(CATALOG.call("query_failures", {"capability": "support"}, context))+ result = call_tool("query_failures", {"capability": "support"}, context)assert result.isError is Falseassert result.structuredContent["failures"][0]["failed_scores"] == [@@ -182,7 +171,7 @@ def test_query_traces_exact_session_counts_root_traces():context,)- result = asyncio.run(invoke())+ result = async_to_sync(invoke)()assert result.isError is Falseassert result.structuredContent["page"]["total"] == 2diff --git a/tests/test_mcp_optimizer.py b/tests/test_mcp_optimizer.pyindex 034a4619..15991dbd 100644--- a/tests/test_mcp_optimizer.py+++ b/tests/test_mcp_optimizer.py@@ -1,33 +1,31 @@from __future__ import annotations-import asyncioimport jsonimport uuidimport pytest+from asgiref.sync import async_to_syncfrom conftest import EVAL_ROWS, frozen_dataset-from mcp_fixtures import mcp_context+from mcp_fixtures import call_tool, mcp_contextfrom overbae.models import (Capability,- Cell,Dataset,EvalSet,OptimizerCandidate,OptimizerExperiment,OptimizerIteration,)-from overbae.services.datasets import paths, storefrom overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext, bind_contextfrom overbae.services.mcp.contracts.optimizer import InspectOptimizerResultOutputfrom overbae.services.mcp.resources import read_resource-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]def _call(name: str, arguments: dict, context: MCPContext):- return asyncio.run(CATALOG.call(name, arguments, context))+ return call_tool(name, arguments, context)def _ready_objects(context: MCPContext):@@ -56,6 +54,7 @@ def _experiment(context: MCPContext, *, status: str | None = None) -> OptimizerE)[email protected]("authentication")def test_read_only_key_hides_and_denies_optimizer_writes():context = mcp_context()visible = {tool.name for tool in CATALOG.tools(frozenset({"read"}))}@@ -89,27 +88,7 @@ def test_readiness_reports_wrong_dataset_intent_and_executioner_state():assert output["executioner"]["connected"] is False-def test_start_calls_shared_create_service_and_returns_cli_next_step():- context = mcp_context(permission=["read", "write"])- capability, dataset, eval_set = _ready_objects(context)- result = _call(- "start_optimizer",- {"capability": capability.slug, "dataset": str(dataset.id)},- context,- )-- assert result.isError is False- output = result.structuredContent- experiment = OptimizerExperiment.objects.get(pk=output["experiment_id"])- assert experiment.openrouter_key_source == OptimizerExperiment.OpenRouterKeySource.PLATFORM- assert experiment.capability == capability- assert output["job"]["id"] == output["experiment_id"]- assert output["experiment"]["cell"]["id"] == str(dataset.active_cell.id)- assert output["experiment"]["cell"]["rows"] == dataset.active_cell.rows- assert output["next_action"]["state"] == "run_executioner"- assert f"start -e {output['experiment_id']}" in output["next_action"]["command"]--[email protected]("tenancy")def test_cross_project_experiment_is_inaccessible():context = mcp_context()other = mcp_context()@@ -186,6 +165,7 @@ def test_inspect_is_bounded_typed_and_exposes_winner_state():assert output.winner.candidate_id == str(winner.id)[email protected]("privacy")def test_optimizer_resource_is_bounded_and_does_not_leak_key_values():context = mcp_context()experiment = _experiment(context)@@ -199,47 +179,8 @@ def test_optimizer_resource_is_bounded_and_does_not_leak_key_values():contents = list(await read_resource(uri))return contents[0].content- payload = json.loads(asyncio.run(read()))+ payload = json.loads(async_to_sync(read)())assert "secret-value" not in json.dumps(payload)assert "iterations" in payloadassert "executioner" in payloadassert "next_action" in payload---def test_readiness_and_start_use_explicit_eval_cell(monkeypatch):- context = mcp_context(permission=["read", "write"])- capability, dataset, eval_set = _ready_objects(context)- extra = Cell.objects.create(- dataset=dataset,- position=1,- title="shaped",- state=Cell.State.OK,- rows=11,- fingerprint=f"fp-opt-{uuid.uuid4().hex[:8]}",- intent_report={"eval": {"ok": True, "reason": ""}},- capability_report={"ok": True, "reason": ""},- )- path = paths.cell_path(dataset.id, extra.id)- store.write_rows(- path,- [- {"source_row": i, "input": f"q{i}", "expected_output": f"a{i}"}- for i in range(extra.rows)- ],- )- extra.fingerprint = store.file_sha256(path)- extra.save(update_fields=["fingerprint"])- result = _call(- "start_optimizer",- {- "capability": capability.slug,- "dataset": str(dataset.id),- "cell": str(extra.id),- },- context,- )- assert result.isError is False, result.structuredContent- experiment = OptimizerExperiment.objects.get(pk=result.structuredContent["experiment_id"])- assert experiment.cell_id == extra.id- assert result.structuredContent["experiment"]["cell"]["id"] == str(extra.id)- assert result.structuredContent["experiment"]["cell"]["rows"] == 11diff --git a/tests/test_mcp_prompts.py b/tests/test_mcp_prompts.pyindex 9443ee33..b4e6b0f1 100644--- a/tests/test_mcp_prompts.py+++ b/tests/test_mcp_prompts.py@@ -6,13 +6,14 @@ import uuidimport pytestfrom mcp import typesfrom mcp.shared.exceptions import McpError+from mcp_fixtures import asgi_dbfrom starlette.testclient import TestClientfrom overbae.models import APIToken, Project, ProjectMembership, Userfrom overbae.services.mcp.prompts import PROMPTS, get_prompt, list_promptsfrom overbae.services.mcp.server import create_mcp_application-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]MCP_URL = "/api/mcp/"@@ -61,6 +62,7 @@ def _arguments(prompt: types.Prompt) -> dict[str, str]:return {argument.name: values.get(argument.name, "") for argument in prompt.arguments or []}+@asgi_dbdef test_lists_the_small_prompt_manifest_over_transport():raw_key = _token()diff --git a/tests/test_mcp_research_journey.py b/tests/test_mcp_research_journey.pyindex 2052562e..da5c5661 100644--- a/tests/test_mcp_research_journey.py+++ b/tests/test_mcp_research_journey.py@@ -5,7 +5,9 @@ from datetime import timedeltafrom unittest.mock import patchimport pytest+from django.test import TestCasefrom django.utils import timezone+from mcp_fixtures import asgi_dbfrom rest_framework.test import APIClientfrom starlette.testclient import TestClientfrom test_data_first_workflow import workspace@@ -22,14 +24,13 @@ from overbae.models import (User,)from overbae.services import native_evaluation, native_evaluation_monitor, training_experiments-from overbae.services.datasets import exploration, land, paths, rows, store+from overbae.services.datasets import exploration, land, rows, storefrom overbae.services.datasets.exploration import advancefrom overbae.services.decision_providers import external_step-from overbae.services.mcp import CONTRACT_VERSIONfrom overbae.services.mcp.server import create_mcp_applicationfrom overbae.tasks.native_evaluation import advance_plan-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("measured-facts")]def call(client, key, name, arguments):@@ -49,39 +50,7 @@ def call(client, key, name, arguments):return result.get("structuredContent") or json.loads(result["content"][0]["text"])[email protected]("tool", ["derive_dataset", "explore_dataset"])-def test_exploration_request_recovery_survives_profiler_upgrade(tool):- project, _, dataset = workspace()- key, _ = APIToken.create_for_user(- project.memberships.first().user, project=project, permission=["read", "write"]- )- arguments = {- "name": "Frozen request",- "source_cell": str(dataset.active_cell.pk),- "request_key": "recover-after-profiler-upgrade",- }- with (- TestClient(create_mcp_application()) as client,- patch("overbae.tasks.data_exploration.run.delay"),- ):- with patch.object(exploration, "PROFILE_VERSION", 1):- original = call(client, key, tool, arguments)- advance(original["workflow"]["id"])- with patch.object(exploration, "PROFILE_VERSION", 2):- recovered = call(client, key, tool, arguments)- assert recovered["workflow"]["id"] == original["workflow"]["id"]- fresh = call(- client, key, tool, {**arguments, "request_key": "new-profiler-measurement"}- )- advance(fresh["workflow"]["id"])- measured = call(- client, key, "get_job", {"kind": "data_exploration", "id": fresh["workflow"]["id"]}- )- assert measured["status"] == "completed"- if tool == "explore_dataset":- assert "reused_from" not in measured["progress"]["report"]--+@asgi_dbdef test_training_draft_validation_names_the_recipe_correction_without_log_access(settings):settings.FINETUNING_BACKEND = "modal"project, _, dataset = workspace()@@ -126,6 +95,7 @@ def test_training_draft_validation_names_the_recipe_correction_without_log_accesassert job["progress"]["jobs"] == []+@asgi_dbdef test_unmeasured_forecast_explains_budget_stop_before_a_launch_attempt(settings):settings.FINETUNING_BACKEND = "modal"project, _, dataset = workspace()@@ -167,6 +137,7 @@ def test_unmeasured_forecast_explains_budget_stop_before_a_launch_attempt(settinassert quote["trained_tokens"] >= 0+@asgi_dbdef test_fresh_mcp_client_derives_and_profiles_exact_parent_without_changing_it():project, _, dataset = workspace()@@ -281,74 +252,7 @@ def test_target_sampling_profiles_mean_and_probability_supervision():]-def test_mcp_derives_historical_chat_source_with_tool_messages_and_lineage():- project, _, _ = workspace()- dataset = Dataset.objects.create(project=project, name="Support conversations", intent="train")- messages = [- {"role": "user", "content": "Find the delivery"},- {- "role": "assistant",- "content": None,- "tool_calls": [- {- "id": "lookup",- "type": "function",- "function": {"name": "lookup", "arguments": '{"order":"123"}'},- }- ],- },- {"role": "tool", "tool_call_id": "lookup", "content": "Arrives Monday"},- {"role": "assistant", "content": "Your order arrives Monday."},- ]- land.land_rows(dataset, [{"messages": messages, "group_id": "same-session"}] * 2)- dataset.refresh_from_db()- original = dataset.active_cell- from conftest import import_version-- latest = import_version(- dataset,- store.head(paths.cell_path(dataset.pk, dataset.source.pk), 1),- name="One conversation",- )- dataset.refresh_from_db()- assert dataset.active_cell.pk == latest.pk- assert dataset.active_cell.rows == 1- key, _ = APIToken.create_for_user(- project.memberships.first().user, project=project, permission=["read", "write"]- )- with (- TestClient(create_mcp_application()) as client,- patch("overbae.tasks.data_exploration.run.delay"),- ):- receipt = call(- client,- key,- "derive_dataset",- {- "source_cell": str(original.pk),- "name": "Full conversations",- "request_key": "chat-parent",- },- )- advance(receipt["workflow"]["id"])- status = call(- client, key, "get_job", {"kind": "data_exploration", "id": receipt["workflow"]["id"]}- )- assert status["status"] == "completed"- derived = Dataset.objects.get(pk=status["progress"]["output_dataset"])- records = list(store.iter_rows(rows.frame_path(derived.active_cell)))- assert len(records) == 2- assert all(record["messages"] == messages for record in records)- assert all(record["group_id"] == "same-session" for record in records)- assert [record["_overmind_provenance"]["derived_from"]["row"] for record in records] == [0, 1]- assert all(- record["_overmind_provenance"]["derived_from"]["cell"] == str(original.pk)- for record in records- )- dataset.refresh_from_db()- assert dataset.active_cell.pk == latest.pk--+@asgi_dbdef test_mcp_comparison_draft_requires_explicit_launch_and_resumes_after_reconnect():project, _, dataset = workspace()@@ -395,42 +299,6 @@ def test_mcp_comparison_draft_requires_explicit_launch_and_resumes_after_reconneassert dispatch.call_count == 1-def test_independent_comparison_stages_survive_one_failed_arm_and_pause():-- project, _, dataset = workspace()- dataset.intent = "eval"- dataset.save()- plan = native_evaluation.create_plan(- project,- name="Independent arms",- request_key="independent",- final_cell=dataset.active_cell,- baseline="first",- participants=[- {"key": key, "name": key, "kind": "external", "model": "typesafe/jev-1.13"}- for key in ("first", "second")- ],- )- with patch("overbae.tasks.native_evaluation.advance_plan.delay"):- plan = native_evaluation.launch(plan)- native_evaluation.advance(plan.pk, stage="verify_inputs")- plan.refresh_from_db()- assert native_evaluation.ready_stages(plan) == ["final_first", "final_second"]- with patch(- "overbae.services.native_evaluation.external_step",- side_effect=ValueError("invalid stored response"),- ):- native_evaluation.advance(plan.pk, stage="final_first")- plan.refresh_from_db()- assert native_evaluation.ready_stages(plan) == ["final_second"]- native_evaluation.pause(plan)- plan.refresh_from_db()- assert native_evaluation.ready_stages(plan) == []- with patch("overbae.services.native_evaluation.external_step") as submit:- native_evaluation.advance(plan.pk, stage="final_second")- submit.assert_not_called()--def test_saved_prediction_reuse_is_explicit_and_refuses_changed_conditions():source, participant, _ = fixture()@@ -502,7 +370,10 @@ def test_expired_stage_lease_is_reconciled_after_worker_loss():}}plan.save()- with patch.object(advance_plan, "apply_async") as queued:+ with (+ patch.object(advance_plan, "apply_async") as queued,+ TestCase.captureOnCommitCallbacks(execute=True),+ ):advance_plan(str(plan.pk))assert queued.call_count >= 1native_evaluation.advance(plan.pk, stage="verify_inputs")@@ -545,6 +416,7 @@ def test_exploration_reports_allocation_and_can_retry_failed_local_work():assert op.report["measurement"]["population"] == "whole_source"+@asgi_dbdef test_label_breakdown_is_shared_by_rest_and_mcp_without_soft_target_accuracy(tmp_path, settings):settings.MEDIA_ROOT = tmp_pathsettings.STRIPE_SECRET_KEY = ""@@ -639,26 +511,3 @@ def test_label_breakdown_is_shared_by_rest_and_mcp_without_soft_target_accuracy(foreign = Project.objects.create(name="Other label project", slug="other-label-project")NativeEvaluationPlan.objects.filter(pk=plan.pk).update(project=foreign)assert rest.get(endpoint, query).status_code == 404---def test_account_client_discovers_interface_without_selecting_a_project():-- user = User.objects.create_user(email="[email protected]")- key, _ = APIToken.create_for_user(user, permission=["read"])- with TestClient(create_mcp_application()) as client:- response = client.post(- "/api/mcp/",- json={- "jsonrpc": "2.0",- "id": 1,- "method": "resources/read",- "params": {"uri": "overmind://interface/current"},- },- headers={"X-Api-Key": key, "Accept": "application/json"},- )- assert response.status_code == 200- body = response.json()- assert "error" not in body, body- resource = json.loads(body["result"]["contents"][0]["text"])- assert resource["contract_version"] == CONTRACT_VERSION- assert len(resource["catalog_sha256"]) == 64diff --git a/tests/test_mcp_resources.py b/tests/test_mcp_resources.pyindex f45e8a82..ed15482a 100644--- a/tests/test_mcp_resources.py+++ b/tests/test_mcp_resources.py@@ -1,11 +1,12 @@from __future__ import annotations-import asyncioimport jsonimport uuidimport pytest+from asgiref.sync import async_to_syncfrom mcp import types+from mcp_fixtures import asgi_db, call_toolfrom starlette.testclient import TestClientfrom overbae.models import (@@ -25,7 +26,6 @@ from overbae.models import (Span,User,)-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext, bind_contextfrom overbae.services.mcp.resources import (read_resource,@@ -35,7 +35,7 @@ from overbae.services.mcp.resources import ()from overbae.services.mcp.server import create_mcp_application-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]def _project() -> tuple[Project, str]:@@ -57,6 +57,7 @@ def _rpc(method: str, params: dict | None = None) -> dict:return payload+@asgi_db@pytest.mark.parametrize(("base_url", "forwarded_proto", "trust_proxy", "expected_scheme"),[@@ -76,6 +77,18 @@ def test_discovery_reports_the_connected_endpoint_and_permission_scoped_catalog(if forwarded_proto:headers["X-Forwarded-Proto"] = forwarded_protowith TestClient(create_mcp_application(), base_url=base_url) as client:+ server = client.post(+ "/api/mcp/",+ json=_rpc(+ "initialize",+ {+ "protocolVersion": "2025-06-18",+ "capabilities": {},+ "clientInfo": {"name": "test", "version": "1"},+ },+ ),+ headers=headers,+ ).json()["result"]["serverInfo"]tools = client.post("/api/mcp/", json=_rpc("tools/list"), headers=headers).json()["result"]["tools"]@@ -92,6 +105,7 @@ def test_discovery_reports_the_connected_endpoint_and_permission_scoped_catalog(identity = json.loads(interface["contents"][0]["text"])assert identity["connection"]["mcp_url"] == f"{expected_scheme}://testserver/api/mcp/"assert identity["tool_count"] == len(tools)+ assert identity["contract_version"] == server["version"]assert projects["connection"] == identity["connection"]assert projects["catalog_sha256"] == identity["catalog_sha256"]assert key not in json.dumps(identity)@@ -115,7 +129,7 @@ def test_project_resource_exposes_scan_provenance():contents = list(await read_resource("overmind://project/current"))return json.loads(contents[0].content)- resource = asyncio.run(read())+ resource = async_to_sync(read)()assert resource["repository_snapshot"] == project.settings["repository_snapshot"]assert resource["last_synced_at"] == project.settings["last_synced_at"]@@ -157,7 +171,7 @@ def test_dataset_upload_resource_describes_cli_flow_and_server_limits():contents = list(await read_resource("overmind://dataset-upload"))return json.loads(contents[0].content)- resource = asyncio.run(read())+ resource = async_to_sync(read)()assert resource["extensions"] == [".csv",".tsv",@@ -195,7 +209,7 @@ def test_dataset_export_resource_describes_local_download_and_trace_flow():contents = list(await read_resource("overmind://dataset-export"))return json.loads(contents[0].content)- resource = asyncio.run(read())+ resource = async_to_sync(read)()assert resource["command"] == "overmind dataset export DATASET --json"assert resource["formats"] == ["jsonl", "csv"]assert "dataset id" in resource["dataset"]@@ -220,7 +234,7 @@ def test_checkpoint_download_resource_describes_cli_boundary_and_availability():contents = list(await read_resource("overmind://checkpoint-download"))return json.loads(contents[0].content)- resource = asyncio.run(read())+ resource = async_to_sync(read)()assert resource["command"] == "overmind model download-checkpoint DEPLOYMENT --json"assert "deployment id supplied by MCP" in resource["deployment"]assert "OVERMIND_API_KEY" in resource["auth"]@@ -246,7 +260,7 @@ def test_connector_setup_resource_describes_human_cli_boundary():contents = list(await read_resource("overmind://connector-setup"))return json.loads(contents[0].content)- resource = asyncio.run(read())+ resource = async_to_sync(read)()encoded = json.dumps(resource)assert resource["command"] == "overmind connector add langfuse --json"assert resource["types"][0]["env"] == ["LANGFUSE_PUBLIC_KEY", "LANGFUSE_SECRET_KEY"]@@ -319,7 +333,7 @@ def test_resource_reads_are_json_and_project_scoped():assert contents[0].mime_type == "application/json"assert '"uri":' in contents[0].content- asyncio.run(read_all())+ async_to_sync(read_all)()@pytest.mark.parametrize(("span_count", "truncated"), [(100, False), (101, True)])@@ -447,7 +461,7 @@ def test_finetune_resource_redacts_all_checkpoint_url_styles():contents = list(await read_resource(f"overmind://finetunes/{job.id}"))return json.loads(contents[0].content)- resource = asyncio.run(read())+ resource = async_to_sync(read)()assert resource["cost_usd"] == 0.25assert resource["group_id"] == str(job.group_id)assert resource["training_objective"] == "decision_cross_entropy"@@ -467,11 +481,12 @@ def test_finetune_resource_redacts_all_checkpoint_url_styles():"Measuring the starting model on the development set before training begins."),}- result = asyncio.run(CATALOG.call("get_job", {"kind": "finetune", "id": str(job.id)}, context))+ result = call_tool("get_job", {"kind": "finetune", "id": str(job.id)}, context)assert result.isError is False, result.structuredContentassert result.structuredContent["progress"] == resource["progress"]+@asgi_dbdef test_resource_read_through_transport_returns_safe_not_found_error():project, raw_key = _project()del project@@ -498,7 +513,7 @@ def _read(project, uri: str) -> dict:contents = list(await read_resource(uri))return json.loads(contents[0].content)- return asyncio.run(read())+ return async_to_sync(read)()def _tool_context(project) -> MCPContext:@@ -582,9 +597,7 @@ def test_get_job_dataset_run_tracks_state_and_emits_job_resource_link():Dataset.objects.filter(pk=dataset.pk).update(state=state, error="clipped-secret" if state == Dataset.State.ERROR else "")- result = asyncio.run(- CATALOG.call("get_job", {"kind": "dataset_run", "id": str(dataset.id)}, context)- )+ result = call_tool("get_job", {"kind": "dataset_run", "id": str(dataset.id)}, context)assert result.isError is False, result.structuredContentbody = result.structuredContentassert body["kind"] == "dataset_run"@@ -617,12 +630,8 @@ def test_dataset_run_job_is_project_scoped():foreign = Dataset.objects.create(project=other, name="Foreign")context = _tool_context(project)- missing = asyncio.run(- CATALOG.call("get_job", {"kind": "dataset_run", "id": str(foreign.id)}, context)- )- retired = asyncio.run(- CATALOG.call("get_job", {"kind": "dataset_build", "id": str(foreign.id)}, context)- )+ missing = call_tool("get_job", {"kind": "dataset_run", "id": str(foreign.id)}, context)+ retired = call_tool("get_job", {"kind": "dataset_build", "id": str(foreign.id)}, context)assert missing.isError is Trueassert missing.structuredContent["error"]["code"] == "resource_not_found"@@ -662,7 +671,7 @@ def test_native_running_resource_retains_latest_metrics_and_contract():contents = list(await read_resource(f"overmind://finetunes/{job.id}"))return json.loads(contents[0].content)- resource = asyncio.run(read())+ resource = async_to_sync(read)()assert resource["inference_contract"] == "decision"assert resource["loss"][-1]["step"] == 250assert resource["progress"]["metrics_history"][-1]["step"] == 250@@ -702,11 +711,12 @@ def test_capability_resource_exposes_tool_branches_and_execution_steps():contents = list(await read_resource(f"overmind://capabilities/{capability.id}"))return json.loads(contents[0].content)- result = asyncio.run(read())+ result = async_to_sync(read)()assert result["tool_spec"][0]["branches"] == [branch]assert result["trajectory_map"] == []+@asgi_dbdef test_eval_set_pages_preserve_complete_sources_and_project_scope():project, key = _project()_, other_key = _project()diff --git a/tests/test_mcp_result_compat.py b/tests/test_mcp_result_compat.pyindex a000b0b5..cf96b523 100644--- a/tests/test_mcp_result_compat.py+++ b/tests/test_mcp_result_compat.py@@ -11,6 +11,8 @@ from overbae.services.mcp.catalog import ToolCatalog, ToolDefinitionfrom overbae.services.mcp.context import MCPContextfrom overbae.services.mcp.errors import MCPError, error_result+pytestmark = pytest.mark.covers("mcp-surface")+class Input(BaseModel):value: strdiff --git a/tests/test_mcp_transport.py b/tests/test_mcp_transport.pyindex 1c40ba9a..7dd42021 100644--- a/tests/test_mcp_transport.py+++ b/tests/test_mcp_transport.py@@ -15,14 +15,14 @@ import httpximport pytestfrom asgiref.sync import sync_to_asyncfrom django.db import connection, transaction-from mcp_fixtures import EXPECTED_TOOL_NAMES, MAX_MANIFEST_BYTES+from mcp_fixtures import EXPECTED_TOOL_NAMES, MAX_MANIFEST_BYTES, asgi_dbfrom starlette.testclient import TestClientfrom overbae.models import APIToken, Capability, Project, ProjectMembership, Span, Userfrom overbae.services.mcp.server import create_mcp_applicationfrom overbae.services.mcp.tools_projects import accessible_projects-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]MCP_URL = "/api/mcp/"@@ -65,6 +65,7 @@ def _application():return create_mcp_application()+@asgi_dbdef test_initialize_uses_official_streamable_http_transport(settings):settings.FRONTEND_URL = "https://console.example.test/workspace/"raw, token = _token()@@ -100,6 +101,7 @@ def test_initialize_uses_official_streamable_http_transport(settings):assert parse_qs(console_url.query) == {"projectId": [str(token.project_id)]}+@asgi_dbdef test_stateless_actions_keep_reported_client_identity_and_shared_keys_stay_ambiguous():from overbae.models import Activity@@ -163,6 +165,7 @@ def test_stateless_actions_keep_reported_client_identity_and_shared_keys_stay_amassert Activity.objects.count() == before+@asgi_dbdef test_transfer_preflight_does_not_register_an_agent_or_obscure_codex():from overbae.models import Activity, ActivityClient@@ -220,6 +223,7 @@ def test_transfer_preflight_does_not_register_an_agent_or_obscure_codex():)+@asgi_dbdef test_ping_is_protocol_level_and_catalog_lists_curated_tools():raw, _ = _token()with TestClient(_application()) as client:@@ -232,6 +236,7 @@ def test_ping_is_protocol_level_and_catalog_lists_curated_tools():assert ping.json()["result"] == {}+@asgi_dbdef test_slow_tool_does_not_block_another_callers_authenticated_request(monkeypatch):slow_key, slow_token = _token()other_key, other_token = _token()@@ -265,6 +270,7 @@ def test_slow_tool_does_not_block_another_callers_authenticated_request(monkeypaassert [p["id"] for p in result["structuredContent"]["projects"]] == [str(token.project_id)]+@asgi_dbdef test_tools_list_is_permission_filtered_and_stays_within_manifest_budget():read_raw, _ = _token(permission=["read"])full_raw, _ = _token()@@ -282,6 +288,7 @@ def test_tools_list_is_permission_filtered_and_stays_within_manifest_budget():assert len(full_response.content) <= MAX_MANIFEST_BYTES+@asgi_dbdef test_resources_and_prompts_list_over_streamable_http():raw, _ = _token()with TestClient(_application()) as client:@@ -301,6 +308,7 @@ def test_resources_and_prompts_list_over_streamable_http():}+@asgi_dbdef test_tool_call_exposes_complete_json_and_resource_links_to_text_only_clients():raw, token = _token(permission=["read"])capability = Capability.objects.create(@@ -350,6 +358,7 @@ def test_tool_call_exposes_complete_json_and_resource_links_to_text_only_clients)+@asgi_dbdef test_initialize_accepts_the_path_with_or_without_a_trailing_slash():raw, _ = _token()body = _rpc(@@ -378,6 +387,7 @@ def test_initialize_accepts_the_path_with_or_without_a_trailing_slash():]+@asgi_dbdef test_initialize_accepts_an_allowed_host_with_a_port():raw, _ = _token()with TestClient(_application()) as client:@@ -391,6 +401,7 @@ def test_initialize_accepts_an_allowed_host_with_a_port():assert response.status_code == 200+@asgi_dbdef test_initialize_allows_any_host_when_allowed_hosts_is_star(settings):settings.ALLOWED_HOSTS = ["*"]raw, _ = _token()@@ -413,6 +424,7 @@ def test_initialize_allows_any_host_when_allowed_hosts_is_star(settings):assert response.json()["result"]["serverInfo"]["name"] == "overmind-platform"+@asgi_dbdef test_unknown_host_is_rejected():raw, _ = _token()with TestClient(_application()) as client:@@ -427,6 +439,7 @@ def test_unknown_host_is_rejected():assert response.json()["error"]["code"] == "invalid_request"+@asgi_dbdef test_unsupported_protocol_version_is_rejected():raw, _ = _token()with TestClient(_application()) as client:@@ -440,6 +453,7 @@ def test_unsupported_protocol_version_is_rejected():assert response.json()["error"]["code"] == "protocol_version_unsupported"+@asgi_dbdef test_origin_is_validated_on_initialize():raw, _ = _token()with TestClient(_application()) as client:@@ -486,6 +500,7 @@ def _a_request_waits_behind(holder_pid: int) -> bool:connection.close()+@asgi_db@pytest.mark.asyncioasync def test_a_request_blocked_in_the_database_does_not_hold_up_other_requests():raw_blocked, blocked = await sync_to_async(_token)()diff --git a/tests/test_mcp_workflow_friction.py b/tests/test_mcp_workflow_friction.pyindex c1802a63..6fe3d6a3 100644--- a/tests/test_mcp_workflow_friction.py+++ b/tests/test_mcp_workflow_friction.py@@ -2,6 +2,7 @@ import jsonfrom unittest.mock import Mock, patchimport pytest+from mcp_fixtures import asgi_dbfrom starlette.testclient import TestClientfrom test_data_first_workflow import workspacefrom test_mcp_research_journey import call@@ -13,9 +14,10 @@ from overbae.services.datasets.partition_plans import build, prepared_member_rowfrom overbae.services.mcp.server import create_mcp_applicationfrom overbae.services.training_forecast import forecast-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]+@asgi_dbdef test_mcp_inspection_is_bounded_paged_and_does_not_profile_on_read(monkeypatch):project, _, dataset = workspace()cell = dataset.active_cell@@ -140,6 +142,7 @@ def test_forecast_distinguishes_current_price_from_missing_duration():assert quote["estimate_blockers"] == ["duration_unmeasured"]+@asgi_dbdef test_inspection_remains_valid_json_for_one_wide_unicode_cell():project, _, dataset = workspace()cell = dataset.active_celldiff --git a/tests/test_migration_history_check.py b/tests/test_migration_history_check.pyindex 5cd6ad88..9426b9ed 100644--- a/tests/test_migration_history_check.py+++ b/tests/test_migration_history_check.py@@ -7,6 +7,8 @@ from pathlib import Pathimport pytest+pytestmark = pytest.mark.covers("migrations")+CHECKER = Path(__file__).resolve().parents[1] / "scripts/check_migrations.py"diff --git a/tests/test_modal_stream_keepalive.py b/tests/test_modal_stream_keepalive.pyindex 7ed7a8bd..cafd4d86 100644--- a/tests/test_modal_stream_keepalive.py+++ b/tests/test_modal_stream_keepalive.py@@ -11,6 +11,8 @@ from overbae.services.inference_client import (InferenceClientError,)+pytestmark = pytest.mark.covers("llm-gateway")+@pytest.mark.asyncioasync def test_gateway_pings_while_waiting_for_worker_headers_and_tokens():diff --git a/tests/test_modal_volume_retention.py b/tests/test_modal_volume_retention.pyindex 9201a7de..eb1c0d2a 100644--- a/tests/test_modal_volume_retention.py+++ b/tests/test_modal_volume_retention.py@@ -11,7 +11,7 @@ from django.utils import timezonefrom overbae.models import DeployedModel, FinetuningJob, Projectfrom overbae.tasks.cleanup_modal import plan_run_retention-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("spend-stops")]def _job(diff --git a/tests/test_model_activation.py b/tests/test_model_activation.pyindex 104abe98..d2df0fe6 100644--- a/tests/test_model_activation.py+++ b/tests/test_model_activation.py@@ -10,7 +10,7 @@ from overbae.services import model_activation as servicefrom overbae.services import operational_progressfrom overbae.services.deployed_chat import is_cold_start, record_inference_call-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]@pytest.fixturediff --git a/tests/test_model_catalog.py b/tests/test_model_catalog.pyindex 5d0eced1..e5ae5003 100644--- a/tests/test_model_catalog.py+++ b/tests/test_model_catalog.py@@ -9,7 +9,7 @@ from rest_framework.test import APIClientfrom overbae.core.llms import call_llmfrom overbae.services import model_catalog-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("llm-gateway")]CATALOG_URL = "/api/models/catalog/"diff --git a/tests/test_model_deployment_resume.py b/tests/test_model_deployment_resume.pyindex 35b597ba..ba51d051 100644--- a/tests/test_model_deployment_resume.py+++ b/tests/test_model_deployment_resume.py@@ -1,10 +1,10 @@-import asyncioimport jsonimport uuidfrom datetime import timedeltafrom unittest.mock import patchimport pytest+from asgiref.sync import async_to_syncfrom conftest import TRAIN_ROWS, frozen_datasetfrom django.utils import timezonefrom factories import make_user@@ -16,7 +16,7 @@ from overbae.services.mcp.context import MCPContext, bind_contextfrom overbae.services.mcp.resources import read_resourcefrom overbae.tasks.inference_controller import reconcile_deployments-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("work-once")]@pytest.fixture@@ -524,7 +524,7 @@ def test_confirmed_stopped_baseline_can_start_fresh_for_a_new_job(deployed, fakeassert fake_modal.spawns() == [][email protected]_db(transaction=True)def test_api_and_mcp_share_progress_without_remote_credentials(deployed, fake_modal):from overbae.api.serializers import DeployedModelSerializer@@ -539,7 +539,7 @@ def test_api_and_mcp_share_progress_without_remote_credentials(deployed, fake_mowith bind_context(context):return list(await read_resource(f"overmind://deployments/{deployed.pk}"))- [content] = asyncio.run(read())+ [content] = async_to_sync(read)()rest = DeployedModelSerializer(deployed).data["deployment_progress"]assert rest == json.loads(content.content)["progress"]assert rest["label"] == "Booting and verifying"diff --git a/tests/test_model_library.py b/tests/test_model_library.pyindex 14980258..7fa06da9 100644--- a/tests/test_model_library.py+++ b/tests/test_model_library.py@@ -1,8 +1,12 @@"""Public model library: provider labels and which catalog entries it lists."""+import pytest+from overbae.modal.model_registry import all_model_entriesfrom overbae.services.model_library import _provider_from_id, public_model_catalog+pytestmark = pytest.mark.covers("model-runtime")+def test_unsloth_hosted_models_resolve_to_their_vendor():assert _provider_from_id("unsloth/Muse-Glimmer-30B") == "Meta"diff --git a/tests/test_model_registry.py b/tests/test_model_registry.pyindex 23033ae6..e44a5542 100644--- a/tests/test_model_registry.py+++ b/tests/test_model_registry.py@@ -15,6 +15,8 @@ from overbae.core.model_registry import (resolve_openrouter_slug,)+pytestmark = pytest.mark.covers("llm-gateway")+@pytest.fixturedef no_keys(monkeypatch):diff --git a/tests/test_model_swap_prompt.py b/tests/test_model_swap_prompt.pyindex 694665b0..87279f8a 100644--- a/tests/test_model_swap_prompt.py+++ b/tests/test_model_swap_prompt.py@@ -8,15 +8,13 @@ from factories import auth_clientfrom overbae.models import (Capability,- DeployedModel,FinetuningJob,Project,ProjectMembership,User,)-from overbae.services.model_swap_prompt import model_swap_prompt_for_job-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]def _setup():@@ -50,18 +48,6 @@ def _make_job(project, dataset, *, status=None, output_model_name="ft-model", ca)-def _deploy(project, job, *, model_id=None, status=None) -> DeployedModel:- deployed = DeployedModel.objects.create(- finetuning_job=job,- project=project,- model_id=model_id or f"ft-{uuid.uuid4().hex[:8]}-qwen2-5-14b",- status=status or DeployedModel.Status.READY,- max_model_len=8192,- )- job.refresh_from_db()- return deployed--def _get(client, job, *, pin=None):url = f"/api/finetuning-jobs/{job.id}/model-swap-prompt/"if pin is not None:@@ -69,47 +55,6 @@ def _get(client, job, *, pin=None):return client.get(url)-def test_model_swap_prompt_returns_alias_payload():- project, user, dataset, capability = _setup()- job = _make_job(project, dataset, capability=capability)- deployed = _deploy(project, job, model_id="ft-abc12345-qwen2-5-14b")-- payload, error = model_swap_prompt_for_job(job, base_url="http://testserver/api/v1")- assert error is None- alias = f"overmind/{capability.id}"- assert payload["new_model"] == alias- assert payload["pin"] is False- assert alias in payload["prompt"]- assert deployed.model_id not in payload["prompt"]-- resp = _get(auth_client(user), job)- assert resp.status_code == 200- body = resp.json()- assert body["prompt"] == payload["prompt"]- assert body["capability_id"] == str(capability.id)- assert body["capability_name"] == capability.name- assert body["new_model"] == alias- assert body["pin"] is False---def test_model_swap_prompt_pin_writes_concrete_id():- project, user, dataset, capability = _setup()- job = _make_job(project, dataset, capability=capability)- _deploy(project, job, model_id="ft-abc12345-qwen2-5-14b")-- payload, error = model_swap_prompt_for_job(job, pin=True, base_url="http://testserver/api/v1")- assert error is None- assert payload["new_model"] == "ft-abc12345-qwen2-5-14b"- assert payload["pin"] is True- assert "overmind/" not in payload["prompt"]- assert 'to "ft-abc12345-qwen2-5-14b"' in payload["prompt"]-- resp = _get(auth_client(user), job, pin=True)- assert resp.status_code == 200- assert resp.json()["new_model"] == "ft-abc12345-qwen2-5-14b"- assert resp.json()["pin"] is True--def test_model_swap_prompt_rejects_non_succeeded():project, user, dataset, capability = _setup()job = _make_job(project, dataset, status=FinetuningJob.Status.FAILED, capability=capability)@@ -117,81 +62,3 @@ def test_model_swap_prompt_rejects_non_succeeded():resp = _get(auth_client(user), job)assert resp.status_code == 400assert "successfully" in resp.json()["detail"].lower()---def test_model_swap_prompt_rejects_unready_deployment():- project, user, dataset, capability = _setup()- job = _make_job(project, dataset, capability=capability)- _deploy(project, job, model_id="ft-warming", status=DeployedModel.Status.DEPLOYING)-- resp = _get(auth_client(user), job)- assert resp.status_code == 400- assert "not ready" in resp.json()["detail"]- assert "ft-warming" in resp.json()["detail"]---def test_model_swap_prompt_rejects_job_with_no_deployment():- project, user, dataset, capability = _setup()- job = _make_job(project, dataset, capability=capability)-- resp = _get(auth_client(user), job)- assert resp.status_code == 400- assert "no deployed model" in resp.json()["detail"]---def test_model_swap_prompt_pin_rejects_unready_deployment():- project, user, dataset, capability = _setup()- job = _make_job(project, dataset, capability=capability)- _deploy(project, job, model_id="ft-warming", status=DeployedModel.Status.DEPLOYING)-- resp = _get(auth_client(user), job, pin=True)- assert resp.status_code == 400- assert "not ready" in resp.json()["detail"]---def test_model_swap_prompt_pin_rejects_job_with_no_deployment():- project, user, dataset, capability = _setup()- job = _make_job(project, dataset, capability=capability)-- resp = _get(auth_client(user), job, pin=True)- assert resp.status_code == 400- assert "no deployed model" in resp.json()["detail"]---def test_model_swap_prompt_pins_the_deployment_without_a_capability():- project, user, dataset, _ = _setup()- Capability.objects.create(project=project, name="second-bot", slug="second-bot")- job = _make_job(project, dataset, capability=None)- deployed = _deploy(project, job)-- resp = _get(auth_client(user), job)- assert resp.status_code == 200- body = resp.json()- assert body["pin"] is True- assert body["capability_id"] is None- assert body["new_model"] == deployed.model_id- assert "overmind/" not in body["prompt"]- assert f'to "{deployed.model_id}"' in body["prompt"]---def test_model_swap_prompt_falls_back_to_sole_capability():- project, user, dataset, capability = _setup()- job = _make_job(project, dataset, capability=None)- _deploy(project, job)-- resp = _get(auth_client(user), job)- assert resp.status_code == 200- assert resp.json()["capability_id"] == str(capability.id)- assert resp.json()["new_model"] == f"overmind/{capability.id}"---def test_self_hosted_prompt_uses_the_request_origin():- project, user, dataset, capability = _setup()- job = _make_job(project, dataset, capability=capability)- _deploy(project, job)- response = auth_client(user).get(- f"/api/finetuning-jobs/{job.id}/model-swap-prompt/", HTTP_HOST="localhost:8000"- )- assert response.status_code == 200- assert "http://localhost:8000/api/v1" in response.data["prompt"]- assert "api.overmindlab.ai" not in response.data["prompt"]diff --git a/tests/test_modelfam.py b/tests/test_modelfam.pyindex 0de2fcea..d4386572 100644--- a/tests/test_modelfam.py+++ b/tests/test_modelfam.py@@ -29,6 +29,8 @@ from modal_shared.stacks import (TRAIN_U2026_10_7,)+pytestmark = pytest.mark.covers("model-runtime")+_MODELS_JSON = Path(__file__).resolve().parents[1] / "overbae" / "modal" / "models.json"# Ordering cases — first match wins.diff --git a/tests/test_moe_adapter_format.py b/tests/test_moe_adapter_format.pyindex fff3867a..706f02c2 100644--- a/tests/test_moe_adapter_format.py+++ b/tests/test_moe_adapter_format.py@@ -4,6 +4,8 @@ import pytestfrom modal_shared.serving.args import VllmServeContext, build_vllm_args, lora_load_request+pytestmark = pytest.mark.covers("model-runtime")+@pytest.mark.parametrize("fused", [False, True])def test_adapter_request_declares_expert_format(tmp_path, fused):diff --git a/tests/test_native_evaluation_deletion.py b/tests/test_native_evaluation_deletion.pyindex f55376fe..9ee4eb31 100644--- a/tests/test_native_evaluation_deletion.py+++ b/tests/test_native_evaluation_deletion.py@@ -20,7 +20,7 @@ from overbae.services.mcp.contracts.model_workflows import ListWorkflowsInputfrom overbae.services.mcp.tools_model_workflows import list_workflowsfrom overbae.tasks.native_evaluation import advance_plan-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("identity")]@pytest.fixturediff --git a/tests/test_native_evaluation_plan.py b/tests/test_native_evaluation_plan.pyindex 83282183..578b404b 100644--- a/tests/test_native_evaluation_plan.py+++ b/tests/test_native_evaluation_plan.py@@ -12,7 +12,7 @@ from overbae.models import Dataset, FinetuningJob, Projectfrom overbae.services import native_evaluation, native_evaluation_monitorfrom overbae.services.datasets import land-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]def setup_plan(*, prepare=True, question_count=None, targets=None):diff --git a/tests/test_native_evaluation_recovery.py b/tests/test_native_evaluation_recovery.pyindex b9fa5cca..f9011607 100644--- a/tests/test_native_evaluation_recovery.py+++ b/tests/test_native_evaluation_recovery.py@@ -19,7 +19,7 @@ from overbae.services import ()from overbae.tasks.native_evaluation import advance_plan, reconcile-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("recovery")]@pytest.fixturediff --git a/tests/test_onboarding_completion.py b/tests/test_onboarding_completion.pyindex 4eec0e38..829253ef 100644--- a/tests/test_onboarding_completion.py+++ b/tests/test_onboarding_completion.py@@ -7,7 +7,7 @@ from factories import auth_client, make_userfrom overbae.models import Project, ProjectMembership, User, UserOnboarding-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]def _me(user: User) -> dict:@@ -19,16 +19,6 @@ def _add_membership(user: User) -> None:ProjectMembership.objects.create(user=user, project=project)-def test_fresh_user_is_incomplete():- assert _me(make_user())["has_completed_onboarding"] is False---def test_membership_without_onboarding_record_counts_as_completed():- user = make_user()- _add_membership(user)- assert _me(user)["has_completed_onboarding"] is True--def test_in_progress_overrides_membership_shortcut():user = make_user()UserOnboarding.objects.create(user=user, status="in_progress")@@ -36,12 +26,7 @@ def test_in_progress_overrides_membership_shortcut():assert _me(user)["has_completed_onboarding"] is False-def test_completed_status_wins():- user = make_user()- UserOnboarding.objects.create(user=user, status="completed")- assert _me(user)["has_completed_onboarding"] is True--[email protected]("authentication")def test_patch_cannot_reassign_onboarding_user():user = make_user()other = make_user()diff --git a/tests/test_operational_progress.py b/tests/test_operational_progress.pyindex 6cccd982..61e794aa 100644--- a/tests/test_operational_progress.py+++ b/tests/test_operational_progress.py@@ -19,7 +19,7 @@ from overbae.services.provider_progress import read_page as read_provider_pagefrom overbae.tasks.finetuning import observe_finetuning_jobfrom overbae.tasks.finetuning_reconciler import reconcile_finetuning_jobs-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("measured-facts")]emit_provider_event = Journal.emitdiff --git a/tests/test_optimizer_fsm.py b/tests/test_optimizer_fsm.pyindex 4bf4793b..781e6434 100644--- a/tests/test_optimizer_fsm.py+++ b/tests/test_optimizer_fsm.py@@ -34,7 +34,7 @@ from overbae.services.optimizer_ledger import ()from overbae.tasks.optimizer_reconciler import reconcile_optimizer_experiments-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]EXACT_MATCH = "def evaluate(span):\n return span.output == span.expected\n"diff --git a/tests/test_optimizer_input_shapes.py b/tests/test_optimizer_input_shapes.pyindex 2c8a7520..413ebd56 100644--- a/tests/test_optimizer_input_shapes.py+++ b/tests/test_optimizer_input_shapes.py@@ -10,7 +10,7 @@ from conftest import EVAL_ROWS, TRAIN_ROWS, frozen_datasetfrom overbae.models import Capability, Projectfrom overbae.models.optimizer import optimizer_dataset_error-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]def test_optimizer_rejects_ft_and_missing_datasets():diff --git a/tests/test_optimizer_ledger.py b/tests/test_optimizer_ledger.pyindex 684fb963..64e48a1e 100644--- a/tests/test_optimizer_ledger.py+++ b/tests/test_optimizer_ledger.py@@ -22,7 +22,7 @@ from overbae.services.optimizer_ledger import (set_command_template,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("metrics-math")]def _capability_with_eval_dataset():diff --git a/tests/test_optimizer_model_comparison.py b/tests/test_optimizer_model_comparison.pyindex 26bdd4b8..28471fe2 100644--- a/tests/test_optimizer_model_comparison.py+++ b/tests/test_optimizer_model_comparison.py@@ -4,22 +4,19 @@ import uuidimport pytestfrom conftest import frozen_dataset-from factories import make_matrix_row, make_span+from factories import make_matrix_rowfrom rest_framework.exceptions import ValidationError-from overbae.api.optimizer import OptimizerCandidateSerializer, OptimizerExperimentSerializerfrom overbae.models import (Capability,DeployedModel,EvalMatrix,OptimizerCandidate,- OptimizerCommand,OptimizerExperiment,OptimizerIteration,Project,)from overbae.services.optimizer_create import (- create_optimizer_experiment,validate_optimizer_models,)from overbae.services.optimizer_ledger import (@@ -29,7 +26,7 @@ from overbae.services.optimizer_ledger import (post_results,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]EXACT_MATCH = "def evaluate(span):\n return span.output == span.expected\n"@@ -74,45 +71,7 @@ def _experiment(*, mode=MODE, model_ids=None, status=None, openrouter_key_sourcereturn experiment[email protected]("model_ids", [None, [], MODELS * 3, [""], [" openai/gpt-5"]])-def test_model_selection_rejects_missing_too_many_or_malformed(model_ids):- with pytest.raises(ValidationError) as exc:- validate_optimizer_models(MODE, model_ids)- assert "model_ids" in str(exc.value)---def test_model_selection_rejects_duplicates_and_unavailable():- with pytest.raises(ValidationError, match="Duplicate"):- validate_optimizer_models(MODE, [MODELS[0], MODELS[0]])-- with pytest.raises(ValidationError, match="dead/model"):- validate_optimizer_models(MODE, ["dead/model"])---def test_finetuned_alias_is_not_a_valid_reference():- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")- capability = Capability.objects.create(- project=project, name="A", slug=f"a-{uuid.uuid4().hex[:8]}"- )- deployed = DeployedModel.objects.create(- project=project,- model_id=f"ft-ready-{uuid.uuid4().hex[:8]}",- status=DeployedModel.Status.READY,- base_model_id="meta-llama/Meta-Llama-3.1-8B-Instruct-Reference",- )- capability.active_model = deployed- capability.save(update_fields=["active_model"])-- # The alias chases the capability's *active* model — the comparison must pin- # the deployment itself, so aliases are rejected outright.- with pytest.raises(ValidationError, match="overmind/"):- validate_optimizer_models(MODE, [f"overmind/{capability.id}"], project=project)-- assert validate_optimizer_models(MODE, [deployed.model_id], project=project) == [- deployed.model_id- ]--[email protected]("tenancy")def test_finetuned_deployment_id_requires_ready_in_project():project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")ready = DeployedModel.objects.create(@@ -156,53 +115,6 @@ def test_normal_optimizer_rejects_model_selection():validate_optimizer_models(OptimizerExperiment.Mode.OPTIMIZE, [MODELS[0]])-def test_hybrid_model_selection_is_validated():- assert validate_optimizer_models(OptimizerExperiment.Mode.HYBRID, MODELS) == MODELS---def test_create_service_forces_one_iteration_per_model():- experiment = _experiment(mode=OptimizerExperiment.Mode.OPTIMIZE)- created = create_optimizer_experiment(- user=None,- capability=experiment.capability,- dataset=experiment.dataset,- mode=MODE,- model_ids=MODELS,- num_iterations=9,- num_candidates_per_iteration=9,- max_iterations_without_improvement=9,- openrouter_key_source=OptimizerExperiment.OpenRouterKeySource.LOCAL,- )- assert created.mode == MODE- assert created.model_ids == MODELS- assert created.num_iterations == 2- assert created.num_candidates_per_iteration == 1- assert created.max_iterations_without_improvement == 0- assert created.status == OptimizerExperiment.Status.SCHEDULED---def test_read_serializers_expose_comparison_fields():- experiment = _experiment()- iteration = OptimizerIteration.objects.create(experiment=experiment, order=1)- candidate = OptimizerCandidate.objects.create(- experiment=experiment,- iteration=iteration,- candidate_index=0,- target_model=MODELS[0],- code_path="diff --git a/x b/x\n",- )-- experiment_data = OptimizerExperimentSerializer(experiment).data- candidate_data = OptimizerCandidateSerializer(candidate).data-- assert experiment_data["mode"] == MODE- assert experiment_data["model_ids"] == MODELS- assert candidate_data["target_model"] == MODELS[0]- assert candidate_data["model_name"] == MODELS[0]- assert candidate_data["code_path"] == "diff --git a/x b/x\n"- assert str(candidate_data["experiment"]) == str(experiment.id)--def _grade(experiment, candidate: dict, results: list[dict], *, order: int = 1):make_matrix_row(experiment.project,@@ -219,115 +131,6 @@ def _grade(experiment, candidate: dict, results: list[dict], *, order: int = 1):return posted[email protected]_db(transaction=True)-def test_failed_outputs_are_excluded_from_the_score(eager):- experiment = _experiment(mode=OptimizerExperiment.Mode.OPTIMIZE)- candidate = _grade(- experiment,- {"candidate_index": 0},- [- {"datapoint_index": 0, "output": "a"},- {"datapoint_index": 1, "success": False, "error": "provider timeout"},- ],- )-- assert candidate.score == pytest.approx(50.0)- assert candidate.scores["coverage"] == {- "excluded_commands": 1,- "errors": ["provider timeout"],- "scored_rows": 1,- "graded_rows": 2,- "total_rows": 2,- "coverage_rate": 0.5,- }- assert candidate.commands.get(datapoint_index=1).status == OptimizerCommand.Status.FAILED--- ("target", "observed", "routed"),- [- ("openai/gpt-5", "openai/gpt-5", True),- ("openai/gpt-5-mini", "gpt-5-mini", True),- ("qwen/qwen3-14b", "qwen3-14b", True),- ("openrouter/qwen/qwen3-14b", "qwen3-14b", True),- ("openai/gpt-5", "openrouter/openai/gpt-5", True),- ("deepseek/deepseek-v4-flash", "DeepSeek/DeepSeek-V4-Flash", True),- ("ft-abc", "ft-abc", True),- ("openai/gpt-5", "anthropic/claude-sonnet-4", False),- ("openai/gpt-5-mini", "anthropic/gpt-5-mini", False),- ("openai/gpt-5-mini", "openai/gpt-5.4", False),- ("ft-abc", "ft-def", False),- ],-)-def test_a_trace_served_by_another_model_fails_the_datapoint(eager, target, observed, routed):- experiment = _experiment()- make_span(- experiment.project,- trace_id="a" * 32,- span_type="llm",- attributes={"gen_ai.request.model": observed},- )-- candidate = _grade(- experiment,- {"candidate_index": 0, "target_model": target},- [- {"datapoint_index": 0, "output": "a", "trace_id": "a" * 32},- {"datapoint_index": 1, "output": "b"},- ],- )-- command = candidate.commands.get(datapoint_index=0)- assert candidate.scores["coverage"]["excluded_commands"] == (0 if routed else 1)- if not routed:- assert command.error.startswith("Model routing mismatch")- assert observed in command.error--[email protected]_db(transaction=True)-def test_candidates_share_the_first_rubric_and_score_answer_rows_scoped_to_a_span(eager):- experiment = _experiment()- make_matrix_row(- experiment.project,- "Answer matches",- capability=experiment.capability,- type=EvalMatrix.Type.DETERMINISTIC,- source=EXACT_MATCH,- span_name="SupportAgent.run",- )- make_matrix_row(- experiment.project,- "Tool step",- capability=experiment.capability,- type=EvalMatrix.Type.DETERMINISTIC,- source="def evaluate(span):\n return False\n",- span_type="tool_call",- )-- def grade(order: int, model: str):- iteration = create_iteration(experiment, order=order, candidates=[{"target_model": model}])- posted = iteration.candidates.get()- post_results(- experiment,- [- {"candidate_id": str(posted.id), "datapoint_index": 0, "output": "a"},- {"candidate_id": str(posted.id), "datapoint_index": 1, "output": "b"},- ],- )- evaluate_iteration(experiment, order)- posted.refresh_from_db()- return posted-- first = grade(1, MODELS[0])- make_matrix_row(experiment.project, "Added later", capability=experiment.capability)- second = grade(2, MODELS[1])-- assert [row["name"] for row in second.eval_run.matrix] == ["Answer matches", "Tool step"]- assert second.eval_run.matrix == first.eval_run.matrix- assert set(first.scores["metrics"]) == {"Answer matches"}- assert first.score == pytest.approx(100.0)--@pytest.mark.parametrize(("mode", "candidate", "label", "model_name"),[@@ -409,11 +212,6 @@ def test_hybrid_report_surfaces_best_combination_even_when_incumbent_wins():}-def test_validate_optimizer_models_stores_canonical_slugs():- assert validate_optimizer_models(MODE, ["openrouter/openai/gpt-5"]) == ["openai/gpt-5"]- assert validate_optimizer_models(MODE, ["openai/gpt-5"]) == ["openai/gpt-5"]--def test_model_comparison_winner_breaks_score_tie_on_coverage():experiment = _experiment()iteration = OptimizerIteration.objects.create(diff --git a/tests/test_optimizer_prereqs.py b/tests/test_optimizer_prereqs.pydeleted file mode 100644index 41b19084..00000000--- a/tests/test_optimizer_prereqs.py+++ /dev/null@@ -1,41 +0,0 @@-from __future__ import annotations--import uuid--import pytest-from conftest import EVAL_ROWS, frozen_dataset--from overbae.models import Capability, EvalSet, Project-from overbae.services.optimizer_prereqs import optimizer_prerequisite_report--pytestmark = pytest.mark.django_db---def test_prerequisite_report_ready_when_dataset_and_eval_set_present():- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")- capability = Capability.objects.create(project=project, name="a", slug="a")- dataset = frozen_dataset(project, EVAL_ROWS, capability=capability, contract="eval")- eval_set = EvalSet.objects.create(project=project, capability=capability, name="Default")- capability.active_eval_set = eval_set- capability.save(update_fields=["active_eval_set"])-- report = optimizer_prerequisite_report(project, capability)- assert report["ready"] is True- assert report["missing"] == []- assert report["eval_datasets"][0]["name"] == (dataset.name or str(dataset.id)[:8])- assert report["eval_datasets"][0]["usable"] is True- assert "overmind optimise start" in report["drive_command"]- assert "executioner_connected" not in report- assert "executioner_start_command" not in report---def test_prerequisite_report_missing_dataset():- project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")- capability = Capability.objects.create(project=project, name="a", slug="a")- eval_set = EvalSet.objects.create(project=project, capability=capability, name="Default")- capability.active_eval_set = eval_set- capability.save(update_fields=["active_eval_set"])-- report = optimizer_prerequisite_report(project, capability)- assert report["ready"] is False- assert any("dataset" in item for item in report["missing"])diff --git a/tests/test_otlp_dialects.py b/tests/test_otlp_dialects.pyindex f072890d..d1e0f900 100644--- a/tests/test_otlp_dialects.py+++ b/tests/test_otlp_dialects.py@@ -15,7 +15,7 @@ from factories import (from overbae.models import Span-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("otlp-ingest")]def _ingested(name: str, attributes: dict) -> Span:diff --git a/tests/test_overwatch_agent_api.py b/tests/test_overwatch_agent_api.pyindex 4937d789..4948be63 100644--- a/tests/test_overwatch_agent_api.py+++ b/tests/test_overwatch_agent_api.py@@ -1,25 +1,20 @@"""The agent credential can only run bounded analytics reads, never product actions."""import json-from datetime import UTC, datetime, timedeltaimport pytestfrom django.core.cache import cachefrom django.db import connection-from django.utils import timezonefrom factories import (api_key_client,auth_client,- make_capability,- make_project,- make_span,make_user,)from rest_framework.test import APIClient-from overbae.models import Dataset, DeployedModel, EvalRun, FinetuningJob, ProjectMembership, User+from overbae.services.overwatch_privacy import model_question, posthog_url-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("authentication")]URL = "/api/internal/overwatch/agent/query/"TOKEN = "agent-test-service-token"@@ -128,223 +123,6 @@ def test_service_token_cannot_use_dashboard_or_product_writes():assert client().get(URL).status_code == 405-def test_retired_backend_slack_paths_are_gone():- for path in ("command", "events"):- assert (- APIClient()- .post(f"/api/internal/overwatch/slack/{path}/", {}, format="json")- .status_code- == 404- )--- "tool,args",- [- ("activation_funnel", {"days": 7}),- ("product_usage", {"days": 7}),- ("customers_at_step", {"days": 7, "step": "signed_up", "limit": 2}),- ],-)-def test_all_read_tools_share_the_validated_contract(tool, args):- response = client().post(URL, {"tool": tool, "arguments": args}, format="json")- assert response.status_code == 200- assert response.data["private"] is (tool == "customers_at_step")- assert response.data["content"]--[email protected]("step", ["deployed_model", "called_alias"])-def test_resettable_milestones_do_not_claim_first_time_customers(step):- user = make_user(email="[email protected]")- project = make_project(member=user)- earlier = timezone.now() - timedelta(days=60)- ProjectMembership.objects.filter(project=project).update(created_at=earlier)- deployed = DeployedModel.objects.create(- project=project,- model_id="ft-returning",- status=DeployedModel.Status.READY,- deployed_at=earlier,- )- capability = make_capability(project, first_application_request_at=earlier)- # The persisted state after a redeploy/model switch no longer retains the first date.- DeployedModel.objects.filter(pk=deployed.pk).update(deployed_at=timezone.now())- type(capability).objects.filter(pk=capability.pk).update(- first_application_request_at=timezone.now()- )- response = client().post(- URL,- {"tool": "customers_at_step", "arguments": {"days": 7, "step": step}},- format="json",- )- assert response.status_code == 200- assert response.data["private"] is True- assert "cannot be determined" in response.data["content"]- assert "[email protected]" not in response.data["content"]- assert "0 users" not in response.data["content"]--- "step",- [- "signed_up",- "joined_project",- "sent_first_span",- "synced_capabilities",- "ran_evaluation",- "started_training",- ],-)-def test_milestone_report_counts_all_matches_but_fetches_only_newest_customers(step, time_machine):- time_machine.move_to(datetime(2026, 10, 25, 12, tzinfo=UTC), tick=False)- now = timezone.now()-- def add_milestone(user, at):- if step == "signed_up":- User.objects.filter(pk=user.pk).update(date_joined=at)- return- project = make_project(member=user)- ProjectMembership.objects.filter(project=project).update(- created_at=at if step == "joined_project" else at - timedelta(days=1)- )- if step == "joined_project":- return- if step == "sent_first_span":- record = make_span(project, trace_id="a" * 32)- field = "received_at"- elif step == "synced_capabilities":- record = make_capability(project)- field = "created_at"- elif step == "ran_evaluation":- record = EvalRun.objects.create(project=project, status=EvalRun.Status.COMPLETED)- field = "created_at"- else:- dataset = Dataset.objects.create(project=project, name="Train", intent="train")- record = FinetuningJob.objects.create(- project=project,- dataset=dataset,- base_model="Qwen/Qwen3-4B",- status=FinetuningJob.Status.SUCCEEDED,- )- field = "created_at"- type(record).objects.filter(pk=record.pk).update(**{field: at})-- expected = []- for index in range(30):- user = make_user(email=f"bounded-{index:02}@example.com")- # Ties must keep deterministic user order, not duplicate a customer.- at = now - timedelta(hours=index // 2 + 1)- add_milestone(user, at)- expected.append(user.email)- guest = make_user(email="[email protected]", is_guest=True)- add_milestone(guest, now)- old = make_user(email="[email protected]")- add_milestone(old, now - timedelta(days=60))- if step != "signed_up":- add_milestone(old, now - timedelta(hours=1))- row_counts = []-- def observe_rows(execute, sql, params, many, context):- result = execute(sql, params, many, context)- if sql.startswith("SELECT") and User._meta.db_table in sql:- row_counts.append(context["cursor"].rowcount)- return result-- with connection.execute_wrapper(observe_rows):- response = client().post(- URL,- {"tool": "customers_at_step", "arguments": {"days": 7, "step": step, "limit": 3}},- format="json",- )- assert response.status_code == 200- report = response.data["content"]- assert "30 users" in report and "Showing 3 results" in report- actual = [line.split(": ")[0] for line in report.splitlines() if "@" in line]- assert actual == expected[:3]- # Observe real PostgreSQL result sizes: a small response must not fetch all matches.- assert row_counts and max(row_counts) <= 3---def test_agent_reads_share_one_snapshot_for_an_hour(time_machine):- time_machine.move_to(datetime(2026, 10, 25, 12, tzinfo=UTC), tick=False)- make_user(email="[email protected]")- calls = [- ("activation_funnel", {"days": 7}),- ("billing_summary", {"days": 7}),- ("customer_activity", {"days": 7, "email": "[email protected]"}),- ("customers_at_step", {"days": 7, "step": "signed_up"}),- ]-- def ask(tool, arguments):- response = client().post(URL, {"tool": tool, "arguments": arguments}, format="json")- assert response.status_code == 200- assert response["Cache-Control"] == "private, no-store"- return response.data-- first = {tool: ask(tool, arguments) for tool, arguments in calls}- make_user(email="[email protected]")- User.objects.filter(email="[email protected]").update(- date_joined=timezone.now() - timedelta(days=2)- )- time_machine.shift(3599)- observed = []-- def record(execute, sql, params, many, context):- observed.append(sql)- return execute(sql, params, many, context)-- with connection.execute_wrapper(record):- again = ask("billing_summary", {"days": 7})- assert again == first["billing_summary"]- assert observed == []- assert ask("activation_funnel", {"days": 7}) == first["activation_funnel"]- assert (- ask("customer_activity", {"days": 7, "email": "[email protected]"})- == first["customer_activity"]- )- assert (- ask("customers_at_step", {"days": 7, "step": "signed_up", "limit": 25})- == first["customers_at_step"]- )- other_window = ask("activation_funnel", {"days": 30})- assert other_window["content"] != first["activation_funnel"]["content"]- assert other_window["as_of"] != first["activation_funnel"]["as_of"]- assert "[email protected]" not in first["customers_at_step"]["content"]-- time_machine.shift(2)- refreshed = ask("activation_funnel", {"days": 7})- customer = ask("customer_activity", {"days": 7, "email": "[email protected]"})- assert refreshed["content"] != first["activation_funnel"]["content"]- assert refreshed["as_of"] != first["activation_funnel"]["as_of"]- assert customer["content"] != first["customer_activity"]["content"]- assert (- in ask("customers_at_step", {"days": 7, "step": "signed_up", "limit": 25})["content"]- )---def posthog_usage_source(settings, scripted):- settings.POSTHOG_PERSONAL_API_KEY = "posthog-cache-test"- settings.POSTHOG_PROJECT_ID = "42"- settings.POSTHOG_API_HOST = "https://eu.posthog.com"- state = {"available": True, "count": 1}-- def answer(request):- if not state["available"]:- return 503, {"content-type": "application/json"}, b"{}"- query = request.json["query"]["query"]- rows = []- if "SELECT toDate(" in query:- rows = [[timezone.now().date().isoformat(), "cli.completed", state["count"]]]- elif "SELECT uniq(person_id)" in query:- rows = [[state["count"]]]- elif "countIf(" in query:- rows = [[0, 0]]- return 200, {"content-type": "application/json"}, json.dumps({"results": rows}).encode()-- return scripted("https://eu.posthog.com").then(answer), state--def usage(days=7):response = client().post(URL, {"tool": "product_usage", "arguments": {"days": days}}, format="json"@@ -353,58 +131,14 @@ def usage(days=7):return json.loads(response.data["content"])-def test_agent_usage_reuses_source_snapshot_for_an_hour_without_caching_product_rows(- posthog_usage_source, time_machine-):- time_machine.move_to(datetime(2026, 10, 25, 12, tzinfo=UTC), tick=False)- api, state = posthog_usage_source- first = usage()- assert first["posthog"]["available"] is True and len(api.calls) == 5- state["count"] = 2- make_user()- time_machine.shift(3599)- cached = usage()- assert cached["posthog"] == first["posthog"]- assert cached["registered_users"] == first["registered_users"] + 1- assert len(api.calls) == 5- time_machine.shift(2)- refreshed = usage()- assert refreshed["posthog"]["totals"]["cli_completions"] == 2- assert refreshed["posthog"]["window_end"] != first["posthog"]["window_end"]- assert len(api.calls) == 10---def test_agent_usage_failure_is_cached_briefly_then_recovers(posthog_usage_source, time_machine):- time_machine.move_to(datetime(2026, 10, 25, 12, tzinfo=UTC), tick=False)- api, state = posthog_usage_source- state["available"] = False- first = usage()["posthog"]- assert first["available"] is False and "totals" not in first- assert len(api.calls) == 5- state["available"] = True- time_machine.shift(59)- assert usage()["posthog"] == first- assert len(api.calls) == 5- time_machine.shift(2)- assert usage()["posthog"]["available"] is True- assert len(api.calls) == 10---def test_agent_usage_cache_separates_window_source_and_utc_day(- posthog_usage_source, time_machine, settings-):- time_machine.move_to(datetime(2026, 10, 25, 23, 59, tzinfo=UTC), tick=False)- api, state = posthog_usage_source- first = usage()["posthog"]- assert first["available"] is True- state["count"] = 2- assert usage(30)["posthog"]["totals"]["cli_completions"] == 2- settings.POSTHOG_PROJECT_ID = "43"- assert usage()["posthog"]["totals"]["cli_completions"] == 2- settings.POSTHOG_PERSONAL_API_KEY = "rotated-read-key"- state["count"] = 3- assert usage()["posthog"]["totals"]["cli_completions"] == 3- time_machine.shift(120)- today = usage()["posthog"]- assert today["window_start"] != first["window_start"]- assert len(api.calls) == 25[email protected]("privacy")+def test_agent_questions_drop_credentials_emails_and_links_and_reads_stay_on_posthog():+ with pytest.raises(ValueError, match="credential_like_input"):+ model_question("Why does sk-live_abcdefghijkl fail?")+ question, identities = model_question(+ "Did [email protected] and <mailto:[email protected]|Jane> open https://x.example/a?"+ )+ assert question == "Did customer_1 and customer_1 open [link omitted]"+ assert identities == {"customer_1": "[email protected]"}+ with pytest.raises(ValueError, match="unapproved_posthog_host"):+ posthog_url("https://posthog.example", "/api/projects/1/query/")diff --git a/tests/test_overwatch_dashboard.py b/tests/test_overwatch_dashboard.pyindex ad9dbe9f..5ea7a623 100644--- a/tests/test_overwatch_dashboard.py+++ b/tests/test_overwatch_dashboard.py@@ -1,8 +1,6 @@from __future__ import annotations-import json-import re-from datetime import datetime, timedelta+from datetime import timedeltaimport pytestfrom django.apps import apps@@ -19,21 +17,15 @@ from factories import (from rest_framework.test import APIClientfrom overbae.models import (- BillingService,- BillingTelemetry,Dataset,DeployedModel,EvalRun,FinetuningJob,- InferenceCall,- OptimizerExperiment,ProjectMembership,- Subscription,- SubscriptionStatus,User,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("authentication")]TOKEN = "overwatch-test-token"@@ -100,247 +92,6 @@ def test_rejects_anything_but_the_configured_token(settings, path):assert overwatch_client("").get(url).status_code == 403-def test_overview_counts_customers_only(accounts):- body = overwatch_client().get("/api/internal/overwatch/overview/").json()-- assert body["users_total"] == 3- assert sum(point["value"] for point in body["signups"]) == 2- assert body["trace_active_users_7d"] == 1- assert sum(point["value"] for point in body["spans"]) == 2- assert sum(point["value"] for point in body["traces"]) == 1- assert body["training_jobs"] == {"succeeded": 1}- assert body["top_base_models"] == [{"base_model": "Qwen/Qwen3-4B", "jobs": 1}]- assert body["live_deployments"] == 1---def test_overview_retains_subscription_spend_and_payment_insights(accounts):- paying = accounts["paying"]- Subscription.objects.create(- user=paying,- status=SubscriptionStatus.ACTIVE,- cancel_at_period_end=True,- )- BillingTelemetry.objects.create(- user=paying,- amount="-53.2500000",- service=BillingService.INFERENCE,- )- BillingTelemetry.objects.create(- user=paying,- amount="5.0000000",- service=BillingService.STRIPE_TOPUP,- )-- body = overwatch_client().get("/api/internal/overwatch/overview/").json()-- assert body["subscriptions"] == {SubscriptionStatus.ACTIVE: 1}- assert body["paying_users"] == 1- assert body["cancelling_users"] == 1- assert body["free_users"] == 1- assert body["low_balance_users"] == 1- assert body["spend_by_service"] == {BillingService.INFERENCE: "53.2500000"}- assert sum(float(point["value"]) for point in body["topups_usd"]) == 5- assert sum(float(point["value"]) for point in body["spend_usd"]) == 53.25---def test_user_activity_retains_lifetime_billing_and_window_history(accounts):- paying = accounts["paying"]- Subscription.objects.create(user=paying, status=SubscriptionStatus.PAST_DUE)- BillingTelemetry.objects.create(- user=paying,- amount="-7.5000000",- service=BillingService.FINETUNING_JOB,- )- BillingTelemetry.objects.create(- user=paying,- amount="10.0000000",- service=BillingService.STRIPE_TOPUP,- )-- body = overwatch_client().get(f"/api/internal/overwatch/users/{paying.id}/").json()-- assert body["user"]["subscription_status"] == SubscriptionStatus.PAST_DUE- assert body["user"]["spend_usd"] == "7.5000000"- assert body["user"]["topups_usd"] == "10.0000000"- assert body["user"]["balance_usd"] == "52.5000000"- assert body["billing"]["subscription_status"] == SubscriptionStatus.PAST_DUE- assert body["billing"]["spend_usd"] == "7.5000000"- assert body["billing"]["topups_usd"] == "10.0000000"- assert body["billing"]["balance_usd"] == "52.5000000"- assert sum(float(point["value"]) for point in body["billing"]["spend_daily"]) == 7.5- assert sum(float(point["value"]) for point in body["billing"]["topups_daily"]) == 10---def test_posthog_usage_survives_http_and_serializer_boundary(settings, scripted):- settings.POSTHOG_PERSONAL_API_KEY = "posthog-read-test"- settings.POSTHOG_PROJECT_ID = "42"- settings.POSTHOG_API_HOST = "https://eu.posthog.com"- queries = []-- def answer(call):- hogql = call.json["query"]["query"]- queries.append(hogql)- if "SELECT toDate(" in hogql:- rows = [[timezone.now().date().isoformat(), "cli.completed", 4]]- elif "SELECT uniq(person_id)" in hogql:- rows = [[3]]- elif "properties.$mcp_tool_name" in hogql:- rows = [["list_projects", 5, 2]]- elif "properties.command_path" in hogql:- rows = [["sync", 7, 3]]- elif "countIf(toBool(properties.$mcp_is_error))" in hogql:- rows = [[5, 1]]- else:- raise AssertionError("Unexpected aggregate query")- return 200, {"content-type": "application/json"}, json.dumps({"results": rows}).encode()-- api = scripted("https://eu.posthog.com").then(answer)- response = overwatch_client().get("/api/internal/overwatch/product-usage/?days=14")- result = response.json()- assert result["available"] is True- assert result["active_users"] == 3- assert result["totals"]["cli_completions"] == 4- assert "funnel_steps" not in result- assert result["top_mcp_tools"] == [{"name": "list_projects", "calls": 5, "users": 2}]- assert result["top_cli_commands"] == [{"name": "sync", "completions": 7, "users": 3}]- assert result["mcp_tool_errors"] == 1- assert result["mcp_tool_error_rate"] == 0.2- assert len(api.calls) == 5- assert all("overwatch_funnel_step" not in query for query in queries)- assert response["Cache-Control"] == "private, no-store"- assert all("timestamp <= toDateTime" in query for query in queries)--- "rows", [None, [["bad-date", "cli.completed", 1]], [["2026-10-25", "unknown", 1]]]-)-def test_malformed_posthog_results_are_unavailable_not_zero(settings, scripted, rows):- settings.POSTHOG_PERSONAL_API_KEY = "posthog-read-test"- settings.POSTHOG_PROJECT_ID = "42"- settings.POSTHOG_API_HOST = "https://eu.posthog.com"- scripted("https://eu.posthog.com").reply(json_body={"results": rows})- result = overwatch_client().get("/api/internal/overwatch/product-usage/").json()- assert result["available"] is False- assert "active_users" not in result--- ("section", "replacement", "available"),- [- ("active", [], False),- ("active", [[0, 1]], False),- ("errors", [], False),- ("errors", [[0]], False),- ("daily", [["2000-01-01", "cli.completed", 1]], False),- ("tools", [["list_projects", 1, 1]] * 9, False),- ("daily", [], True),- ],-)-def test_posthog_empty_events_differ_from_incomplete_aggregates(- settings, scripted, section, replacement, available-):- settings.POSTHOG_PERSONAL_API_KEY = "posthog-read-test"- settings.POSTHOG_PROJECT_ID = "42"- settings.POSTHOG_API_HOST = "https://eu.posthog.com"-- def answer(request):- query = request.json["query"]["query"]- key, rows = "other", []- if "SELECT uniq(person_id)" in query:- key, rows = "active", [[0]]- elif "countIf(toBool(properties.$mcp_is_error))" in query:- key, rows = "errors", [[0, 0]]- elif "SELECT toDate(" in query:- key = "daily"- elif "properties.$mcp_tool_name" in query:- key = "tools"- return (- 200,- {"content-type": "application/json"},- json.dumps({"results": replacement if key == section else rows}).encode(),- )-- scripted("https://eu.posthog.com").then(answer)- result = overwatch_client().get("/api/internal/overwatch/product-usage/").json()- assert result["available"] is available- if available:- assert result["active_users"] == result["mcp_tool_errors"] == 0- else:- assert "active_users" not in result--[email protected]("days", [30, 365])-def test_posthog_daily_totals_include_the_complete_window(settings, scripted, days):- settings.POSTHOG_PERSONAL_API_KEY = "posthog-read-test"- settings.POSTHOG_PROJECT_ID = "42"- settings.POSTHOG_API_HOST = "https://eu.posthog.com"- today = timezone.now().date()- events = [- "cli.completed",- "$mcp_tool_call",- "training_result_available",- "training_check_finished",- ]- daily = [- [(today - timedelta(days=offset)).isoformat(), event, 1]- for offset in reversed(range(days))- for event in events- ]-- def answer(request):- query = request.json["query"]["query"]- if "GROUP BY" in query and "timestamp" in query and "properties." not in query:- # Reproduce the external API's implicit result cap, not an unlimited fake.- match = re.search(r"LIMIT (\d+)\s*$", query)- limit = int(match[1]) if match else 100- payload = {"results": daily[:limit], "hasMore": len(daily) > limit}- elif "SELECT uniq(person_id)" in query:- payload = {"results": [[1]]}- elif "countIf(" in query:- payload = {"results": [[days, 0]]}- else:- payload = {"results": []}- return 200, {"content-type": "application/json"}, json.dumps(payload).encode()-- scripted("https://eu.posthog.com").then(answer)- result = overwatch_client().get(f"/api/internal/overwatch/product-usage/?days={days}").json()- assert result["available"] is True- assert list(result["totals"].values()) == [days] * 4- assert len(result["daily"]) == days- assert result["daily"][-1]["day"] == today.isoformat()- assert result["daily"][-1]["cli_completions"] == 1--[email protected]("section", ["daily", "active", "errors", "tools"])-def test_posthog_truncation_is_only_allowed_for_top_lists(settings, scripted, section):- settings.POSTHOG_PERSONAL_API_KEY = "posthog-read-test"- settings.POSTHOG_PROJECT_ID = "42"- settings.POSTHOG_API_HOST = "https://eu.posthog.com"-- def answer(request):- query = request.json["query"]["query"]- key, rows = "daily", [[timezone.now().date().isoformat(), "cli.completed", 1]]- if "SELECT uniq(person_id)" in query:- key, rows = "active", [[1]]- elif "countIf(" in query:- key, rows = "errors", [[1, 0]]- elif "properties.$mcp_tool_name" in query:- key, rows = "tools", [["list_projects", 1, 1]] * 8- elif "properties.command_path" in query:- key, rows = "commands", []- return (- 200,- {"content-type": "application/json"},- json.dumps({"results": rows, "hasMore": key == section}).encode(),- )-- scripted("https://eu.posthog.com").then(answer)- result = overwatch_client().get("/api/internal/overwatch/product-usage/?days=7").json()- assert result["available"] is (section == "tools")- if section != "tools":- assert "totals" not in result--def test_unicode_bearer_token_is_rejected_safely():assert overwatch_client("☃").get("/api/internal/overwatch/overview/").status_code == 403@@ -380,130 +131,6 @@ def test_dashboard_credential_cannot_create_a_core_product_project():).exists()-def test_funnel_follows_window_signups(accounts):- body = overwatch_client().get("/api/internal/overwatch/activation/").json()-- assert body["steps"] == [- {"step": "signed_up", "users": 2},- {"step": "joined_project", "users": 1},- {"step": "sent_first_span", "users": 1},- {"step": "synced_capabilities", "users": 1},- {"step": "ran_evaluation", "users": 1},- {"step": "started_training", "users": 1},- {"step": "deployed_model", "users": 1},- {"step": "called_alias", "users": 1},- ]- assert body["median_hours_to_first_span"] is not None-- widened = overwatch_client().get("/api/internal/overwatch/activation/?days=90").json()- assert widened["steps"][0] == {"step": "signed_up", "users": 3}---def test_project_activity_only_counts_after_a_user_joins(accounts):- active = accounts["active"]- project = active.project_memberships.get().project- invited = make_user(email="[email protected]")- ProjectMembership.objects.create(user=invited, project=project)-- body = overwatch_client().get("/api/internal/overwatch/activation/").json()- steps = {step["step"]: step["users"] for step in body["steps"]}-- assert steps["signed_up"] == 3- assert steps["joined_project"] == 2- assert steps["sent_first_span"] == 1- assert steps["synced_capabilities"] == 1- assert steps["ran_evaluation"] == 1- assert steps["started_training"] == 1- assert steps["deployed_model"] == 1- assert steps["called_alias"] == 1- overview = overwatch_client().get("/api/internal/overwatch/overview/").json()- assert overview["trace_active_users_7d"] == overview["trace_active_users_window"] == 1---def test_accounts_table_pages_and_orders(accounts):- first = overwatch_client().get("/api/internal/overwatch/users/?ordering=-spans&page_size=1")- body = first.json()-- assert body["count"] == 3- assert body["next"]- row = body["results"][0]- assert row["email"] == "[email protected]"- assert row["projects"] == 1- assert row["seats"] == 1- assert row["spans"] == 2- assert row["training_jobs"] == 1- assert row["live_deployments"] == 1- assert row["stage"] == "called_alias"-- by_projects = overwatch_client().get("/api/internal/overwatch/users/?ordering=-projects").json()- assert by_projects["results"][0]["email"] == "[email protected]"-- assert overwatch_client().get("/api/internal/overwatch/overview/?days=0").status_code == 400---def test_account_activity_breaks_down_each_workflow(accounts):- active = accounts["active"]- project = active.project_memberships.get().project- dataset = project.datasets.get()- FinetuningJob.objects.create(- project=project,- dataset=dataset,- base_model="Qwen/Qwen3-4B",- status=FinetuningJob.Status.FAILED,- )- deployed = DeployedModel.objects.get(model_id="ft-qwen-1")- InferenceCall.objects.create(deployed_model=deployed, project=project)- InferenceCall.objects.create(deployed_model=deployed, project=project)- Dataset.objects.create(project=project, name="Traces", source_kind="traces", intent="eval")- OptimizerExperiment.objects.create(- project=project, capability=project.capabilities.get(), dataset=dataset- )-- body = overwatch_client().get(f"/api/internal/overwatch/users/{active.id}/").json()-- assert body["user"]["email"] == "[email protected]"- training = body["training"]- assert training["totals"] == {- "started": 2,- "completed": 1,- "failed": 1,- "cancelled": 0,- "in_progress": 0,- }- assert sum(sum(point["values"].values()) for point in training["daily"]) == 2- assert {job["status"] for job in training["recent"]} == {"succeeded", "failed"}- assert body["traces"]["total"] == 1- assert sum(point["value"] for point in body["traces"]["daily"]) == 1- assert body["inference"]["calls"] == 2- assert body["inference"]["models"] == 1- assert body["inference"]["by_model"] == {"ft-qwen-1": 2}- assert body["datasets"]["total"] == 2- assert body["datasets"]["by_source"] == {"file": 1, "traces": 1}- assert body["datasets"]["by_intent"] == {"train": 1, "eval": 1}- assert body["optimizer"]["by_status"] == {"scheduled": 1}- assert body["evaluations"]["by_status"] == {"completed": 1}-- guest = User.objects.get(email="[email protected]")- assert overwatch_client().get(f"/api/internal/overwatch/users/{guest.id}/").status_code == 404---def test_responses_are_cached_for_an_hour(accounts):- first = overwatch_client().get("/api/internal/overwatch/overview/").json()- make_user()- again = overwatch_client().get("/api/internal/overwatch/overview/").json()-- assert again["users_total"] == first["users_total"] == 3- assert again["computed_at"] == first["computed_at"]- computed = datetime.fromisoformat(first["computed_at"])- assert datetime.fromisoformat(first["refreshes_at"]) - computed == timedelta(hours=1)-- other_window = overwatch_client().get("/api/internal/overwatch/overview/?days=7").json()- assert other_window["users_total"] == 4-- page = overwatch_client().get("/api/internal/overwatch/users/").json()- assert page["count"] == 4 and page["computed_at"]--@pytest.fixture(autouse=True)def _sandbox(settings):# These tests never call the parser sandbox; outbound requests remain guarded.@@ -511,31 +138,6 @@ def _sandbox(settings):settings.SANDBOX_TOKEN = "analytics-test"-def test_one_day_window_starts_at_utc_midnight():- from overbae.services.user_insights import window_start-- start = window_start(1)- assert (start.hour, start.minute, start.second, start.microsecond) == (0, 0, 0, 0)- assert start.date() == timezone.now().date()---def test_database_timeout_is_bounded_and_restores_connection():- from django.db import DatabaseError, connection-- from overbae.services.user_insights import analytics_read_budget-- with connection.cursor() as cursor:- cursor.execute("SHOW statement_timeout")- before = cursor.fetchone()[0]- with pytest.raises(DatabaseError), analytics_read_budget(0.05), connection.cursor() as cursor:- cursor.execute("SELECT pg_sleep(0.3)")- with connection.cursor() as cursor:- cursor.execute("SHOW statement_timeout")- assert cursor.fetchone()[0] == before- cursor.execute("SELECT 1")- assert cursor.fetchone() == (1,)--def test_posthog_credentials_cannot_be_sent_to_unapproved_host(settings, scripted):settings.POSTHOG_PERSONAL_API_KEY = "posthog-read-test"settings.POSTHOG_PROJECT_ID = "42"diff --git a/tests/test_plan_limits.py b/tests/test_plan_limits.pyindex d1c725c9..d43872b8 100644--- a/tests/test_plan_limits.py+++ b/tests/test_plan_limits.py@@ -15,7 +15,7 @@ from overbae.services.plan_limits import (require_seat_for_invite,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]def _user(email: str | None = None, **extra) -> User:diff --git a/tests/test_preparation_resume.py b/tests/test_preparation_resume.pyindex 8de3ab9d..fabf7e8e 100644--- a/tests/test_preparation_resume.py+++ b/tests/test_preparation_resume.py@@ -14,6 +14,8 @@ from modal_shared.preparation import processor_fingerprintfrom modal_shared.training_data import file_digestfrom overbae.services.sft_assets import preprocess+pytestmark = pytest.mark.covers("recovery")+def fixture(tmp_path, rows=9):source = tmp_path / "rows.jsonl.gz"diff --git a/tests/test_project_invites.py b/tests/test_project_invites.pyindex 3f678d78..9e8df2c4 100644--- a/tests/test_project_invites.py+++ b/tests/test_project_invites.py@@ -20,7 +20,7 @@ from overbae.models import ()from overbae.services.project_invites import claim_pending_invites-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("authentication")]@pytest.fixture(autouse=True)diff --git a/tests/test_projects.py b/tests/test_projects.pyindex 1dadd1bc..2f46783b 100644--- a/tests/test_projects.py+++ b/tests/test_projects.py@@ -12,7 +12,7 @@ from rest_framework.test import APIClientfrom overbae.models import Project, ProjectMembership-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("tenancy")]def _project_payload(slug_suffix: str | None = None) -> dict:diff --git a/tests/test_provider_pricing.py b/tests/test_provider_pricing.pyindex f1683433..c4b5a517 100644--- a/tests/test_provider_pricing.py+++ b/tests/test_provider_pricing.py@@ -1,9 +1,13 @@from decimal import Decimal+import pytest+from overbae.services import provider_pricingfrom overbae.services.compute_costs import estimate_usagefrom overbae.services.inference_pricing import gpu_usd_per_second+pytestmark = pytest.mark.covers("ledger")+def test_current_workspace_rates_drive_costs_without_historical_charges(monkeypatch):monkeypatch.setattr(diff --git a/tests/test_queue_metrics.py b/tests/test_queue_metrics.pyindex 79d6146b..1e827578 100644--- a/tests/test_queue_metrics.py+++ b/tests/test_queue_metrics.py@@ -8,6 +8,8 @@ from django.utils import timezonefrom overbae.services.queue_capacity import metric_data, read_workloads+pytestmark = pytest.mark.covers("topology")+def test_metrics_count_durable_waiting_not_only_admitted_broker_messages():now = timezone.now()diff --git a/tests/test_recommendation_constraints.py b/tests/test_recommendation_constraints.pyindex 15266b20..6f66a3c8 100644--- a/tests/test_recommendation_constraints.py+++ b/tests/test_recommendation_constraints.py@@ -7,6 +7,8 @@ from django.test import override_settingsfrom overbae.services.recommendation.constraints import Exclusion, eligible_models+pytestmark = pytest.mark.covers("recommendations")+_UNTRAINABLE = {"training_type": {"lora": {"enabled": False}, "full": {"enabled": False}}}_NO_TOOLS = {"supports_tool_calling": False}_SHORT_CONTEXT = {"context_length_sft": 2048}diff --git a/tests/test_recommendation_engine.py b/tests/test_recommendation_engine.pyindex 64e93bcc..4924c256 100644--- a/tests/test_recommendation_engine.py+++ b/tests/test_recommendation_engine.py@@ -18,6 +18,8 @@ from overbae.services.recommendation.constraints import eligible_modelsfrom overbae.services.recommendation.hyperparams import compute_hyperparamsfrom overbae.services.recommendation.ranking import DEFAULT_PICKS+pytestmark = pytest.mark.covers("recommendations")+_STATS = {"num_examples": 500,"avg_input_chars": 300,diff --git a/tests/test_recommendation_ranking.py b/tests/test_recommendation_ranking.pyindex 8a2b0a71..fc4ade71 100644--- a/tests/test_recommendation_ranking.py+++ b/tests/test_recommendation_ranking.py@@ -15,6 +15,8 @@ from overbae.services.recommendation.ranking import (select_default,)+pytestmark = pytest.mark.covers("recommendations")+_THIN_EVIDENCE_MODEL = "LiquidAI/LFM2.5-2.6B"_MEASURED_MODEL = "Qwen/Qwen3-8B"_TWO_SCORE_MODEL = "Qwen/Qwen2.5-7B-Instruct"diff --git a/tests/test_register_artifact_layout.py b/tests/test_register_artifact_layout.pyindex b7465a63..191fa1fa 100644--- a/tests/test_register_artifact_layout.py+++ b/tests/test_register_artifact_layout.py@@ -19,6 +19,8 @@ from overbae.modal.register_model import ( # noqa: E402resolve_artifact_dir,)+pytestmark = pytest.mark.covers("model-runtime")+def _touch(root: Path, *rels: str) -> None:for rel in rels:diff --git a/tests/test_retired_cursor_usage_migration.py b/tests/test_retired_cursor_usage_migration.pydeleted file mode 100644index fc096d40..00000000--- a/tests/test_retired_cursor_usage_migration.py+++ /dev/null@@ -1,104 +0,0 @@-from decimal import Decimal--import pytest-from django.db import connections-from django.db.backends.postgresql.base import DatabaseWrapper-from django.db.migrations.executor import MigrationExecutor-from django.test import override_settings-from test_workshop_training_migration import scratch_database as scratch_database--from overbae.models import OptimizerExperiment-from overbae.services.optimizer_ledger import complete_experiment--BEFORE = [("overbae", "0034_source_import_recovery")]-AFTER = [("overbae", "0035_retire_cursor_usage")]--[email protected]("conflicting_archive", [False, True])-def test_retiring_usage_preserves_experiments_and_ledger(- scratch_database, django_db_blocker, conflicting_archive-):- original = connections["default"]- database = DatabaseWrapper(- {**original.settings_dict, "NAME": scratch_database}, alias="default"- )- with django_db_blocker.unblock(), override_settings(MIGRATION_MODULES={}):- connections["default"] = database- try:- executor = MigrationExecutor(database)- executor.migrate(BEFORE)- apps = executor.loader.project_state(BEFORE).apps- project = apps.get_model("overbae", "Project").objects.create(name="Retained")- capability = apps.get_model("overbae", "Capability").objects.create(- project=project, name="Retained", slug="retained"- )- user = apps.get_model("overbae", "User").objects.create(email="[email protected]")- experiments = apps.get_model("overbae", "OptimizerExperiment")- usage = {"input_tokens": 9007199254740993, "output_tokens": 20, "unknown": [0, None]}- state = {"eval_pending": {}, "winner_score": 42}- if conflicting_archive:- state["archived_cursor_usage"] = {"separate": "retained evidence"}- experiment = experiments.objects.create(- project=project,- capability=capability,- triggered_by=user,- state=state,- cursor_usage=usage,- )- empty = experiments.objects.create(- project=project, capability=capability, state={"keep": True}- )- ledger = apps.get_model("overbae", "BillingTelemetry")- receipt = ledger.objects.create(- user=user,- project=project,- service="cursor-agent",- amount=Decimal("-0.55"),- idempotency_key=f"cursor-agent:optimizer:{experiment.pk}",- metadata={"llm_usage": {"served_model": "composer-2.5"}},- )- before_receipts = list(ledger.objects.values())-- executor = MigrationExecutor(database)- if conflicting_archive:- with pytest.raises(RuntimeError, match="archive already exists"):- executor.migrate(AFTER)- retained = experiments.objects.get(pk=experiment.pk)- assert retained.state == state and retained.cursor_usage == usage- assert list(ledger.objects.values()) == before_receipts- return-- executor.migrate(AFTER)- apps = executor.loader.project_state(AFTER).apps- current = apps.get_model("overbae", "OptimizerExperiment")- retained = current.objects.get(pk=experiment.pk)- assert retained.state == {**state, "archived_cursor_usage": usage}- assert current.objects.get(pk=empty.pk).state == {"keep": True}- assert retained.updated_at == experiment.updated_at- with database.cursor() as cursor:- columns = database.introspection.get_table_description(- cursor, "overbae_optimizerexperiment"- )- assert "cursor_usage" not in {column.name for column in columns}-- executor = MigrationExecutor(database)- executor.migrate(BEFORE)- apps = executor.loader.project_state(BEFORE).apps- restored = apps.get_model("overbae", "OptimizerExperiment").objects.get(- pk=experiment.pk- )- assert restored.cursor_usage == usage- assert "archived_cursor_usage" not in restored.state- assert restored.state == state- assert list(ledger.objects.values()) == before_receipts-- executor = MigrationExecutor(database)- executor.migrate(executor.loader.graph.leaf_nodes("overbae"))- completed = complete_experiment(OptimizerExperiment.objects.get(pk=experiment.pk))- assert completed.status == "completed"- assert completed.state["archived_cursor_usage"] == usage- assert list(ledger.objects.values()) == before_receipts- assert ledger.objects.get(pk=receipt.pk).amount == Decimal("-0.55")- finally:- database.close()- connections["default"] = originaldiff --git a/tests/test_reusable_workshop_journey.py b/tests/test_reusable_workshop_journey.pyindex 0ce1327a..a895ff98 100644--- a/tests/test_reusable_workshop_journey.py+++ b/tests/test_reusable_workshop_journey.py@@ -1,4 +1,3 @@-import asyncioimport ioimport jsonimport os@@ -9,6 +8,8 @@ import zipfilefrom unittest.mock import patchimport pytest+from asgiref.sync import async_to_sync+from mcp_fixtures import call_toolfrom rest_framework.test import APIClientfrom overbae.models import APIToken, Dataset, Project, ProjectMembership, Span, User@@ -21,7 +22,6 @@ from overbae.services.datasets import (workbench,)from overbae.services.datasets.lifecycle import DatasetError-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext, bind_contextfrom overbae.services.mcp.resources import read_resourcefrom tests.workshop_script_fixtures import (@@ -34,7 +34,7 @@ from tests.workshop_script_fixtures import (select_script,)-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("data-logic")]@pytest.mark.parametrize("eligible", [[True, False, True], [True, True], [False, False]])@@ -212,18 +212,16 @@ def test_conditional_revision_retrieval_adaptation_and_conflict_recovery():assert run["status"] == "completed"scoped = call(context, "inspect_dataset_workbench", pipeline=revised["id"])assert scoped["runs"] == []- stale = asyncio.run(- CATALOG.call(- "save_dataset_pipeline",- {- "name": "Stale",- "request_key": "stale",- "pipeline": first["pipeline_id"],- "expected_revision": 1,- "package": first["package"],- },- context,- )+ stale = call_tool(+ "save_dataset_pipeline",+ {+ "name": "Stale",+ "request_key": "stale",+ "pipeline": first["pipeline_id"],+ "expected_revision": 1,+ "package": first["package"],+ },+ context,)assert stale.isError and stale.structuredContent["error"]["code"] == "revision_conflict"unrelated = Project.objects.create(name="Other project", slug="conditional-other")@@ -234,9 +232,7 @@ def test_conditional_revision_retrieval_adaptation_and_conflict_recovery():request_key="private",package=retained_package(unrelated, context.user, [filter_script("eligible", True)]),)- denied = asyncio.run(- CATALOG.call("inspect_dataset_workbench", {"pipeline": str(foreign.pk)}, context)- )+ denied = call_tool("inspect_dataset_workbench", {"pipeline": str(foreign.pk)}, context)assert denied.isError@@ -276,7 +272,7 @@ def test_agent_authored_branches_are_retained_executed_and_read_back(settings):assert [cell.review["step_id"] for cell in cells] == ["eligible", "ineligible"]with bind_context(context):retained = json.loads(- asyncio.run(read_resource(f"overmind://dataset-pipelines/{recipe['id']}"))[0].content+ async_to_sync(read_resource)(f"overmind://dataset-pipelines/{recipe['id']}")[0].content)assert retained["flow"] == recipe["flow"]with pytest.raises(DatasetError, match="Cycles"):@@ -291,7 +287,7 @@ def test_agent_authored_branches_are_retained_executed_and_read_back(settings):def call(context, tool_name, **arguments):- result = asyncio.run(CATALOG.call(tool_name, arguments, context))+ result = call_tool(tool_name, arguments, context)assert not result.isError, result.structuredContentreturn result.structuredContent@@ -831,20 +827,16 @@ def test_revisions_conflicts_tenancy_and_resources():),)["pipeline"]assert revised["revision"] == 2 and revised["parent"] == recipe["id"]- stale = asyncio.run(- CATALOG.call(- "save_dataset_pipeline",- {- "name": "Stale",- "request_key": "stale",- "pipeline": recipe["pipeline_id"],- "expected_revision": 1,- "package": retained_package(- context.project, context.user, [select_script(["value"])]- ),- },- context,- )+ stale = call_tool(+ "save_dataset_pipeline",+ {+ "name": "Stale",+ "request_key": "stale",+ "pipeline": recipe["pipeline_id"],+ "expected_revision": 1,+ "package": retained_package(context.project, context.user, [select_script(["value"])]),+ },+ context,)assert stale.isErrorother = Project.objects.create(name="Other", slug="other")@@ -855,48 +847,40 @@ def test_revisions_conflicts_tenancy_and_resources():request_key="private",package=retained_package(other, context.user, [select_script(["value"])]),)- rejected = asyncio.run(- CATALOG.call(- "run_dataset_pipeline",- {- "dataset": str(dataset.pk),- "pipeline": str(outside.pk),- "source_cell": str(dataset.active_cell.pk),- "source_fingerprint": dataset.active_cell.fingerprint,- "request_key": "outside",- },- context,- )+ rejected = call_tool(+ "run_dataset_pipeline",+ {+ "dataset": str(dataset.pk),+ "pipeline": str(outside.pk),+ "source_cell": str(dataset.active_cell.pk),+ "source_fingerprint": dataset.active_cell.fingerprint,+ "request_key": "outside",+ },+ context,)assert rejected.isErrorassert dataset.cells.count() == 1- conflict = asyncio.run(- CATALOG.call(- "save_dataset_pipeline",- {- "name": "Changed",- "request_key": "original",- "package": retained_package(- context.project, context.user, [select_script(["value"])]- ),- },- context,- )+ conflict = call_tool(+ "save_dataset_pipeline",+ {+ "name": "Changed",+ "request_key": "original",+ "package": retained_package(context.project, context.user, [select_script(["value"])]),+ },+ context,)assert conflict.isErrorassert conflict.structuredContent["error"]["code"] == "request_key_conflict"- wrong_source = asyncio.run(- CATALOG.call(- "run_dataset_pipeline",- {- "dataset": str(dataset.pk),- "pipeline": recipe["id"],- "source_cell": str(dataset.active_cell.pk),- "source_fingerprint": "0" * 64,- "request_key": "wrong-fingerprint",- },- context,- )+ wrong_source = call_tool(+ "run_dataset_pipeline",+ {+ "dataset": str(dataset.pk),+ "pipeline": recipe["id"],+ "source_cell": str(dataset.active_cell.pk),+ "source_fingerprint": "0" * 64,+ "request_key": "wrong-fingerprint",+ },+ context,)assert wrong_source.isErrorassert wrong_source.structuredContent["error"]["code"] == "source_conflict"@@ -907,7 +891,7 @@ def test_revisions_conflicts_tenancy_and_resources():result = list(await read_resource(f"overmind://dataset-pipelines/{recipe['id']}"))return json.loads(result[0].content)- assert asyncio.run(read())["revision"] == 1+ assert async_to_sync(read)()["revision"] == 1job = execute(context, dataset, recipe, "original-still-works")assert job["status"] == "completed"assert job["details"]["operation"]["event_count"] > 0diff --git a/tests/test_reusable_workshop_migration.py b/tests/test_reusable_workshop_migration.pydeleted file mode 100644index 70f78a4c..00000000--- a/tests/test_reusable_workshop_migration.py+++ /dev/null@@ -1,74 +0,0 @@-from django.db import connections-from django.db.backends.sqlite3.base import DatabaseWrapper-from django.db.migrations.executor import MigrationExecutor-from django.test import override_settings---def test_project_recipe_cutover_preserves_history_and_resolves_request_collisions(- tmp_path, django_db_blocker-):- original = connections["default"]- database = DatabaseWrapper(- {**original.settings_dict, "NAME": str(tmp_path / "recipes.sqlite3")}, alias="default"- )- with django_db_blocker.unblock(), override_settings(MIGRATION_MODULES={}):- connections["default"] = database- try:- executor = MigrationExecutor(database)- before = [("overbae", "0031_dataset_transfer")]- executor.migrate(before)- old = executor.loader.project_state(before).apps- project = old.get_model("overbae", "Project").objects.create(- name="Existing", slug="existing"- )- identities = []- for number in range(2):- dataset = old.get_model("overbae", "Dataset").objects.create(- project=project, name=str(number)- )- cell = old.get_model("overbae", "Cell").objects.create(- dataset=dataset, position=1, fingerprint="a" * 64- )- recipe = old.get_model("overbae", "DatasetPipeline").objects.create(- dataset=dataset,- name="Projection",- request_key="same-key",- fingerprint="b" * 64,- steps=[{"operation": "select", "columns": ["value"]}],- )- run = old.get_model("overbae", "DatasetPipelineRun").objects.create(- dataset=dataset,- pipeline=recipe,- source=cell,- output=cell,- source_fingerprint="a" * 64,- request_key="run",- fingerprint="c" * 64,- state="completed",- result={"rows": 10000},- )- identities.append((recipe.pk, run.pk, cell.pk))- executor = MigrationExecutor(database)- after = [("overbae", "0032_datasetpipelinebinding_datasetpipelinepackage_and_more")]- executor.migrate(after)- current = executor.loader.project_state(after).apps- requests, attempts = set(), set()- for recipe_id, run_id, cell_id in identities:- recipe = current.get_model("overbae", "DatasetPipeline").objects.get(pk=recipe_id)- run = current.get_model("overbae", "DatasetPipelineRun").objects.get(pk=run_id)- assert (- recipe.project_id == project.pk- and recipe.family == recipe.pk- and recipe.revision == 1- )- assert (- run.output_id == cell_id- and run.result == {"rows": 10000}- and run.state == "completed"- )- requests.add(recipe.request_key)- attempts.add(run.attempt)- assert len(requests) == len(attempts) == 2- finally:- database.close()- connections["default"] = originaldiff --git a/tests/test_runtime_envelope.py b/tests/test_runtime_envelope.pyindex daab704c..96df5947 100644--- a/tests/test_runtime_envelope.py+++ b/tests/test_runtime_envelope.py@@ -3,9 +3,13 @@ from __future__ import annotationsimport jsonfrom types import SimpleNamespace+import pytest+from overbae.api import overmind_attrs as oc_attrsfrom overbae.services.transcripts import envelope, normalizer+pytestmark = pytest.mark.covers("sdk-wire")+def expectation(exp_id="currency", kind="contains", spec="USD", scope="trace", gate=True):return {"id": exp_id, "kind": kind, "spec": spec, "scope": scope, "gate": gate}diff --git a/tests/test_sandbox_packages.py b/tests/test_sandbox_packages.pyindex a1882ffc..d106ec2f 100644--- a/tests/test_sandbox_packages.py+++ b/tests/test_sandbox_packages.py@@ -9,6 +9,8 @@ import pytestfrom sandbox import execute, packagesfrom sandbox.protocol import HeaderReader, header_bytes+pytestmark = pytest.mark.covers("sandbox")+def run_package(sandbox_server, code, *, limits=None, runtime=None, files=None):url, token = sandbox_serverdiff --git a/tests/test_sdk_permutations.py b/tests/test_sdk_permutations.pyindex 87ea11e8..fcc2b836 100644--- a/tests/test_sdk_permutations.py+++ b/tests/test_sdk_permutations.py@@ -20,7 +20,7 @@ from overbae.models import (OptimizerExperiment,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("sdk-wire")]URL = "/api/v1/chat/completions"diff --git a/tests/test_seat_downgrade.py b/tests/test_seat_downgrade.pyindex d4461538..057f43ad 100644--- a/tests/test_seat_downgrade.py+++ b/tests/test_seat_downgrade.py@@ -6,7 +6,7 @@ from factories import make_project, make_userfrom overbae.models import ProjectMembershipfrom overbae.services.seat_downgrade import enforce_free_seats_after_downgrade-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("authentication")]def test_strips_invitees_keeps_creator():diff --git a/tests/test_serving_args.py b/tests/test_serving_args.pyindex 503ff12a..492af6f5 100644--- a/tests/test_serving_args.py+++ b/tests/test_serving_args.py@@ -5,6 +5,8 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+import pytest+from modal_shared.serving.args import (CUDAGRAPH_CAPTURE_SIZES,MAX_LORA_SLOTS,@@ -12,6 +14,8 @@ from modal_shared.serving.args import (build_vllm_args,)+pytestmark = pytest.mark.covers("model-runtime")+def _checkpoint(tmp_path: Path, *, experts: int = 0) -> Path:d = tmp_path / "ckpt"diff --git a/tests/test_serving_artifacts.py b/tests/test_serving_artifacts.pyindex 9949bbed..955b61fb 100644--- a/tests/test_serving_artifacts.py+++ b/tests/test_serving_artifacts.py@@ -6,6 +6,8 @@ import pytestfrom modal_shared.serving import artifacts+pytestmark = pytest.mark.covers("lineage")+def base(tmp_path):(tmp_path / "config.json").write_text('{"model_type":"test"}')diff --git a/tests/test_sessions.py b/tests/test_sessions.pyindex 852b2d27..e027297b 100644--- a/tests/test_sessions.py+++ b/tests/test_sessions.py@@ -31,7 +31,7 @@ from overbae.models import ()from overbae.tasks import connector_sync-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("otlp-ingest")]SESSIONS_URL = "/api/sessions/"TRACES_URL = "/api/traces/"diff --git a/tests/test_sft_base_weights.py b/tests/test_sft_base_weights.pyindex 19cbbc5d..ec37456f 100644--- a/tests/test_sft_base_weights.py+++ b/tests/test_sft_base_weights.py@@ -11,6 +11,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "overbae" / "servicfrom basepath import base_weights_for # noqa: E402+pytestmark = pytest.mark.covers("model-runtime")+MODEL = "Qwen/Qwen3-1.7B"DIRNAME = "Qwen--Qwen3-1.7B"diff --git a/tests/test_sft_causal_mask.py b/tests/test_sft_causal_mask.pyindex 50f3d656..f6db9c89 100644--- a/tests/test_sft_causal_mask.py+++ b/tests/test_sft_causal_mask.py@@ -1,7 +1,11 @@from types import SimpleNamespace+import pytest+from overbae.services.sft_assets.causal_mask import install_training_causal_mask+pytestmark = pytest.mark.covers("model-runtime")+def _model(module: str, model_type: str = "qwen3"):seen: dict = {}diff --git a/tests/test_sft_gemma4_hooks.py b/tests/test_sft_gemma4_hooks.pyindex 01091a62..1f1282a9 100644--- a/tests/test_sft_gemma4_hooks.py+++ b/tests/test_sft_gemma4_hooks.py@@ -3,6 +3,10 @@ from __future__ import annotationsimport sysfrom pathlib import Path+import pytest++pytestmark = pytest.mark.covers("model-runtime")+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "overbae" / "services" / "sft_assets"))diff --git a/tests/test_sft_gpt_oss_hooks.py b/tests/test_sft_gpt_oss_hooks.pyindex ab9d520b..9c2b5131 100644--- a/tests/test_sft_gpt_oss_hooks.py+++ b/tests/test_sft_gpt_oss_hooks.py@@ -3,6 +3,10 @@ from __future__ import annotationsimport sysfrom pathlib import Path+import pytest++pytestmark = pytest.mark.covers("model-runtime")+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "overbae" / "services" / "sft_assets"))diff --git a/tests/test_sft_no_truncation.py b/tests/test_sft_no_truncation.pyindex 1552a106..3b3479c2 100644--- a/tests/test_sft_no_truncation.py+++ b/tests/test_sft_no_truncation.py@@ -6,6 +6,8 @@ import pytestfrom overbae.services.sft_assets.truncation import refuse_truncation+pytestmark = pytest.mark.covers("model-runtime")+def test_refuse_truncation_raises_on_overlong_row():with pytest.raises(RuntimeError, match="refusing to truncate"):diff --git a/tests/test_sft_packing.py b/tests/test_sft_packing.pyindex 78a582fd..99074d1a 100644--- a/tests/test_sft_packing.py+++ b/tests/test_sft_packing.py@@ -1,3 +1,5 @@+import pytest+from overbae.services.sft_assets.packing import (packs_safely,sft_collator_flags,@@ -5,6 +7,8 @@ from overbae.services.sft_assets.packing import (use_row_packing,)+pytestmark = pytest.mark.covers("model-runtime")+def test_sdpa_does_not_isolate_packed_rows():assert not packs_safely("sdpa")diff --git a/tests/test_sft_preparation_process.py b/tests/test_sft_preparation_process.pyindex bdadc3aa..ce795953 100644--- a/tests/test_sft_preparation_process.py+++ b/tests/test_sft_preparation_process.py@@ -16,6 +16,8 @@ from modal_shared.preparation import (from overbae.services.finetuning_runner import sanitize_job_errorfrom overbae.services.sft_assets import preprocess+pytestmark = pytest.mark.covers("model-runtime")+def test_training_edits_preserve_token_cache_but_invalidate_optimizer_resume(tmp_path):(tmp_path / "preprocess.py").write_text("tokenize input")diff --git a/tests/test_sft_qwen35_hooks.py b/tests/test_sft_qwen35_hooks.pyindex 46156b16..25e20e3d 100644--- a/tests/test_sft_qwen35_hooks.py+++ b/tests/test_sft_qwen35_hooks.py@@ -4,10 +4,14 @@ import sysfrom pathlib import Pathfrom types import SimpleNamespace+import pytest+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "overbae" / "services" / "sft_assets"))from families.qwen35 import _seq_len_from_mask_kwargs, hooks+pytestmark = pytest.mark.covers("model-runtime")+def test_qwen35_sdpa_and_flex_off():overrides = hooks.env_overrides(use_lora=True)diff --git a/tests/test_sft_token_accuracy.py b/tests/test_sft_token_accuracy.pyindex dd0afdf6..1576932f 100644--- a/tests/test_sft_token_accuracy.py+++ b/tests/test_sft_token_accuracy.py@@ -15,6 +15,8 @@ import pytestfrom modal_shared.training_telemetry import record_stage+pytestmark = pytest.mark.covers("metrics-math")+ASSETS = Path(__file__).resolve().parents[1] / "overbae/services/sft_assets"diff --git a/tests/test_sft_tool_rows.py b/tests/test_sft_tool_rows.pyindex 965afa7a..14c3be1f 100644--- a/tests/test_sft_tool_rows.py+++ b/tests/test_sft_tool_rows.py@@ -5,12 +5,16 @@ from __future__ import annotationsimport sysfrom pathlib import Path+import pytest+# sft_assets is uploaded to Modal as a flat directory, so its modules import each# other by bare name and only resolve with the directory itself on sys.path.sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "overbae" / "services" / "sft_assets"))from pretok import normalize_openai_wire # noqa: E402+pytestmark = pytest.mark.covers("model-runtime")+CALL = {"id": "call_1","type": "function",diff --git a/tests/test_sft_training_chat_template.py b/tests/test_sft_training_chat_template.pyindex ab636ebc..f74dd370 100644--- a/tests/test_sft_training_chat_template.py+++ b/tests/test_sft_training_chat_template.py@@ -3,6 +3,8 @@ from __future__ import annotationsimport sysfrom pathlib import Path+import pytest+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "overbae" / "services" / "sft_assets"))from training_chat_template import ( # noqa: E402@@ -10,6 +12,8 @@ from training_chat_template import ( # noqa: E402patch_known_training_template,)+pytestmark = pytest.mark.covers("model-runtime")+_ASSETS = Path(__file__).resolve().parents[1] / "overbae" / "services" / "sft_assets"diff --git a/tests/test_shared_base_http_benchmark.py b/tests/test_shared_base_http_benchmark.pyindex dd25ec82..33b44e57 100644--- a/tests/test_shared_base_http_benchmark.py+++ b/tests/test_shared_base_http_benchmark.py@@ -6,6 +6,8 @@ import pytestfrom scripts import validate_shared_base_serving as benchmark+pytestmark = pytest.mark.covers("measured-facts")+def test_http_ttft_ignores_idle_pings_and_role_chunks(monkeypatch):response = MagicMock()diff --git a/tests/test_shared_base_serving.py b/tests/test_shared_base_serving.pyindex d2cde17e..5b0df106 100644--- a/tests/test_shared_base_serving.py+++ b/tests/test_shared_base_serving.py@@ -12,6 +12,8 @@ import pytestfrom modal_shared.stacks import WORKER_ALLOWED, worker_cls_namefrom overbae.modal import modal_vllm_worker as serving+pytestmark = pytest.mark.covers("model-runtime")+def test_shared_worker_resolves_family_from_sealed_base(monkeypatch, tmp_path):obj = serving._BaseVLLMWorker()diff --git a/tests/test_shared_base_weights.py b/tests/test_shared_base_weights.pyindex 2a9b64cb..7a045636 100644--- a/tests/test_shared_base_weights.py+++ b/tests/test_shared_base_weights.py@@ -8,6 +8,8 @@ from unittest.mock import MagicMock, Mockimport pytest+pytestmark = pytest.mark.covers("model-runtime")+@pytest.fixturedef loader(monkeypatch):diff --git a/tests/test_signals.py b/tests/test_signals.pyindex b01f9d1a..5b0cd962 100644--- a/tests/test_signals.py+++ b/tests/test_signals.py@@ -1,10 +1,11 @@-import asyncioimport uuidfrom datetime import timedeltafrom types import SimpleNamespaceimport pytest+from asgiref.sync import async_to_syncfrom django.utils import timezone+from mcp_fixtures import call_toolfrom rest_framework.test import APIClientfrom overbae.innermind.signals import (@@ -24,10 +25,9 @@ from overbae.models import (Span,User,)-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("metrics-math")]@pytest.fixture@@ -42,7 +42,7 @@ def context():def call(context, name, arguments):- result = asyncio.run(CATALOG.call(name, arguments, context))+ result = call_tool(name, arguments, context)assert not result.isError, result.contentreturn result.structuredContent@@ -66,8 +66,8 @@ def test_leak_signal_does_not_treat_timing_decimals_as_card_numbers():def output(value):return SimpleNamespace(name="run", attributes={"output": value})- assert asyncio.run(signal.check([output('"step_interval": 3.8305869102478027')])) is None- assert asyncio.run(signal.check([output("card 4242 4242 4242 4242")])) == (+ assert async_to_sync(signal.check)([output('"step_interval": 3.8305869102478027')]) is None+ assert async_to_sync(signal.check)([output("card 4242 4242 4242 4242")]) == ("sensitive data in outputs: run (card number)")@@ -94,8 +94,8 @@ def test_defaults_generate_session_evidence_without_subscriptions_or_model_callsother_project = Project.objects.create(name="Other", slug=f"other-{uuid.uuid4()}")other = span(other_project)assert ctx.project.id in projects_with_recent_spans()- asyncio.run(SignalRunner(ctx.project.id).run())- asyncio.run(SignalRunner(ctx.project.id).run())+ async_to_sync(SignalRunner(ctx.project.id).run)()+ async_to_sync(SignalRunner(ctx.project.id).run)()event = SignalEvent.objects.get(project=ctx.project, conversation=session, signal_type="errors")assert set(event.details["trace_ids"]) == {first.trace_id, second.trace_id}assert event.subscription_id is None@@ -137,14 +137,14 @@ def test_project_and_capability_mutes_override_defaults(context):assert not next(s for s in call(ctx, "list_signals", {})["signals"] if s["signal_type"] == "errors")["enabled"]- asyncio.run(SignalRunner(ctx.project.id).run())+ async_to_sync(SignalRunner(ctx.project.id).run)()assert not SignalEvent.objects.filter(signal_type="errors").exists()call(ctx,"set_signal_subscription",{"signal_type": "errors", "capability": "answer", "enabled": True},)- asyncio.run(SignalRunner(ctx.project.id).run())+ async_to_sync(SignalRunner(ctx.project.id).run)()assert list(SignalEvent.objects.filter(signal_type="errors").values_list("trace_id", flat=True)) == [scoped.trace_id]@@ -155,7 +155,7 @@ def test_project_and_capability_mutes_override_defaults(context):{"signal_type": "errors", "capability": "answer", "enabled": False},)another = span(ctx.project, capability=cap)- asyncio.run(SignalRunner(ctx.project.id).run())+ async_to_sync(SignalRunner(ctx.project.id).run)()assert set(SignalEvent.objects.filter(signal_type="errors").values_list("trace_id", flat=True)) == {scoped.trace_id, unscoped.trace_id}@@ -192,7 +192,7 @@ def test_signal_scan_releases_payloads_between_complete_groups(context):post_init.connect(observe, sender=Span)try:- asyncio.run(SignalRunner(ctx.project.id).run())+ async_to_sync(SignalRunner(ctx.project.id).run)()finally:post_init.disconnect(observe, sender=Span)assert peak <= 2@@ -212,7 +212,7 @@ def test_signal_scan_reports_oversized_group_without_dropping_other_groups(conteSpan.objects.filter(pk=item.pk).update(attributes={"padding": "x" * (5 * 1024 * 1024)})small = span(ctx.project)with pytest.raises(SignalInputTooLargeError, match="1 signal groups exceed"):- asyncio.run(SignalRunner(ctx.project.id).run())+ async_to_sync(SignalRunner(ctx.project.id).run)()assert not SignalEvent.objects.filter(conversation=session).exists()assert SignalEvent.objects.filter(trace_id=small.trace_id, signal_type="errors").exists()@@ -233,10 +233,8 @@ def test_signal_batch_rechecks_bytes_before_materializing_payloads(context):post_init.connect(observe, sender=Span)try:with pytest.raises(SignalInputTooLargeError, match="changed or exceeded"):- asyncio.run(- SignalRunner(ctx.project.id).run_batch(- {item.pk: f"trace:{item.trace_id}"}, [], [], "2026-10-17"- )+ async_to_sync(SignalRunner(ctx.project.id).run_batch)(+ {item.pk: f"trace:{item.trace_id}"}, [], [], "2026-10-17")finally:post_init.disconnect(observe, sender=Span)@@ -265,7 +263,7 @@ def test_signal_scan_continues_after_concurrent_payload_growth(context):yield idswith pytest.raises(SignalInputTooLargeError, match="1 signal groups changed"):- asyncio.run(ConcurrentGrowthRunner(ctx.project.id).run())+ async_to_sync(ConcurrentGrowthRunner(ctx.project.id).run)()assert set(SignalEvent.objects.filter(signal_type="errors").values_list("trace_id", flat=True)) == {item.trace_id for item in items[1:]}diff --git a/tests/test_snapshot_executor.py b/tests/test_snapshot_executor.pyindex ef2614f8..56cfbaba 100644--- a/tests/test_snapshot_executor.py+++ b/tests/test_snapshot_executor.py@@ -7,6 +7,8 @@ import pytestimport modal_shared.serving+pytestmark = pytest.mark.covers("model-runtime")+def test_snapshot_rendezvous_is_fresh_and_single_rank(monkeypatch):class Executor:diff --git a/tests/test_source_import_migration.py b/tests/test_source_import_migration.pydeleted file mode 100644index adc070ae..00000000--- a/tests/test_source_import_migration.py+++ /dev/null@@ -1,82 +0,0 @@-import pytest-from django.db import connections-from django.db.backends.postgresql.base import DatabaseWrapper-from django.db.migrations.executor import MigrationExecutor-from django.db.migrations.recorder import MigrationRecorder-from django.test import override_settings-from django.utils import timezone-from test_workshop_training_migration import scratch_database as scratch_database--TARGET = ("overbae", "0034_source_import_recovery")--[email protected]("start", ["0015_workshop_execution_clock", "0033_training_monitoring"])-def test_each_applied_branch_upgrades_without_losing_source_or_training_state(- start,- scratch_database,- django_db_blocker,-):- original = connections["default"]- database = DatabaseWrapper(- {**original.settings_dict, "NAME": scratch_database}, alias="default"- )- with django_db_blocker.unblock(), override_settings(MIGRATION_MODULES={}):- connections["default"] = database- try:- executor = MigrationExecutor(database)- executor.migrate([("overbae", start)])- apps = executor.loader.project_state([("overbae", start)]).apps- project = apps.get_model("overbae", "Project").objects.create(name="Retained")- dataset = apps.get_model("overbae", "Dataset").objects.create(- project=project, name="Source", state="idle"- )- cell = apps.get_model("overbae", "Cell").objects.create(- dataset=dataset, position=0, state="ok", fingerprint="retained-cell", rows=3- )- job = apps.get_model("overbae", "FinetuningJob").objects.create(- project=project,- dataset=dataset,- cell=cell,- status="succeeded",- output_model_name="retained-model",- )- if start.startswith("0015"):- dataset.workshop_queued_at = timezone.now()- dataset.save(update_fields=["workshop_queued_at"])- receipt = apps.get_model("overbae", "DatasetImport").objects.create(- dataset=dataset,- inputs={"source": {"rows": []}},- handoff_pending=True,- handoff_attempts=0,- queued_at=timezone.now(),- )- before = set(MigrationRecorder(database).applied_migrations())- executor = MigrationExecutor(database)- executor.migrate([TARGET])- apps = executor.loader.project_state([TARGET]).apps- retained = apps.get_model("overbae", "FinetuningJob").objects.get(pk=job.pk)- assert retained.cell_id == cell.pk and retained.output_model_name == "retained-model"- assert (- apps.get_model("overbae", "Cell").objects.get(pk=cell.pk).fingerprint- == "retained-cell"- )- assert before <= set(MigrationRecorder(database).applied_migrations())- if start.startswith("0015"):- assert (- apps.get_model("overbae", "DatasetImport").objects.get(pk=receipt.pk).inputs- == receipt.inputs- )- archived = {- row.kind: row.payload- for row in apps.get_model("overbae", "DatasetHistory").objects.filter(- dataset_id=dataset.pk- )- }- assert (- archived["workshop_ownership"]["queued_at"]- == dataset.workshop_queued_at.isoformat()- )- assert archived["import_handoff"]["pending"] is True- finally:- database.close()- connections["default"] = originaldiff --git a/tests/test_span_cost.py b/tests/test_span_cost.pyindex 79153535..c97d2791 100644--- a/tests/test_span_cost.py+++ b/tests/test_span_cost.py@@ -18,7 +18,7 @@ from rest_framework_simplejwt.tokens import RefreshTokenfrom overbae.models import Capability, Project, ProjectMembership, User-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("metrics-math")]# Prices are looked up at the span's start time, so a fixed date keeps them stable._START_NS = int(datetime(2026, 1, 1, tzinfo=UTC).timestamp() * 1e9)diff --git a/tests/test_span_evidence.py b/tests/test_span_evidence.pyindex f84eddd3..cab39fd1 100644--- a/tests/test_span_evidence.py+++ b/tests/test_span_evidence.py@@ -1,6 +1,8 @@import jsonfrom types import SimpleNamespace+import pytest+from overbae.services.transcripts.normalizer import reconstruct_spansfrom overbae.services.transcripts.span_evidence import (build_span_tree,@@ -9,6 +11,8 @@ from overbae.services.transcripts.span_evidence import (unwrap_payload,)+pytestmark = pytest.mark.covers("otlp-ingest")+def _span(**kwargs):defaults = {diff --git a/tests/test_span_tenancy.py b/tests/test_span_tenancy.pyindex e98046a1..f92f3a9c 100644--- a/tests/test_span_tenancy.py+++ b/tests/test_span_tenancy.py@@ -12,7 +12,7 @@ from opentelemetry.proto.trace.v1.trace_pb2 import Span as ProtoSpanfrom overbae.models import Span-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("tenancy")]def test_a_reused_span_id_from_another_project_leaves_the_owner_row_untouched():diff --git a/tests/test_span_usage_emission.py b/tests/test_span_usage_emission.pyindex 00380d25..5fc134c1 100644--- a/tests/test_span_usage_emission.py+++ b/tests/test_span_usage_emission.py@@ -2,10 +2,14 @@ from __future__ import annotationsfrom unittest import mock+import pytest+from overbae.api import overmind_attrs as oc_attrsfrom overbae.api.span_usage import usage_span_attributesfrom overbae.services import model_catalog+pytestmark = pytest.mark.covers("sdk-wire")+class _Usage:"""OpenAI/OpenRouter-style usage object (attribute access, no ``cost``)."""diff --git a/tests/test_stacks.py b/tests/test_stacks.pyindex 4200f76d..d7d9076a 100644--- a/tests/test_stacks.py+++ b/tests/test_stacks.py@@ -3,6 +3,8 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+import pytest+from modal_shared.modelfam import resolvefrom modal_shared.modelfam.registry import all_familiesfrom modal_shared.stacks import (@@ -18,6 +20,8 @@ from modal_shared.stacks import (worker_cls_name,)+pytestmark = pytest.mark.covers("model-runtime")+_MODELS_JSON = Path(__file__).resolve().parents[1] / "overbae" / "modal" / "models.json"diff --git a/tests/test_sync_api.py b/tests/test_sync_api.pyindex 880b60ef..81c7bae6 100644--- a/tests/test_sync_api.py+++ b/tests/test_sync_api.py@@ -3,7 +3,6 @@from __future__ import annotationsimport uuid-from datetime import UTC, datetimefrom unittest.mock import patchimport pytest@@ -18,6 +17,8 @@ from overbae.models import ()from overbae.services.codebase.flow import build_capability_flow+pytestmark = pytest.mark.covers("identity")+PROJECT_ID = uuid.UUID("11111111-1111-1111-1111-111111111111")@@ -61,37 +62,7 @@ def _snapshot(capabilities):}-def test_scan_provenance_roundtrips_and_sync_time_is_server_owned(client, project):- source = {- "repository": "acme/agent",- "directory": ".",- "branch": "main",- "commit": "a" * 40,- "dirty": True,- "fingerprint": "b" * 64,- "scanned_at": "2026-09-20T12:00:00+00:00",- }- body = {- **_snapshot([_cap()]),- "repository_snapshot": source,- "last_synced_at": "2000-01-01T00:00:00Z",- }- now = datetime(2026, 9, 27, 12, tzinfo=UTC)- with patch("overbae.services.sync.timezone.now", return_value=now):- response = client.post("/api/v1/sync", body, format="json")- assert response.status_code == 200, response.data- assert response.data["repository_snapshot"] == source- assert response.data["last_synced_at"] == "2026-09-27T12:00:00+00:00"- pulled = client.get("/api/v1/sync", {"project_id": str(project.id)}).data- assert pulled["repository_snapshot"] == source- graph = client.get("/api/agent/", {"project": str(project.id)}).data- assert graph["repository_snapshot"] == source- assert graph["last_synced_at"] == response.data["last_synced_at"]- response = client.post("/api/v1/sync", _snapshot([_cap()]), format="json")- assert response.data["repository_snapshot"] is None--[email protected]("lineage")@pytest.mark.django_dbdef test_invalid_provenance_does_not_replace_project_snapshot(client, project):response = client.post(@@ -112,65 +83,13 @@ def _quiet_side_effects():yield[email protected]("authentication")@pytest.mark.django_dbdef test_missing_api_key_is_unauthorized():resp = APIClient().post("/api/v1/sync", _snapshot([_cap()]), format="json")assert resp.status_code in (401, 403)-def test_post_assigns_ids_and_get_roundtrips(client):- posted = client.post("/api/v1/sync", _snapshot([_cap()]), format="json")- assert posted.status_code == 200, posted.data- caps = posted.data["capabilities"]- assert len(caps) == 1- cap_id = caps[0]["id"]- assert cap_id- assert caps[0]["slug"] == "support-agent"- assert caps[0]["eval_metrics"][0]["name"] == "Task Completion"- assert caps[0]["status"] == "active"-- pulled = client.get("/api/v1/sync", {"project_id": str(PROJECT_ID)})- assert pulled.status_code == 200- assert pulled.data["capabilities"][0]["id"] == cap_id- assert pulled.data["repo_summary"] == "invoice bot"- assert pulled.data["version"] == "0.2.1"---def test_absent_slug_becomes_leftover_and_is_not_in_post_response(client):- client.post(- "/api/v1/sync", _snapshot([_cap(), _cap(slug="other", name="Other")]), format="json"- )- posted = client.post("/api/v1/sync", _snapshot([_cap()]), format="json")- slugs = {c["slug"] for c in posted.data["capabilities"]}- assert slugs == {"support-agent"}- leftover = Capability.objects.get(project_id=PROJECT_ID, slug="other")- assert leftover.status == Capability.Status.LEFTOVER-- pulled = client.get("/api/v1/sync", {"project_id": str(PROJECT_ID)})- by_slug = {c["slug"]: c for c in pulled.data["capabilities"]}- assert by_slug["other"]["status"] == "leftover"- assert by_slug["other"]["archived"] is True- assert by_slug["support-agent"]["status"] == "active"- assert by_slug["support-agent"]["archived"] is False---def test_observed_capability_is_not_marked_leftover(client):- client.post("/api/v1/sync", _snapshot([_cap()]), format="json")- observed = Capability.objects.create(- project_id=PROJECT_ID,- slug="runtime-only",- name="Runtime Only",- observed=True,- status=Capability.Status.CURRENT,- )- client.post("/api/v1/sync", _snapshot([_cap()]), format="json")- observed.refresh_from_db()- assert observed.status == Capability.Status.CURRENT--@pytest.mark.django_dbdef test_archived_slug_stays_leftover(client):client.post("/api/v1/sync", _snapshot([_cap()]), format="json")@@ -185,6 +104,7 @@ def test_archived_slug_stays_leftover(client):assert kept.data["capabilities"][0]["archived"] is True[email protected]("tenancy")@pytest.mark.django_dbdef test_wrong_project_id_is_403(client):other = str(uuid.uuid4())@@ -198,6 +118,7 @@ def test_wrong_project_id_is_403(client):assert pulled.status_code == 403[email protected]("authentication")@pytest.mark.django_dbdef test_account_key_can_sync_a_membership_project(project):user = User.objects.create_user(@@ -213,54 +134,6 @@ def test_account_key_can_sync_a_membership_project(project):assert posted.status_code == 200, posted.data-def test_system_prompt_and_capability_card_roundtrip(client):- card = {- "task": "Answer product questions",- "anchors": [{"qualname": "agent.reply", "kind": "entry_point"}],- "trajectory_map": [- {- "id": "happy-path",- "name": "Happy path",- "claim": "code_path",- "anchors": ["agent.reply"],- "terminal": {"kind": "emits_record"},- }- ],- }- matrix = [- {- "name": "Answer quality",- "type": "custom_judge",- "rubric": "Score 1 if the answer is correct.",- "measures": "correctness",- }- ]- posted = client.post(- "/api/v1/sync",- _snapshot(- [- _cap(- system_prompt="You are helpful.",- capability_card=card,- eval_matrix=matrix,- )- ]- ),- format="json",- )- assert posted.status_code == 200, posted.data- assert posted.data["capabilities"][0]["system_prompt"] == "You are helpful."- assert posted.data["capabilities"][0]["capability_card"]["task"] == "Answer product questions"- assert posted.data["capabilities"][0]["eval_matrix"][0]["name"] == "Answer quality"-- cap = Capability.objects.get(slug="support-agent")- assert cap.improvement_metadata.get("system_prompt") == "You are helpful."- assert cap.improvement_metadata["capability_card"]["trajectory_map"][0]["id"] == "happy-path"- assert cap.active_eval_set.name == "Default"- assert cap.active_eval_set.rows.get(name="Answer quality").source == "correctness"--@pytest.mark.django_dbdef test_scan_modes_utilities_and_policy_reach_the_capability(client):card = {@@ -317,58 +190,6 @@ def test_resync_rebuilds_the_default_set_from_the_toml(client):assert Capability.objects.get(pk=cap.pk).active_eval_set_id == default.id-def test_toml_deterministic_entry_becomes_a_parameterised_row_in_the_default_set(client):- matrix = [- {- "name": "Reply carries ticket keys",- "type": "deterministic",- "check": "json_required_keys",- "params": {"REQUIRED_KEYS": ["ticket_id", "status"]},- "span_name": "SupportAgent.run",- }- ]- client.post("/api/v1/sync", _snapshot([_cap(eval_matrix=matrix)]), format="json")-- cap = Capability.objects.get(slug="support-agent")- row = cap.active_eval_set.rows.get(name="Reply carries ticket keys")- assert row.type == "deterministic"- assert row.span_name == "SupportAgent.run"- assert "REQUIRED_KEYS = ['ticket_id', 'status']" in row.source- assert "def evaluate(span)" in row.source- assert cap.improvement_metadata["eval_preload"]["counts"]["expectations"] == 0-- matrix[0]["params"] = {"REQUIRED_KEYS": ["ticket_id"]}- client.post("/api/v1/sync", _snapshot([_cap(eval_matrix=matrix)]), format="json")- assert (- "REQUIRED_KEYS = ['ticket_id']"- in cap.active_eval_set.rows.get(name="Reply carries ticket keys").source- )---def test_code_expectations_become_span_scoped_rows_and_leave_with_the_code(client):- declared = [- {"expectation": "Cites the order id", "span_name": "SupportAgent.run"},- {"expectation": "Lists the refund steps", "span_name": "summarize"},- ]- client.post("/api/v1/sync", _snapshot([_cap(expectations=declared)]), format="json")-- cap = Capability.objects.get(slug="support-agent")- rows = {row.name: row for row in cap.active_eval_set.rows.filter(capability=cap)}- assert {name: (row.type, row.source, row.span_name) for name, row in rows.items()} == {- "Cites the order id": ("llm", "Cites the order id", "SupportAgent.run"),- "Lists the refund steps": ("llm", "Lists the refund steps", "summarize"),- }- assert cap.improvement_metadata["eval_preload"]["counts"]["expectations"] == 2-- client.post("/api/v1/sync", _snapshot([_cap(expectations=declared[:1])]), format="json")- assert set(cap.eval_matrix.values_list("name", flat=True)) == {"Cites the order id"}-- client.post("/api/v1/sync", _snapshot([_cap()]), format="json")- assert set(cap.eval_matrix.values_list("name", flat=True)) == {"Cites the order id"}--@pytest.mark.django_db@pytest.mark.parametrize("entry",@@ -391,43 +212,6 @@ def test_toml_deterministic_entry_with_a_bad_check_is_refused(client, entry):assert not Capability.objects.filter(slug="support-agent").exists()-def test_sync_normalizes_string_constraints_to_dicts(client):- constraints = [- "Answer must be plain English",- {"rule": "At most 5 tool calls", "type": "budget", "params": {"max_calls": 5}},- ]- card = {- "task": "Answer questions",- "trajectory_map": [- {- "id": "main",- "name": "Main",- "claim": "code_path",- "anchors": [],- "terminal": {"kind": "emits_record"},- }- ],- "constraints": constraints,- }- posted = client.post(- "/api/v1/sync",- _snapshot([_cap(capability_card=card)]),- format="json",- )- assert posted.status_code == 200, posted.data- cap = Capability.objects.get(slug="support-agent")- stored = cap.improvement_metadata["capability_card"]["constraints"]- assert stored[0] == {- "rule": "Answer must be plain English",- "type": "output_format",- "params": {},- "provenance": [],- }- assert stored[1]["rule"] == "At most 5 tool calls"- assert stored[1]["type"] == "budget"--@pytest.mark.django_dbdef test_evaluation_definitions_distinguish_catalogue_code_config_and_custom(client, project):declared = [{"expectation": "Reports completed work accurately", "span_name": "Agent.run"}]@@ -476,45 +260,3 @@ def test_evaluation_definitions_distinguish_catalogue_code_config_and_custom(clirow.save(update_fields=["source"])response = client.get(f"/api/eval-matrix/{row.pk}/")assert response.data["definition_source"] == "unknown"---def test_sync_retains_tool_branch_conditions_and_local_outcomes(client):- branch = {- "condition": "The clicked element is a select input",- "basis": "code",- "action": "Read dropdown options",- "outcome": "Available choices are returned",- "next": "Return choices to the next decision",- "transitions": [{"target": "Agent.decide", "condition": "Action returns choices"}],- "provenance": ["tools.py#L20-L35"],- }- response = client.post(- "/api/v1/sync",- _snapshot(- [- _cap(- capability_card={- "task": "Operate the browser",- "tool_spec": [- {- "name": "click",- "purpose": "Activate an element",- "args": "index",- "branches": [branch],- }- ],- }- )- ]- ),- format="json",- )- assert response.status_code == 200, response.content- capability = Capability.objects.get(project_id=PROJECT_ID, slug="support-agent")- detail = client.get(f"/api/capabilities/{capability.id}/")- assert detail.status_code == 200, detail.content- assert detail.json()["flow"]["tool_spec"][0]["branches"] == [branch]- assert capability.improvement_metadata["capability_card"]["tool_spec"][0]["branches"] == [- branch- ]diff --git a/tests/test_systemone_criteria.py b/tests/test_systemone_criteria.pyindex c1fa8f7a..c9349b0c 100644--- a/tests/test_systemone_criteria.py+++ b/tests/test_systemone_criteria.py@@ -1,5 +1,9 @@+import pytest+from overbae.services.systemone import parse+pytestmark = pytest.mark.covers("llm-gateway")+def test_choice_descriptions_reach_the_fine_tune_question():_model, _state, _names, decisions = parse(diff --git a/tests/test_task_lock.py b/tests/test_task_lock.pydeleted file mode 100644index 53b6f5ba..00000000--- a/tests/test_task_lock.py+++ /dev/null@@ -1,78 +0,0 @@-"""A worker restart leaves the Redis lock unreleased, so the per-lock safety timeout is-the only thing that revives the periodic task."""--import multiprocessing-import os-import time-import uuid--import pytest--from overbae.tasks.utils.task_lock import acquire_task_lock---def _redis_or_skip():- from overbae.tasks.utils.task_lock import _get_redis_client-- try:- # Test settings use CELERY_BROKER_URL=memory:// which redis-py rejects.- client = _get_redis_client()- client.ping()- except Exception: # noqa: BLE001- pytest.skip("Redis broker not reachable in this environment")- return client---def test_with_task_lock_passes_timeout_through():- from overbae.tasks.utils.task_lock import with_task_lock-- client = _redis_or_skip()- key = "celery:lock:_test_decorator_lock"- client.delete(key)-- @with_task_lock(lock_name="_test_decorator_lock", timeout=7)- def observe_ttl():- return client.ttl(key)-- ttl = observe_ttl()- assert 0 < ttl <= 7- assert client.ttl(key) == -2--- not os.environ.get("WORKSHOP_REDIS_URL"),- reason="Requires local Redis for process-loss lease verification",-)-def test_live_lease_renews_and_dead_collector_expires(settings):- settings.CELERY_BROKER_URL = os.environ["WORKSHOP_REDIS_URL"]- name = "workshop-lease-test-" + uuid.uuid4().hex- context = multiprocessing.get_context("fork")- ready = context.Event()-- def hold():- with acquire_task_lock(name, timeout=2, renew=True) as acquired:- assert acquired- ready.set()- time.sleep(30)-- process = context.Process(target=hold)- process.start()- try:- assert ready.wait(5)- time.sleep(3)- with acquire_task_lock(name, timeout=2) as acquired:- assert not acquired- process.terminate()- process.join(5)- deadline = time.monotonic() + 4- while time.monotonic() < deadline:- with acquire_task_lock(name, timeout=2) as acquired:- if acquired:- break- time.sleep(0.1)- else:- pytest.fail("The killed collector kept its lease beyond its recovery deadline")- finally:- if process.is_alive():- process.terminate()- process.join(5)diff --git a/tests/test_task_type_classifier.py b/tests/test_task_type_classifier.pyindex 6ca9c07d..fcf4b2e1 100644--- a/tests/test_task_type_classifier.py+++ b/tests/test_task_type_classifier.py@@ -7,6 +7,8 @@ import pytestfrom overbae.services.benchmarks.classify import classify_task_typefrom overbae.services.benchmarks.taxonomy import TaskType+pytestmark = pytest.mark.covers("recommendations")+def _profile(**overrides: Any) -> dict[str, Any]:profile = {diff --git a/tests/test_trace_errors.py b/tests/test_trace_errors.pyindex 0e34f4ca..320721c2 100644--- a/tests/test_trace_errors.py+++ b/tests/test_trace_errors.py@@ -7,7 +7,7 @@ from factories import api_key_client, make_member, make_project, make_span, makefrom google.protobuf.json_format import ParseDictfrom opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("otlp-ingest")]@pytest.mark.parametrize("wire_format", ["json", "protobuf"])diff --git a/tests/test_trace_streaming.py b/tests/test_trace_streaming.pyindex b9c67e84..fc59929d 100644--- a/tests/test_trace_streaming.py+++ b/tests/test_trace_streaming.py@@ -15,7 +15,7 @@ from overbae.models import (User,)-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("live-console")]TRACES_URL = "/api/traces/"diff --git a/tests/test_trace_usage_aggregation.py b/tests/test_trace_usage_aggregation.pyindex 2f2c4c1b..939fa21c 100644--- a/tests/test_trace_usage_aggregation.py+++ b/tests/test_trace_usage_aggregation.py@@ -14,7 +14,7 @@ from rest_framework_simplejwt.tokens import RefreshTokenfrom overbae.api.serializers import SpanSerializer, trace_usage_totalsfrom overbae.models import Project, ProjectMembership, Span, User-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("metrics-math")]TRACES_URL = "/api/traces/"diff --git a/tests/test_training_artifact_streaming.py b/tests/test_training_artifact_streaming.pyindex fc1c1858..efb2b0ad 100644--- a/tests/test_training_artifact_streaming.py+++ b/tests/test_training_artifact_streaming.py@@ -6,6 +6,8 @@ import pytestfrom modal_shared.training_data import materialize_files, row_key, write_selectionfrom overbae.services.sft_assets.preprocess import preprocess_rows+pytestmark = pytest.mark.covers("lineage")+def test_disk_materialization_preserves_order_duplicates_and_refuses_changed_targets(tmp_path):rows = [{"decision": {"target_probabilities": [p, 1 - p]}} for p in [0.2, 0.8]]diff --git a/tests/test_training_eta.py b/tests/test_training_eta.pyindex 3219d37f..5019c767 100644--- a/tests/test_training_eta.py+++ b/tests/test_training_eta.py@@ -1,5 +1,9 @@+import pytest+from overbae.services.finetuning_runner import PollSnapshot, progress_from_snapshot+pytestmark = pytest.mark.covers("measured-facts")+def snapshot(events, step):return PollSnapshot(diff --git a/tests/test_training_experience.py b/tests/test_training_experience.pyindex 7f9d148d..19c87a87 100644--- a/tests/test_training_experience.py+++ b/tests/test_training_experience.py@@ -13,7 +13,7 @@ from modal_shared.training_monitoring import fingerprintfrom overbae.models import Dataset, FinetuningJob, Projectfrom overbae.services import training_experience, training_monitoring-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("work-once")]@pytest.fixturediff --git a/tests/test_training_experiment_workflow.py b/tests/test_training_experiment_workflow.pyindex 60aba10e..db8c9b63 100644--- a/tests/test_training_experiment_workflow.py+++ b/tests/test_training_experiment_workflow.py@@ -11,7 +11,7 @@ from overbae.models import Dataset, FinetuningJob, Project, ProjectMembership, Ufrom overbae.services import native_evaluation, training_experimentsfrom overbae.services.datasets import land, rows-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("work-once")]def data(project, name):diff --git a/tests/test_training_failure.py b/tests/test_training_failure.pyindex 072bbd08..34840a83 100644--- a/tests/test_training_failure.py+++ b/tests/test_training_failure.py@@ -1,5 +1,9 @@+import pytest+from modal_shared.training_failure import failure_receipt+pytestmark = pytest.mark.covers("privacy")+def test_decision_reload_failure_exposes_the_failed_check_without_worker_text(tmp_path):log = tmp_path / "worker.log"diff --git a/tests/test_training_field_checks.py b/tests/test_training_field_checks.pyindex bc1760d7..b109fb06 100644--- a/tests/test_training_field_checks.py+++ b/tests/test_training_field_checks.py@@ -1,20 +1,21 @@-import asyncioimport jsonimport uuidfrom unittest.mock import patchimport pytestfrom django.urls import reverse+from mcp_fixtures import call_toolfrom rest_framework.test import APIClientfrom modal_shared.training_monitoring import paired_generation_metrics, resolve_policyfrom modal_shared.training_monitoring_runtime import Monitorfrom overbae.models import APIToken, Dataset, FinetuningJob, Project, ProjectMembership, Userfrom overbae.services import training_monitoring-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContextfrom overbae.services.mcp.contracts.training_monitoring import TrainingMonitoringPolicy+pytestmark = pytest.mark.covers("metrics-math")+def policy(fields):declared = TrainingMonitoringPolicy.model_validate(@@ -87,7 +88,7 @@ def test_missing_or_invalid_reference_is_unscorable_not_a_model_failure(referencassert measured["fields"]["/value"]["passed"] is None[email protected]_db(transaction=True)def test_declared_fields_flow_from_policy_through_checks_to_passive_agent_and_console(tmp_path):contract = policy(["/risk", "/case/id"])rows = [{"key": str(i), "input_ids": [1, 2], "labels": [-100, 2]} for i in range(5)]@@ -147,16 +148,12 @@ def test_declared_fields_flow_from_policy_through_checks_to_passive_agent_and_coclient = APIClient()client.force_authenticate(user)with patch("modal.Function.from_name", side_effect=AssertionError("read invoked provider")):- result = asyncio.run(- CATALOG.call("inspect_training_progress", {"job": str(job.id)}, context)- )+ result = call_tool("inspect_training_progress", {"job": str(job.id)}, context)response = client.get(reverse("finetuningjob-monitoring", kwargs={"id": job.id}))- evidence = asyncio.run(- CATALOG.call(- "inspect_training_progress",- {"job": str(job.id), "check": str(job.validation_runs.order_by("step").first().id)},- context,- )+ evidence = call_tool(+ "inspect_training_progress",+ {"job": str(job.id), "check": str(job.validation_runs.order_by("step").first().id)},+ context,)assert not result.isError, result.structuredContentassert response.status_code == 200diff --git a/tests/test_training_forecast.py b/tests/test_training_forecast.pyindex dd1c4671..7bbc983f 100644--- a/tests/test_training_forecast.py+++ b/tests/test_training_forecast.py@@ -11,6 +11,8 @@ from overbae.services import training_releasefrom overbae.services.recommendation import estimate_for_hyperparamsfrom overbae.services.training_forecast import forecast+pytestmark = pytest.mark.covers("measured-facts")+def test_native_forecast_uses_matching_measurements_and_selected_gpu():recipe = {"objective": "decision_cross_entropy", "context_length": 2048, "batch_size": 128}diff --git a/tests/test_training_monitoring.py b/tests/test_training_monitoring.pyindex 4bc89d97..a5359281 100644--- a/tests/test_training_monitoring.py+++ b/tests/test_training_monitoring.py@@ -14,6 +14,8 @@ from modal_shared.training_monitoring import (from modal_shared.training_monitoring_runtime import Monitorfrom overbae.services.training_policies import profile_options+pytestmark = pytest.mark.covers("plans")+@pytest.mark.parametrize("policy",diff --git a/tests/test_training_monitoring_journey.py b/tests/test_training_monitoring_journey.pyindex 8bef0085..acbe87a7 100644--- a/tests/test_training_monitoring_journey.py+++ b/tests/test_training_monitoring_journey.py@@ -1,20 +1,21 @@-import asyncioimport jsonimport uuidfrom unittest.mock import patchimport pytestfrom django.urls import reverse+from mcp_fixtures import call_toolfrom rest_framework.test import APIClientfrom modal_shared.training_monitoring import fingerprint, freeze_plan, resolve_policy, row_identityfrom overbae.models import APIToken, Dataset, FinetuningJob, Project, ProjectMembership, Userfrom overbae.services import training_monitoring-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext+pytestmark = pytest.mark.covers("measured-facts")[email protected]_db(transaction=True)+def test_many_decision_questions_remain_inspectable_through_paged_receipts():user = User.objects.create_user(email=f"families-{uuid.uuid4()}@example.com", password="test")project = Project.objects.create(name="Question families")@@ -69,9 +70,7 @@ def test_many_decision_questions_remain_inspectable_through_paged_receipts():client = APIClient()client.force_authenticate(user)with patch("modal.Function.from_name", side_effect=AssertionError("read invoked provider")):- result = asyncio.run(- CATALOG.call("inspect_training_progress", {"job": str(job.pk), "limit": 1}, context)- )+ result = call_tool("inspect_training_progress", {"job": str(job.pk), "limit": 1}, context)assert not result.isError, result.structuredContentoverview = result.structuredContent["progress"]assert len(json.dumps(overview).encode()) < 128 * 1024@@ -82,7 +81,7 @@ def test_many_decision_questions_remain_inspectable_through_paged_receipts():collected, offset = {}, 0while offset is not None:args = {"job": str(job.pk), "field": field, "offset": offset, "limit": 20}- page = asyncio.run(CATALOG.call("inspect_training_progress", args, context))+ page = call_tool("inspect_training_progress", args, context)assert not page.isError, page.structuredContentdetail = page.structuredContent["progress"]rest = client.get(@@ -93,169 +92,36 @@ def test_many_decision_questions_remain_inspectable_through_paged_receipts():collected.update({item["key"]: item["value"] for item in detail["items"]})offset = detail["next_offset"]assert collected == families- findings = asyncio.run(- CATALOG.call(- "inspect_training_progress",- {- "job": str(job.pk),- "field": f"/checks/{check.pk}/facts/assessment/findings",- "limit": 1,- },- context,- )+ findings = call_tool(+ "inspect_training_progress",+ {+ "job": str(job.pk),+ "field": f"/checks/{check.pk}/facts/assessment/findings",+ "limit": 1,+ },+ context,)assert not findings.isError and findings.structuredContent["progress"]["count"] == 1600- matrix = asyncio.run(- CATALOG.call(- "inspect_training_progress",- {- "job": str(job.pk),- "field": f"/checkpoints/{checkpoint.pk}/metrics/categorical_families/{next(iter(families))}/confusion_matrix",- "limit": 1,- },- context,- )+ matrix = call_tool(+ "inspect_training_progress",+ {+ "job": str(job.pk),+ "field": f"/checkpoints/{checkpoint.pk}/metrics/categorical_families/{next(iter(families))}/confusion_matrix",+ "limit": 1,+ },+ context,)assert not matrix.isError and matrix.structuredContent["progress"]["items"] == [[0, 1]]foreign = FinetuningJob.objects.create(project=project, dataset=job.dataset)- denied = asyncio.run(- CATALOG.call(- "inspect_training_progress", {"job": str(foreign.pk), "field": field}, context- )+ denied = call_tool(+ "inspect_training_progress", {"job": str(foreign.pk), "field": field}, context)assert denied.isErrorcheck.refresh_from_db()assert check.metrics == metrics[email protected]_db(transaction=True)-def test_agent_and_console_read_the_same_durable_check_then_cancel_without_losing_evidence():- user = User.objects.create_user(email=f"monitor-{uuid.uuid4()}@example.com", password="test")- project = Project.objects.create(name="Monitoring journey")- ProjectMembership.objects.create(user=user, project=project)- dataset = Dataset.objects.create(project=project)- job = FinetuningJob.objects.create(- project=project, dataset=dataset, status="running", base_model="Qwen/Qwen3-0.6B"- )- context = MCPContext(- user=user,- project=project,- token=APIToken(scope={"scope": "project", "permission": ["read", "write"]}),- )- training_monitoring.ingest(- job,- {- "checks": [- {- "key": "1:development:14",- "attempt": 1,- "stream": "development",- "step": 14,- "state": "completed",- "policy_fingerprint": "a" * 64,- "sample_fingerprint": "b" * 64,- "started_at": 100,- "observed_at": 110,- "metrics": {- "eval_loss": 0.2,- "generation": {- "pass_rate": 0.75,- "scored": 4,- "expected": 4,- "coverage": 1,- },- },- }- ]- },- )- client = APIClient()- client.force_authenticate(user)- with patch("modal.Function.from_name", side_effect=AssertionError("read invoked provider")):- result = asyncio.run(- CATALOG.call("inspect_training_progress", {"job": str(job.id)}, context)- )- assert not result.isError, result.structuredContent- response = client.get(reverse("finetuningjob-monitoring", kwargs={"id": job.id}))- assert response.status_code == 200, response.data- assert result.structuredContent["progress"]["checks"] == response.json()["checks"]- assert result.structuredContent["progress"]["checks"][0]["metrics"]["eval_loss"] == 0.2- compact = asyncio.run(- CATALOG.call("get_job", {"kind": "finetune_job", "id": str(job.id)}, context)- )- assert not compact.isError, compact.structuredContent- quality = compact.structuredContent["details"]["monitoring"]["latest_check"]["generation"]- assert quality["pass_rate"] == 0.75- assert quality["accuracy"] is None- cancelled = asyncio.run(CATALOG.call("cancel_finetune", {"job": str(job.id)}, context))- assert not cancelled.isError, cancelled.structuredContent- job.refresh_from_db()- assert job.status == "cancelled"- assert job.validation_runs.get().state == "completed"- other = Project.objects.create(name="Not authorised", slug="not-authorised")- foreign = FinetuningJob.objects.create(- project=other, dataset=Dataset.objects.create(project=other)- )- denied = asyncio.run(- CATALOG.call("inspect_training_progress", {"job": str(foreign.id)}, context)- )- assert denied.isError--[email protected]_db(transaction=True)-def test_agent_evidence_is_lossless_or_returns_an_explicit_size_error():- user = User.objects.create_user(email=f"evidence-{uuid.uuid4()}@example.com", password="test")- project = Project.objects.create(name="Evidence")- ProjectMembership.objects.create(user=user, project=project)- job = FinetuningJob.objects.create(- project=project, dataset=Dataset.objects.create(project=project)- )- context = MCPContext(- user=user,- project=project,- token=APIToken(scope={"scope": "project", "permission": ["read"]}),- )- rows = [- {- "row": 0,- "input": "x" * 15000,- "output": "y" * 15000,- "reference": "z",- "status": "completed",- }- ]- training_monitoring.ingest(- job,- {- "checks": [- {- "key": "1:development:0",- "attempt": 1,- "stream": "development",- "step": 0,- "state": "completed",- "policy_fingerprint": "a" * 64,- "sample_fingerprint": "b" * 64,- "artifact": {"sha256": fingerprint(rows), "examples": rows},- }- ]- },- )- result = asyncio.run(- CATALOG.call(- "inspect_training_progress",- {- "job": str(job.pk),- "check": str(job.validation_runs.get().pk),- },- context,- )- )- assert not result.isError, result.structuredContent- assert result.structuredContent["progress"]["items"] == rows--[email protected]_db(transaction=True)def test_frozen_monitoring_rows_are_paged_without_provider_access():user = User.objects.create_user(email=f"probe-{uuid.uuid4()}@example.com", password="test")project = Project.objects.create(name="Frozen monitoring")@@ -279,12 +145,10 @@ def test_frozen_monitoring_rows_are_paged_without_provider_access():with patch("modal.Function.from_name", side_effect=AssertionError("inspection invoked provider")):- result = asyncio.run(- CATALOG.call(- "inspect_training_progress",- {"job": str(job.id), "probe": "development", "limit": 2},- context,- )+ result = call_tool(+ "inspect_training_progress",+ {"job": str(job.id), "probe": "development", "limit": 2},+ context,)assert not result.isError, result.structuredContentassert (diff --git a/tests/test_training_monitoring_native.py b/tests/test_training_monitoring_native.pyindex 50f9247e..b723dd0a 100644--- a/tests/test_training_monitoring_native.py+++ b/tests/test_training_monitoring_native.py@@ -1,9 +1,13 @@import jsonfrom contextlib import nullcontext+import pytest+from modal_shared.training_monitoring import resolve_policyfrom overbae.services.sft_assets.native_monitor import NativeTrainingMonitor+pytestmark = pytest.mark.covers("metrics-math")+class Rows:def __init__(self):diff --git a/tests/test_training_monitoring_receipts.py b/tests/test_training_monitoring_receipts.pyindex 718742cb..17007554 100644--- a/tests/test_training_monitoring_receipts.py+++ b/tests/test_training_monitoring_receipts.py@@ -15,6 +15,8 @@ from overbae.models import (from overbae.services import training_monitoringfrom overbae.services.training_cancellation import cancel+pytestmark = pytest.mark.covers("work-once")+@pytest.fixturedef monitoring_job():diff --git a/tests/test_training_plan_workflow.py b/tests/test_training_plan_workflow.pyindex bda7d5ea..34f3b5c5 100644--- a/tests/test_training_plan_workflow.py+++ b/tests/test_training_plan_workflow.py@@ -20,7 +20,7 @@ from overbae.services.datasets import landfrom overbae.services.datasets.partition_plans import buildfrom overbae.services.mcp.server import create_mcp_application-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("plans")]def invoke(client, key, name, arguments, *, error=False):diff --git a/tests/test_training_preparation.py b/tests/test_training_preparation.pyindex a0b0a388..fc7fa1c9 100644--- a/tests/test_training_preparation.py+++ b/tests/test_training_preparation.py@@ -17,7 +17,7 @@ from overbae.services.datasets.lifecycle import DatasetErrorfrom overbae.services.sft_assets.preprocess import preprocess_rowsfrom overbae.tasks.finetuning import run_finetuning-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("model-runtime")]@pytest.fixture(autouse=True)diff --git a/tests/test_training_quality.py b/tests/test_training_quality.pyindex d6ad29a7..748d1352 100644--- a/tests/test_training_quality.py+++ b/tests/test_training_quality.py@@ -1,10 +1,10 @@-import asyncioimport copyimport uuidfrom unittest.mock import patchimport pytestfrom django.urls import reverse+from mcp_fixtures import call_toolfrom rest_framework.test import APIClientfrom modal_shared.training_monitoring import classification_metrics, fingerprint, resolve_policy@@ -18,9 +18,10 @@ from overbae.models import (User,)from overbae.services import training_monitoring-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext+pytestmark = pytest.mark.covers("measured-facts")+@pytest.fixturedef quality_job():@@ -70,7 +71,7 @@ def record(job, *, step=2, examples=None):}[email protected]_db(transaction=True)def test_collector_retains_quality_assessment_and_later_loss_does_not_hide_it(quality_job):job, user = quality_jobsource = record(job)@@ -114,12 +115,8 @@ def test_collector_retains_quality_assessment_and_later_loss_does_not_hide_it(quclient = APIClient()client.force_authenticate(user)with patch("modal.Function.from_name", side_effect=AssertionError("read invoked provider")):- result = asyncio.run(- CATALOG.call("get_job", {"kind": "finetune_job", "id": str(job.id)}, context)- )- snapshot = asyncio.run(- CATALOG.call("inspect_training_progress", {"job": str(job.id)}, context)- )+ result = call_tool("get_job", {"kind": "finetune_job", "id": str(job.id)}, context)+ snapshot = call_tool("inspect_training_progress", {"job": str(job.id)}, context)rest = client.get(reverse("finetuningjob-monitoring", kwargs={"id": job.id}))assert not result.isError, result.structuredContentsummary = result.structuredContent["details"]["monitoring"]diff --git a/tests/test_training_release.py b/tests/test_training_release.pyindex 832c3a9f..233dc414 100644--- a/tests/test_training_release.py+++ b/tests/test_training_release.py@@ -6,6 +6,8 @@ import pytestfrom overbae.services import training_release+pytestmark = pytest.mark.covers("model-runtime")+def test_release_requires_explicit_environment_and_pins_observers_to_saved_release(tmp_path, monkeypatchdiff --git a/tests/test_training_startup_journey.py b/tests/test_training_startup_journey.pyindex 85bd41da..471e8710 100644--- a/tests/test_training_startup_journey.py+++ b/tests/test_training_startup_journey.py@@ -13,7 +13,7 @@ from overbae.services.finetuning_runner import PollSnapshotfrom overbae.services.mcp.server import create_mcp_applicationfrom overbae.tasks.finetuning import _persist_snapshot_progress-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("measured-facts")]def test_startup_stage_receipts_reach_console_and_mcp_without_provider_calls(tmp_path):diff --git a/tests/test_training_submission.py b/tests/test_training_submission.pyindex d75f8550..67b3c8d4 100644--- a/tests/test_training_submission.py+++ b/tests/test_training_submission.py@@ -5,7 +5,7 @@ import pytestfrom overbae.models import Dataset, FinetuningJob, Projectfrom overbae.services import training_submission-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("work-once")]def test_submission_intent_survives_worker_loss_and_never_resubmits():diff --git a/tests/test_training_telemetry.py b/tests/test_training_telemetry.pyindex 83296f26..41db2cec 100644--- a/tests/test_training_telemetry.py+++ b/tests/test_training_telemetry.py@@ -9,6 +9,8 @@ from overbae.services import training_submissionfrom overbae.services.finetuning_runner import ModalRunner, PollSnapshot, progress_from_snapshotfrom overbae.tasks.finetuning import _persist_snapshot_progress+pytestmark = pytest.mark.covers("measured-facts")+def test_stages_and_recovery_cross_provider_and_progress_boundaries(tmp_path):record_stage(tmp_path, "initial_validation", completed=12, total=30, unit="decisions")diff --git a/tests/test_training_transfer.py b/tests/test_training_transfer.pyindex b3f93dd1..3e5e7234 100644--- a/tests/test_training_transfer.py+++ b/tests/test_training_transfer.py@@ -15,6 +15,8 @@ from overbae.models import FinetuningJob, Projectfrom overbae.services import finetuning_runner, training_submissionfrom overbae.services.training_preparation import request_preparation+pytestmark = pytest.mark.covers("lineage")+@pytest.mark.django_db@pytest.mark.parametrize("objective", ["assistant_cross_entropy", "decision_cross_entropy"])diff --git a/tests/test_training_transfer_journey.py b/tests/test_training_transfer_journey.pyindex be02e1f4..ad8ad913 100644--- a/tests/test_training_transfer_journey.py+++ b/tests/test_training_transfer_journey.py@@ -17,7 +17,7 @@ from overbae.services.mcp.server import create_mcp_applicationfrom overbae.services.training_transfer import stage_datafrom overbae.tasks.finetuning_reconciler import _reconcile-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("lineage")]def test_active_transfer_reconciles_real_rows_into_console_and_mcp_without_dispatch(tmp_path):diff --git a/tests/test_training_type.py b/tests/test_training_type.pyindex b3961878..63b7115a 100644--- a/tests/test_training_type.py+++ b/tests/test_training_type.py@@ -3,6 +3,8 @@ pin the per-training-kind restriction against a dataset's longest row."""from __future__ import annotations+import pytest+from overbae.modal.training_type import (dataset_training_type,normalize_training_type,@@ -11,6 +13,8 @@ from overbae.modal.training_type import (usable_training_kinds,)+pytestmark = pytest.mark.covers("plans")+# Full's smaller context than LoRA's is the exact shape the onboarding skill# describes (LoRA's lighter optimizer state leaves more VRAM for activations)._ENTRY = {diff --git a/tests/test_vllm_text_only_multimodal.py b/tests/test_vllm_text_only_multimodal.pyindex 403cd42f..335621ac 100644--- a/tests/test_vllm_text_only_multimodal.py+++ b/tests/test_vllm_text_only_multimodal.py@@ -12,6 +12,8 @@ from overbae.modal.modal_vllm_worker import ( # noqa: E402_normalize_model_blob,)+pytestmark = pytest.mark.covers("model-runtime")+def test_normalize_unifies_separators():assert "qwen3-5" in _normalize_model_blob("Qwen/Qwen3.5-0.8B")diff --git a/tests/test_weight_ops.py b/tests/test_weight_ops.pyindex f23f19ec..c534b715 100644--- a/tests/test_weight_ops.py+++ b/tests/test_weight_ops.py@@ -22,6 +22,8 @@ from overbae.modal.weight_ops import ( # noqa: E402prepare_fp8_weights,)+pytestmark = pytest.mark.covers("model-runtime")+def _write_tiny_lora_pair(tmp: Path) -> tuple[Path, Path]:base = tmp / "base"diff --git a/tests/test_worker_drain.py b/tests/test_worker_drain.pyindex 85c70f7b..8e430193 100644--- a/tests/test_worker_drain.py+++ b/tests/test_worker_drain.py@@ -4,6 +4,8 @@ import pytestfrom overbae import worker_drain+pytestmark = pytest.mark.covers("topology")+def test_mixed_consumers_stop_fetching_and_drain_reserved_work(monkeypatch):initial = Mock()diff --git a/tests/test_workflow_measurements.py b/tests/test_workflow_measurements.pyindex 633324d0..c6e02a6d 100644--- a/tests/test_workflow_measurements.py+++ b/tests/test_workflow_measurements.py@@ -8,6 +8,8 @@ from overbae.services import training_releasefrom overbae.services.compute_costs import estimate_usagefrom overbae.services.training_forecast import forecast+pytestmark = pytest.mark.covers("measured-facts")+def measured_job():stats = {diff --git a/tests/test_workshop_admission.py b/tests/test_workshop_admission.pyindex 67ba0fdf..67f86fc2 100644--- a/tests/test_workshop_admission.py+++ b/tests/test_workshop_admission.py@@ -13,6 +13,8 @@ from overbae.models import Cell, Dataset, DatasetPipelineRunfrom overbae.services.datasets import pipeline_runnerfrom overbae.tasks.datasets import execute_pipeline+pytestmark = pytest.mark.covers("capacity")+def test_scratch_reclaims_dead_workers_but_preserves_active_runs(tmp_path, monkeypatch):monkeypatch.setattr(tempfile, "tempdir", str(tmp_path))diff --git a/tests/test_workshop_analytics.py b/tests/test_workshop_analytics.pyindex 6d6f20b9..92a32cee 100644--- a/tests/test_workshop_analytics.py+++ b/tests/test_workshop_analytics.py@@ -4,6 +4,8 @@ from overbae.models import Cellfrom overbae.services.datasets.analytics import VERSION, describefrom overbae.services.datasets.profile import profile_records+pytestmark = pytest.mark.covers("data-logic")+def decision(target, *, options=None, **extra):return {diff --git a/tests/test_workshop_documents.py b/tests/test_workshop_documents.pyindex 084ce68c..155ee997 100644--- a/tests/test_workshop_documents.py+++ b/tests/test_workshop_documents.py@@ -19,7 +19,7 @@ from sandbox.documents import ocrfrom sandbox.documents.extract import DocumentError as ParserErrorfrom sandbox.documents.extract import extract as parse_document-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("data-logic")]@pytest.fixturediff --git a/tests/test_workshop_health.py b/tests/test_workshop_health.pyindex d7331cfc..3b4a1608 100644--- a/tests/test_workshop_health.py+++ b/tests/test_workshop_health.py@@ -7,6 +7,8 @@ from overbae.models import DatasetPipelineRunnerfrom overbae.services.datasets import pipeline_runner, workbenchfrom sandbox.packages import runtime_id+pytestmark = pytest.mark.covers("sandbox")+@pytest.mark.django_dbdef test_runtime_health_checks_identity_and_expires(settings):diff --git a/tests/test_workshop_history_migration.py b/tests/test_workshop_history_migration.pydeleted file mode 100644index 84cb2948..00000000--- a/tests/test_workshop_history_migration.py+++ /dev/null@@ -1,98 +0,0 @@-from django.db import connections-from django.db.backends.postgresql.base import DatabaseWrapper-from django.db.migrations.executor import MigrationExecutor-from django.test import override_settings-from test_workshop_training_migration import scratch_database as scratch_database---def test_cutover_preserves_published_cells_and_provider_receipts(- scratch_database, django_db_blocker-):- original = connections["default"]- database = DatabaseWrapper(- {**original.settings_dict, "NAME": scratch_database},- alias="default",- )- with django_db_blocker.unblock(), override_settings(MIGRATION_MODULES={}):- connections["default"] = database- try:- executor = MigrationExecutor(database)- before = [("overbae", "0025_dataset_import_artifact")]- executor.migrate(before)- old = executor.loader.project_state(before).apps- project = old.get_model("overbae", "Project").objects.create(- name="Migration", slug="migration"- )- dataset = old.get_model("overbae", "Dataset").objects.create(- project=project,- name="History",- state="diagnosing",- chat=[{"role": "agent", "text": "Saved history"}],- agent_id="provider-agent",- operation={- "provider": {"run_id": "unresolved-provider-run", "state": "submitting"}- },- )- cell = old.get_model("overbae", "Cell").objects.create(- dataset=dataset,- position=0,- title="Source",- state="ok",- fingerprint="a" * 64,- )- dataset.active = cell- dataset.source_spec = {- "_migration_workshop_archive": {- "cells": [{"id": str(cell.pk), "state": "ok", "review": {"retained": True}}]- }- }- dataset.save(update_fields=["active", "source_spec"])- run = old.get_model("overbae", "WorkshopRun").objects.create(- dataset=dataset, source=cell- )- item = old.get_model("overbae", "WorkshopWorkItem").objects.create(- run=run,- key="batch",- provider={"receipt": "provider-receipt"},- artifact="retained.parquet",- )- executor = MigrationExecutor(database)- target = [("overbae", "0026_dataset_history")]- executor.migrate(target)- current = executor.loader.project_state(target).apps- assert (- current.get_model("overbae", "Cell").objects.get(pk=cell.pk).fingerprint == "a" * 64- )- assert (- current.get_model("overbae", "Dataset").objects.get(pk=dataset.pk).state == "idle"- )- retained = current.get_model("overbae", "Dataset").objects.get(pk=dataset.pk)- assert retained.active_id == cell.pk- assert "_migration_workshop_archive" not in retained.source_spec- assert current.get_model("overbae", "Cell").objects.get(pk=cell.pk).review == {- "retained": True- }- history = current.get_model("overbae", "DatasetHistory")- assert (- history.objects.get(dataset_id=dataset.pk, kind="conversation").payload["chat"][0][- "text"- ]- == "Saved history"- )- assert (- history.objects.get(dataset_id=dataset.pk, kind="operation").payload["provider"][- "run_id"- ]- == "unresolved-provider-run"- )- assert (- history.objects.get(- dataset_id=dataset.pk, kind="work_item", reference=str(item.pk)- ).payload["provider"]["receipt"]- == "provider-receipt"- )- assert "overbae_workshoprun" not in database.introspection.table_names()-- finally:- database.close()- connections["default"] = originaldiff --git a/tests/test_workshop_mcp_acceptance.py b/tests/test_workshop_mcp_acceptance.pyindex 3a93b3c4..8bc16f08 100644--- a/tests/test_workshop_mcp_acceptance.py+++ b/tests/test_workshop_mcp_acceptance.py@@ -1,4 +1,3 @@-import asyncioimport jsonimport uuidfrom datetime import timedelta@@ -6,12 +5,13 @@ from pathlib import Pathfrom unittest.mock import patchimport pytest+from asgiref.sync import async_to_syncfrom django.utils import timezone+from mcp_fixtures import call_toolfrom test_workshop_redesign import call, workspacefrom overbae.models import Dataset, DatasetPipelineRunfrom overbae.services.datasets import dispatch, paths, store, workbench-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import bind_contextfrom overbae.services.mcp.resources import read_resourcefrom overbae.tasks.datasets import land@@ -22,7 +22,7 @@ from tests.workshop_script_fixtures import (select_script,)-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("mcp-surface")]@pytest.mark.parametrize("mode", ["preview", "publish"])@@ -76,7 +76,7 @@ def test_pipeline_poll_and_replay_keep_examples_in_drilldown_not_status(mode):contents = list(await read_resource(job["resource"]["uri"]))return json.loads(contents[0].content)- retained = asyncio.run(evidence())+ retained = async_to_sync(evidence)()assert retained["result"] == recorded.resultrecorded.refresh_from_db()assert json.dumps(recorded.result, sort_keys=True) == original_result@@ -92,12 +92,10 @@ def test_query_deadline_preserves_source_and_next_read(settings):dataset = Dataset.objects.get(pk=created.data["id"])original = dataset.active_cell.fingerprintsettings.DATASET_QUERY_TIMEOUT_SECONDS = 0.001- result = asyncio.run(- CATALOG.call(- "query_dataset",- {"dataset": str(dataset.pk), "sql": "SELECT sum(hash(i)) FROM range(10000000) t(i)"},- context,- )+ result = call_tool(+ "query_dataset",+ {"dataset": str(dataset.pk), "sql": "SELECT sum(hash(i)) FROM range(10000000) t(i)"},+ context,)assert result.isError, result.structuredContentassert result.structuredContent["error"]["code"] == "query_timeout"@@ -128,9 +126,7 @@ def test_unsafe_query_and_llm_call_source_return_public_mcp_contracts():"SELECT * FROM read_csv_auto('/etc/passwd')","DELETE FROM t",):- result = asyncio.run(- CATALOG.call("query_dataset", {"dataset": str(dataset.pk), "sql": sql}, context)- )+ result = call_tool("query_dataset", {"dataset": str(dataset.pk), "sql": sql}, context)assert result.isErrorassert result.structuredContent["error"]["code"] == "query_invalid"Dataset.objects.filter(pk=dataset.pk).update(source_kind=Dataset.SourceKind.LLM_CALLS)@@ -619,10 +615,8 @@ def test_wide_query_fails_with_actionable_size_error_without_clipping_values():format="json",)dataset = Dataset.objects.get(pk=created.data["id"])- result = asyncio.run(- CATALOG.call(- "query_dataset", {"dataset": str(dataset.pk), "sql": "SELECT text FROM t"}, context- )+ result = call_tool(+ "query_dataset", {"dataset": str(dataset.pk), "sql": "SELECT text FROM t"}, context)assert result.isErrorassert result.structuredContent["error"]["code"] == "query_result_too_large"@@ -644,10 +638,8 @@ def test_wide_schema_query_does_not_omit_column_metadata():"/api/datasets/", {"project": str(project.pk), "source": {"rows": [row]}}, format="json")dataset = Dataset.objects.get(pk=created.data["id"])- result = asyncio.run(- CATALOG.call(- "query_dataset", {"dataset": str(dataset.pk), "sql": "SELECT * FROM t"}, context- )+ result = call_tool(+ "query_dataset", {"dataset": str(dataset.pk), "sql": "SELECT * FROM t"}, context)assert result.isErrorassert result.structuredContent["error"]["code"] == "query_result_too_large"diff --git a/tests/test_workshop_package_transfer_journey.py b/tests/test_workshop_package_transfer_journey.pyindex 84f9ce9b..11252d12 100644--- a/tests/test_workshop_package_transfer_journey.py+++ b/tests/test_workshop_package_transfer_journey.py@@ -1,4 +1,3 @@-import asyncioimport hashlibimport importlib.utilimport io@@ -8,6 +7,7 @@ from urllib.parse import urlsplitimport pytestimport requests+from asgiref.sync import async_to_syncfrom django.core.files.uploadedfile import SimpleUploadedFilefrom rest_framework.test import APIClientfrom typer.testing import CliRunner@@ -18,7 +18,7 @@ from overbae.services.datasets import pipeline_packagesfrom overbae.services.mcp.context import MCPContext, bind_contextfrom overbae.services.mcp.resources import read_resource-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db, pytest.mark.covers("sandbox")]def test_cli_package_roundtrip_through_rest_services(tmp_path, monkeypatch, settings):@@ -205,10 +205,8 @@ def test_cli_package_roundtrip_through_rest_services(tmp_path, monkeypatch, settquery = {"file": "unicode.py", "offset": offset, "limit": 16000}rest = client.get(f"/api/dataset-pipeline-packages/{receipt['id']}/source/", query)with bind_context(context):- resource = asyncio.run(- read_resource(- f"overmind://dataset-pipeline-packages/{receipt['id']}?file=unicode.py&offset={offset}&limit=16000"- )+ resource = async_to_sync(read_resource)(+ f"overmind://dataset-pipeline-packages/{receipt['id']}?file=unicode.py&offset={offset}&limit=16000")assert json.loads(resource[0].content)["file"] == rest.datarecovered += rest.data["content"]diff --git a/tests/test_workshop_preparation_journey.py b/tests/test_workshop_preparation_journey.pyindex 5d494188..579d44ff 100644--- a/tests/test_workshop_preparation_journey.py+++ b/tests/test_workshop_preparation_journey.py@@ -1,6 +1,5 @@-import asyncio-import pytest+from mcp_fixtures import call_toolfrom overbae.models import Activity, DatasetPipelineRunfrom overbae.services import operational_progress@@ -24,7 +23,7 @@ from tests.workshop_script_fixtures import (script_step,)-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("lineage")]def decision_step(**settings):@@ -457,7 +456,7 @@ def test_workshop_surfaces_omit_retired_checks_but_keep_execution_receipts():dataset = source(client, project, "Retained preparation", [{"value": 1}])for name in ("inspect_dataset_preparation", "record_dataset_findings"):assert name not in {tool.name for tool in CATALOG.tools(frozenset({"read", "write"}))}- result = asyncio.run(CATALOG.call(name, {"dataset": str(dataset.pk)}, context))+ result = call_tool(name, {"dataset": str(dataset.pk)}, context)assert result.isErrorassert result.structuredContent["error"]["code"] == "invalid_tool"assert client.get(f"/api/datasets/{dataset.pk}/preparation-checks/").status_code == 404diff --git a/tests/test_workshop_readiness.py b/tests/test_workshop_readiness.pyindex 701bb06f..472b5ba7 100644--- a/tests/test_workshop_readiness.py+++ b/tests/test_workshop_readiness.py@@ -21,7 +21,7 @@ from overbae.services.mcp.contracts.datasets import serialize_dataset_detailfrom overbae.services.mcp.errors import mcp_cell_contractfrom overbae.services.training_preparation import request_preparation-pytestmark = pytest.mark.django_db+pytestmark = [pytest.mark.django_db, pytest.mark.covers("data-logic")]@pytest.fixturediff --git a/tests/test_workshop_redesign.py b/tests/test_workshop_redesign.pyindex 5597b0c9..303cf3dc 100644--- a/tests/test_workshop_redesign.py+++ b/tests/test_workshop_redesign.py@@ -1,24 +1,20 @@-import asyncio-import jsonfrom unittest.mock import patchimport pytestfrom django.contrib.auth import get_user_model+from mcp_fixtures import call_toolfrom rest_framework.test import APIClientfrom overbae.models import APIToken, Dataset, Project, ProjectMembership-from overbae.services.datasets import paths, store, use, workbench-from overbae.services.mcp.catalog import CATALOG-from overbae.services.mcp.context import MCPContext, bind_context-from overbae.services.mcp.resources import read_resource+from overbae.services.datasets import paths, store, use+from overbae.services.mcp.context import MCPContextfrom tests.workshop_script_fixtures import (- conversation_script,execute_fixture,retained_package,select_script,)-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("lineage")]def workspace():@@ -42,152 +38,12 @@ def workspace():def call(context, tool, arguments):- result = asyncio.run(CATALOG.call(tool, arguments, context))+ result = call_tool(tool, arguments, context)assert not result.isError, resultreturn result.structuredContent-def test_native_agent_prepares_data_without_a_platform_agent():- project, client, context = workspace()- response = client.post(- "/api/datasets/",- {- "project": str(project.pk),- "name": "Support examples",- "brief": "Prepare training examples",- "intent": "train",- "source": {- "rows": [- {"question": "Where is my order?", "answer": "Check the tracking link."},- {- "question": "Can I return it?",- "answer": "Returns are accepted in 30 days.",- },- ]- },- },- format="json",- )- assert response.status_code == 201, response.data- dataset = Dataset.objects.get(pk=response.data["id"])- source = dataset.active_cell- recipe = call(- context,- "save_dataset_pipeline",- {- "dataset": str(dataset.pk),- "name": "Conversation format",- "request_key": "recipe-1",- "package": retained_package(- context.project, context.user, [conversation_script("question", "answer")]- ),- },- )- arguments = {- "dataset": str(dataset.pk),- "pipeline": recipe["pipeline"]["id"],- "source_cell": str(source.pk),- "source_fingerprint": source.fingerprint,- "request_key": "run-1",- }- from overbae.services.datasets.workbench import execute-- with patch("overbae.tasks.datasets.execute_pipeline.delay") as dispatch:- receipt = call(context, "run_dataset_pipeline", arguments)- dispatch.assert_called_once_with(receipt["run"]["id"])- execute(receipt["run"]["id"], script_executor=execute_fixture)- repeated = call(context, "run_dataset_pipeline", arguments)- assert repeated["run"]["id"] == receipt["run"]["id"]- job = call(context, "get_job", {"kind": "dataset_pipeline", "id": receipt["job"]["id"]})- assert job["status"] == "completed"- assert job["details"]["source_fingerprint"] == source.fingerprint-- async def read_receipt():- with bind_context(context):- content = list(await read_resource(receipt["job"]["resource"]["uri"]))- return json.loads(content[0].content)-- assert asyncio.run(read_receipt())["output_cell"] == repeated["run"]["output_cell"]- dataset.refresh_from_db()- output = dataset.active_cell- assert output.pk != source.pk- assert output.rows == 2- assert use.check(dataset, "train", cell=output) is not None- assert (- list(store.iter_rows(paths.cell_path(dataset.pk, source.pk)))[0]["question"]- == "Where is my order?"- )- detail = client.get(f"/api/datasets/{dataset.pk}/workbench/")- assert detail.status_code == 200- assert detail.data["runs"][0]["output_cell"] == str(output.pk)- assert detail.data["pipelines"][0]["fingerprint"]--- "steps",- [- [conversation_script("question", "answer")],- [select_script(["question", "answer"])],- ],-)-def test_pipeline_does_not_reinterpret_landed_parent_fields(steps):- project, client, context = workspace()- response = client.post(- "/api/datasets/",- {- "project": str(project.pk),- "name": "Landed parent metadata",- "intent": "explore",- "source": {- "rows": [- {- "question": f"Question {i}",- "answer": f"Answer {i}",- "_overmind_parent_rows": [0],- }- for i in range(3)- ]- },- },- format="json",- )- assert response.status_code == 201, response.data- dataset = Dataset.objects.get(pk=response.data["id"])- source = dataset.active_cell- recipe = call(- context,- "save_dataset_pipeline",- {- "dataset": str(dataset.pk),- "name": "Preserve identities",- "request_key": "preserve-identities",- "package": retained_package(context.project, context.user, steps),- },- )- with patch("overbae.tasks.datasets.execute_pipeline.delay"):- receipt = call(- context,- "run_dataset_pipeline",- {- "dataset": str(dataset.pk),- "pipeline": recipe["pipeline"]["id"],- "source_cell": str(source.pk),- "source_fingerprint": source.fingerprint,- "request_key": "preserve-identities",- },- )- workbench.execute(receipt["run"]["id"], script_executor=execute_fixture)- job = call(context, "get_job", {"kind": "dataset_pipeline", "id": receipt["job"]["id"]})- assert job["status"] == "completed", job- dataset.refresh_from_db()- output = list(store.iter_rows(paths.cell_path(dataset.pk, dataset.active_cell.pk)))- assert [row["source_row"] for row in output] == [0, 1, 2]- assert [row["_overmind_provenance"]["parents"][0]["row"] for row in output] == [0, 1, 2]- assert [row["answer"] for row in output] == [f"Answer {i}" for i in range(3)]- original = list(store.iter_rows(paths.cell_path(dataset.pk, source.pk)))- assert all(row["_overmind_parent_rows"] == [0] for row in original)--[email protected]("tenancy")def test_pipeline_conflicts_and_project_isolation_preserve_the_source():project, client, context = workspace()response = client.post(@@ -212,27 +68,23 @@ def test_pipeline_conflicts_and_project_isolation_preserve_the_source():"package": retained_package(context.project, context.user, [select_script(["text"])]),},)- result = asyncio.run(- CATALOG.call(- "run_dataset_pipeline",- {- "dataset": str(dataset.pk),- "pipeline": recipe["pipeline"]["id"],- "source_cell": str(source.pk),- "source_fingerprint": "0" * 64,- "request_key": "stale",- },- context,- )+ result = call_tool(+ "run_dataset_pipeline",+ {+ "dataset": str(dataset.pk),+ "pipeline": recipe["pipeline"]["id"],+ "source_cell": str(source.pk),+ "source_fingerprint": "0" * 64,+ "request_key": "stale",+ },+ context,)assert result.isErrorforeign = Project.objects.create(name="Other", slug="other-workshop")- denied = asyncio.run(- CATALOG.call(- "inspect_dataset_workbench",- {"dataset": str(dataset.pk)},- MCPContext(user=context.user, token=context.token, project=foreign),- )+ denied = call_tool(+ "inspect_dataset_workbench",+ {"dataset": str(dataset.pk)},+ MCPContext(user=context.user, token=context.token, project=foreign),)assert denied.isErrordataset.refresh_from_db()@@ -240,17 +92,6 @@ def test_pipeline_conflicts_and_project_isolation_preserve_the_source():assert dataset.cells.count() == 1-def test_brief_only_dataset_stays_available_without_scheduling_intelligence():- project, client, _ = workspace()- response = client.post(- "/api/datasets/",- {"project": str(project.pk), "name": "New data", "brief": "Prepare a training dataset"},- format="json",- )- assert response.status_code == 201, response.data- assert response.data["state"] == "idle"--def test_failed_external_lineage_and_cancelled_runs_never_publish():from overbae.services.datasets.workbench import execute@@ -361,9 +202,7 @@ def test_external_output_records_attribution_and_preserves_frozen_inputs():next(store.iter_rows(paths.cell_path(dataset.pk, source.pk)))["expected_output"]== "Source answer")- conflict = asyncio.run(- CATALOG.call("import_dataset_version", {**args, "name": "Different request"}, context)- )+ conflict = call_tool("import_dataset_version", {**args, "name": "Different request"}, context)assert conflict.isErrorselected = call(context, "update_dataset", {"dataset": str(dataset.pk), "active": str(source.pk)}@@ -373,38 +212,6 @@ def test_external_output_records_attribution_and_preserves_frozen_inputs():assert dataset.active_id == source.pk-def test_retired_agent_and_arbitrary_code_surfaces_are_not_available():- project, client, context = workspace()- response = client.post(- "/api/datasets/",- {"project": str(project.pk), "name": "Draft", "brief": "Prepare data"},- format="json",- )- dataset_id = response.data["id"]- for tool in ("message_dataset_agent", "run_dataset", "manage_dataset_workflow"):- assert asyncio.run(CATALOG.call(tool, {"dataset": dataset_id}, context)).isError- for path in ("chat", "run", "cells/00000000-0000-0000-0000-000000000001"):- response = client.post(f"/api/datasets/{dataset_id}/{path}/", {}, format="json")- assert response.status_code == 404- for path in ("cells", "workflow"):- assert (- client.post(f"/api/datasets/{dataset_id}/{path}/", {}, format="json").status_code == 404- )- invalid = asyncio.run(- CATALOG.call(- "save_dataset_pipeline",- {- "dataset": dataset_id,- "name": "Untrusted code",- "request_key": "code",- "steps": [{"operation": "python", "code": "import os"}],- },- context,- )- )- assert invalid.isError--def test_large_external_artifact_is_project_scoped_and_retained():from overbae.services.datasets.workbench import execute@@ -495,23 +302,6 @@ def test_invalid_recipes_are_rejected_and_metadata_updates_are_atomic():assert dataset.name == "Original"-def test_removed_chatgpt_routes_are_absent_and_local_accounts_remain():- project, client, context = workspace()- user_id = context.user.pk- for path in (- "",- "start/",- "login/",- "callback/",- "callback/session/",- "disconnect/",- "models/",- ):- assert client.get(f"/api/chatgpt/{path}").status_code == 404- assert client.post(f"/api/chatgpt/{path}", {}, format="json").status_code == 404- assert type(context.user).objects.filter(pk=user_id).exists()--def test_queued_source_cancellation_releases_the_dataset_without_publishing():from overbae.tasks import datasets as tasksdiff --git a/tests/test_workshop_retained_code_contract.py b/tests/test_workshop_retained_code_contract.pyindex c967f699..561394fa 100644--- a/tests/test_workshop_retained_code_contract.py+++ b/tests/test_workshop_retained_code_contract.py@@ -1,17 +1,16 @@-import asyncioimport uuidfrom unittest.mock import patchimport pytest+from mcp_fixtures import call_toolfrom overbae.models import Dataset, DatasetPipeline, DatasetPipelineBinding, DatasetPipelineRunfrom overbae.services.datasets import pipeline_bindings, workbenchfrom overbae.services.datasets.lifecycle import DatasetError-from overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.contracts.workbench import SaveInputfrom tests.test_workshop_redesign import workspace-pytestmark = pytest.mark.django_db(transaction=True)+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("sandbox")]def historical_workspace():@@ -37,12 +36,8 @@ def historical_workspace():@pytest.mark.parametrize("extra", [{}, {"steps": [{"operation": "select", "columns": ["text"]}]}])def test_mcp_requires_retained_package_before_creating_revision(extra):project, _, context = workspace()- result = asyncio.run(- CATALOG.call(- "save_dataset_pipeline",- {"name": "Selection", "request_key": "missing", **extra},- context,- )+ result = call_tool(+ "save_dataset_pipeline", {"name": "Selection", "request_key": "missing", **extra}, context)assert result.isError, resultassert "package" in str(result.structuredContent).lower()diff --git a/tests/test_workshop_training_migration.py b/tests/test_workshop_training_migration.pydeleted file mode 100644index 74c6aca2..00000000--- a/tests/test_workshop_training_migration.py+++ /dev/null@@ -1,108 +0,0 @@-import uuid--import psycopg2-import pytest-from django.db import connections-from django.db.backends.postgresql.base import DatabaseWrapper-from django.db.migrations.executor import MigrationExecutor-from django.db.migrations.recorder import MigrationRecorder-from django.test import override_settings--TARGET = ("overbae", "0005_workshop_training")-BASE = ("overbae", "0004_finetuningjob_eval_cell")-BEAT = ("django_celery_beat", "0001_initial")---def scratch_database():- settings = connections["default"].settings_dict- name = f"migration_{uuid.uuid4().hex[:12]}"- admin = psycopg2.connect(- dbname="postgres",- user=settings["USER"],- password=settings["PASSWORD"],- host=settings["HOST"],- port=settings["PORT"],- )- admin.autocommit = True- admin.cursor().execute(f'CREATE DATABASE "{name}"')- try:- yield name- finally:- admin.cursor().execute(f'DROP DATABASE IF EXISTS "{name}" WITH (FORCE)')- admin.close()---def test_consolidated_migration_preserves_data_and_applied_history(- scratch_database, django_db_blocker-):- original = connections["default"]- database = DatabaseWrapper(- {**original.settings_dict, "NAME": scratch_database}, alias="default"- )- with django_db_blocker.unblock(), override_settings(MIGRATION_MODULES={}):- connections["default"] = database- try:- executor = MigrationExecutor(database)- executor.migrate([BASE, BEAT])- apps = executor.loader.project_state([BASE, BEAT]).apps- project = apps.get_model("overbae", "Project").objects.create(name="Migration")- dataset = apps.get_model("overbae", "Dataset").objects.create(- project=project, name="Evaluation", intent="eval"- )- cell_model = apps.get_model("overbae", "Cell")- pinned = cell_model.objects.create(- dataset=dataset, position=0, state="ok", fingerprint="old"- )- active = cell_model.objects.create(- dataset=dataset, position=1, state="ok", fingerprint="new"- )- dataset.active = active- dataset.save(update_fields=["active"])- job_model = apps.get_model("overbae", "FinetuningJob")- job = job_model.objects.create(project=project, dataset=dataset, eval_dataset=dataset)- fallback = job_model.objects.create(- project=project, dataset=dataset, eval_dataset=dataset- )- already_pinned = job_model.objects.create(- project=project, dataset=dataset, eval_dataset=dataset, eval_cell=pinned- )- run = apps.get_model("overbae", "EvalRun").objects.create(- project=project, dataset=dataset, cell=pinned- )- apps.get_model("overbae", "FinetuningJobEval").objects.create(- job=job, eval_run=run, kind="baseline"- )- task_model = apps.get_model("django_celery_beat", "PeriodicTask")- janitor = task_model.objects.create(- name="Old janitor", task="overbae.tasks.inference_controller.janitor_stuck_fsm"- )- other = task_model.objects.create(name="Other task", task="other.task")-- executor = MigrationExecutor(database)- executor.migrate([TARGET])- apps = executor.loader.project_state([TARGET]).apps- job_model = apps.get_model("overbae", "FinetuningJob")- assert job_model.objects.get(pk=job.pk).eval_cell_id == pinned.pk- assert job_model.objects.get(pk=fallback.pk).eval_cell_id == active.pk- assert job_model.objects.get(pk=already_pinned.pk).eval_cell_id == pinned.pk- assert job_model.objects.get(pk=job.pk).eval_incumbent_before is True- assert job_model.objects.get(pk=job.pk).eval_model_before is False- assert job_model._meta.get_field("eval_incumbent_before").default is False- assert job_model._meta.get_field("eval_model_before").default is True- task_model = apps.get_model("django_celery_beat", "PeriodicTask")- assert task_model.objects.get(pk=janitor.pk).enabled is False- assert task_model.objects.get(pk=other.pk).enabled is True- assert apps.get_model("overbae", "TrainingPreparation").objects.count() == 0-- # A database upgraded with the nine original files must not replay their DDL.- recorder = MigrationRecorder(database)- recorder.record_unapplied(*TARGET)- executor = MigrationExecutor(database)- assert executor.migration_plan([TARGET]) == []- executor.migrate([TARGET])- assert TARGET in recorder.applied_migrations()- assert job_model.objects.count() == 3- finally:- database.close()- connections["default"] = original