The platform for continuously improving AI agents.
"""No context-length literals live in product code — these tests read the same
models.json catalog the code does."""
from __future__ import annotations
import uuid
from unittest.mock import Mock
import pytest
from conftest import EVAL_ROWS, TRAIN_ROWS, frozen_dataset
from django.test import override_settings
from factories import make_matrix_row
from overbae.core.errors import InputValidationError
from overbae.modal.model_registry import (
get_sft_context_length,
get_training_context_policy,
min_sft_context_length,
)
from overbae.models import Capability, EvalSet
from overbae.services.finetuning_runner import snap_context_length
from overbae.services.recommendation.analysis import build_analysis
from overbae.services.recommendation.constraints import eligible_models
from overbae.services.recommendation.hyperparams import compute_hyperparams
pytestmark = pytest.mark.covers("plans")
_POLICY = get_training_context_policy("modal")
_BUCKETS = sorted(int(b) for b in _POLICY["context_buckets"])
_HEADROOM = int(_POLICY["context_headroom"])
class TestCatalogContextPolicy:
def test_policy_comes_from_catalog(self):
assert _BUCKETS, "modal context buckets must be defined in models.json"
assert _HEADROOM > 0
def test_unknown_backend_raises(self):
with pytest.raises(KeyError):
get_training_context_policy("no-such-backend")
def test_modal_models_are_not_uniformly_capped(self):
assert get_sft_context_length("Qwen/Qwen3-0.6B", backend="modal") == 40960
assert get_sft_context_length("LiquidAI/LFM2.5-350M", backend="modal") == 32768
assert get_sft_context_length("meta-llama/Llama-3.1-8B-Instruct", backend="modal") == 131072
assert get_sft_context_length("Qwen/Qwen3.5-9B", backend="modal") == 262144
assert get_sft_context_length("fdtn-ai/antares-1b", backend="modal") == 131072
def test_min_sft_context_length(self):
smallest = min_sft_context_length("modal")
assert smallest is not None
assert smallest >= _BUCKETS[0]
class TestRecommendFiltersByDatasetContext:
@override_settings(FINETUNING_BACKEND="modal")
def test_eligible_models_drop_short_context(self):
# 50k tokens: Qwen3-0.6B trains at 40K and drops; Llama 8B and Qwen 3.5 remain.
filtered, excluded = eligible_models(has_tool_calling=False, max_row_tokens=50_000)
surviving = {m["id"] for models in filtered.values() for m in models}
assert surviving, "some models must still fit at 50k"
assert all(
(get_sft_context_length(mid, backend="modal") or 0) >= 50_000 + _HEADROOM
for mid in surviving
)
assert "Qwen/Qwen3-0.6B" not in surviving
assert "meta-llama/Llama-3.1-8B-Instruct" in surviving
reasons = {e.model: e.reason for e in excluded}
assert "50,000" in reasons["Qwen/Qwen3-0.6B"]
@override_settings(FINETUNING_BACKEND="modal")
def test_analysis_excludes_short_context_models(self):
stats = {
"num_examples": 100,
"avg_input_chars": 300,
"avg_output_chars": 60,
"has_tool_calling": False,
"max_token_length": 50_000,
}
analysis = build_analysis(stats, task_type="dialogue", task_type_source="heuristic")
assert analysis["candidates"]
for row in analysis["candidates"]:
model_max = get_sft_context_length(row["model"], backend="modal")
assert model_max is not None and model_max >= 50_000 + _HEADROOM
assert any("50,000" in e["reason"] for e in analysis["excluded"])
@override_settings(FINETUNING_BACKEND="modal")
def test_no_candidate_survives_rows_past_every_context_limit(self):
# Past every SFT max. Qwen4-35B-A3B trains at 1,048,576.
max_tokens = 1_048_576
eligible, _excluded = eligible_models(has_tool_calling=False, max_row_tokens=max_tokens)
assert not eligible
stats = {
"num_examples": 10,
"avg_input_chars": 100,
"avg_output_chars": 20,
"has_tool_calling": False,
"max_token_length": max_tokens,
}
analysis = build_analysis(stats, task_type="dialogue", task_type_source="heuristic")
assert analysis["candidates"] == []
assert analysis["excluded"]
# A model with no enabled training kind at all is rejected before context is
# even considered — that reason names no dataset size, unlike every other one.
assert all(
"1,048,576" in e["reason"] or e["reason"] == "No supported fine-tuning method"
for e in analysis["excluded"]
)
class TestSnapContextLength:
def test_default_is_smallest_bucket(self):
assert snap_context_length(0) == _BUCKETS[0]
assert snap_context_length(100) == _BUCKETS[0]
def test_snaps_up_never_down(self):
# A row over a bucket boundary must land in the next bucket — TRL would
# silently truncate it (corrupting targets) if we snapped down.
assert snap_context_length(_BUCKETS[0] + 1) == _BUCKETS[1]
assert snap_context_length(11051) == 16384
def test_headroom_pushes_boundary_rows_up(self):
assert snap_context_length(_BUCKETS[1] - _HEADROOM) == _BUCKETS[1]
assert snap_context_length(_BUCKETS[1]) == _BUCKETS[2]
def test_requested_wins_when_larger_than_need(self):
assert snap_context_length(100, requested=32768) == 32768
def test_caps_at_model_max_when_rows_fit(self):
# Requested context can still be clamped down when the dataset is short.
assert snap_context_length(100, model_max=4096, requested=16384) == 4096
def test_refuses_when_model_cannot_cover_longest_row(self):
from overbae.services.finetuning_policy import TrainingPlanError
with pytest.raises(TrainingPlanError, match="refusing to clamp"):
snap_context_length(20000, model_max=4096)
@pytest.mark.parametrize(
("needed_tokens", "requested", "expected"),
[(999_999, None, 999_999 + _HEADROOM), (0, 999_999, 999_999)],
)
def test_uncapped_context_never_truncates_to_largest_bucket(
self, needed_tokens, requested, expected
):
assert snap_context_length(needed_tokens, requested=requested) == expected
class TestRecommenderIncludesContext:
_ENTRY = {
"id": "Qwen/Qwen3-8B",
"total_params_b": 8.2,
"context_length_sft": 32768,
"min_batch_size": 1,
"max_batch_size": 8,
}
def test_hyperparams_include_snapped_context(self):
with override_settings(FINETUNING_BACKEND="modal"):
hp = compute_hyperparams(500, model_entry=self._ENTRY, max_row_tokens=11051)
assert hp["context_length"] == 16384
@pytest.mark.django_db
class TestJobSerializerContextValidation:
@pytest.mark.parametrize("source", ["evaluation_budget", "serving_plan"])
@pytest.mark.parametrize(
"failure_type", [ValueError, RuntimeError, OSError, InputValidationError]
)
def test_context_validation_only_exposes_authored_messages(
self, monkeypatch, source, failure_type
):
private = "Traceback: /srv/private/evaluation.py credential=hidden"
known = failure_type is InputValidationError
detail = "This workload needs a larger context window." if known else private
operation = Mock(side_effect=failure_type(detail))
monkeypatch.setattr(f"overbae.api.serializers.{source}", operation)
serializer = self._serializer(max_token_length=100, base_model="Qwen/Qwen3.5-9B")
assert not serializer.is_valid()
operation.assert_called_once()
assert private not in str(serializer.errors)
assert "base_model" in serializer.errors
if known:
assert detail in str(serializer.errors)
def _serializer(self, *, max_token_length: int, base_model: str):
from overbae.api.serializers import FinetuningJobSerializer
from overbae.models import Project, ProjectMembership, User
user = User.objects.create_user(
email=f"ctx-{uuid.uuid4().hex[:8]}@example.com",
password="pass",
clerk_user_id=f"clerk_{uuid.uuid4().hex}",
)
project = Project.objects.create(name="ctx", slug=f"ctx-{uuid.uuid4().hex[:8]}")
ProjectMembership.objects.create(user=user, project=project)
dataset = frozen_dataset(project, TRAIN_ROWS, contract="train")
evaluation = frozen_dataset(
project,
[{**row, "input": "held-out-" + row["input"]} for row in EVAL_ROWS],
contract="eval",
)
capability = Capability.objects.create(project=project, name="Judge", slug="judge")
eval_set = EvalSet.objects.create(project=project, capability=capability, name="Judges")
eval_set.rows.add(make_matrix_row(eval_set.project))
version = dataset.active_cell
version.stats = {**version.stats, "max_token_length": max_token_length}
version.save(update_fields=["stats"])
# Exact shape the wizard sends (frontend/src/routes/_auth/finetuning.tsx).
payload = {
"project": str(project.id),
"capability": None,
"dataset": str(dataset.id),
"eval_dataset": str(evaluation.id),
"eval_set": str(eval_set.id),
"group_id": str(uuid.uuid4()),
"base_model": base_model,
"model_tier": "small",
"name": "ctx-test",
"hyperparameters": {
"learning_rate": 1e-4,
"warmup_ratio": 0.05,
"training_type": {
"type": "Lora",
"lora_r": 16,
"lora_alpha": 32,
"lora_dropout": 0,
"lora_trainable_modules": "all-linear",
},
},
}
class _Req:
def __init__(self, u):
self.user = u
return FinetuningJobSerializer(data=payload, context={"request": _Req(user)})
@override_settings(FINETUNING_BACKEND="modal")
def test_rows_within_model_max_pass(self):
s = self._serializer(max_token_length=12309, base_model="Qwen/Qwen3.5-9B")
assert s.is_valid(), s.errors
@pytest.mark.parametrize("field", ["eval_dataset", "eval_set"])
@pytest.mark.parametrize("omit", [True, False])
def test_enabled_training_evaluations_require_inputs_without_capability(self, field, omit):
s = self._serializer(max_token_length=100, base_model="Qwen/Qwen3.5-9B")
s.initial_data["eval_model_before"] = True
if omit:
s.initial_data.pop(field)
else:
s.initial_data[field] = None
assert not s.is_valid()
assert field in s.errors
@override_settings(FINETUNING_BACKEND="modal")
def test_full_ft_rejected_when_catalog_disables_it(self):
"""Gemma 4 31B has full.enabled=false — wizard must not be able to submit Full."""
s = self._serializer(max_token_length=512, base_model="google/gemma-4-31B-it")
s.initial_data["hyperparameters"] = {
"learning_rate": 2e-5,
"warmup_ratio": 0.05,
"training_type": {"type": "Full"},
}
assert not s.is_valid()
assert "hyperparameters" in s.errors