The platform for continuously improving AI agents.
from copy import deepcopy
from datetime import timedelta
from unittest.mock import patch
from uuid import uuid4
import pytest
from django.utils import timezone
from test_experiment_engine import checkpoint_schema as checkpoint_schema
from test_experiment_engine import flow, investigating
from test_research_experiments import setup_experiment
from overbae.core.errors import DatasetError, InputValidationError
from overbae.models import Cell, Dataset, DatasetPipelineRun, Project, User
from overbae.services import (
execution_mandates,
research,
research_experiments,
research_tools,
)
from overbae.services.datasets import land, measure, paths, store
from overbae.services.workshop_agent import agent as workshop_agent
from overbae.services.workshop_agent import conversation, lifecycle
from overbae.services.workshop_agent.contracts import StartTask
pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]
def admitted(experiment, user, source, *, authority="act", key="admitted"):
mandate = execution_mandates.admission(
roots=[f"cell:{source.pk}"], experiment=experiment.pk, authority=authority
)
mandate["sources"][0]["fingerprint"] = source.fingerprint
return research_experiments.start(
experiment,
user,
revision=experiment.version,
request_key=key,
budget={},
execution_mandate=mandate,
)
def test_child_inherits_a_fingerprint_pin_but_cannot_replace_it():
experiment, user, dataset = setup_experiment()
assignment = admitted(experiment, user, dataset.active_cell)
child = execution_mandates.admission(roots=[f"cell:{dataset.active_cell.pk}"])
inherited = execution_mandates.intersect(assignment.execution_mandate, child)
assert inherited["sources"][0]["fingerprint"] == dataset.active_cell.fingerprint
child["sources"][0]["fingerprint"] = "f" * 64
with pytest.raises(InputValidationError):
execution_mandates.intersect(assignment.execution_mandate, child)
def test_an_empty_source_grant_does_not_allow_other_project_data():
experiment, user, dataset = setup_experiment()
assignment = research.create(
experiment.project,
user=user,
request_key="no-sources",
objective="Inspect the request",
task={"deliverable": "Report"},
budget={},
)
assert (
research_tools.source_cell(assignment, dataset.active_cell.pk).pk == dataset.active_cell.pk
)
_, _, foreign = setup_experiment()
with pytest.raises(InputValidationError):
execution_mandates.require_cell(
assignment.execution_mandate, foreign.active_cell, assignment=assignment
)
def test_omitting_a_mandate_on_retry_recovers_its_retained_observation_authority():
experiment, user, dataset = setup_experiment()
assignment = admitted(experiment, user, dataset.active_cell, authority="observe")
original = deepcopy(assignment.execution_mandate)
replayed = research_experiments.start(
experiment, user, revision=experiment.version, request_key="admitted", budget={}
)
assert replayed.pk == assignment.pk
assert replayed.execution_mandate == original
with pytest.raises(InputValidationError):
research_experiments.start(
experiment,
user,
revision=experiment.version,
request_key="admitted",
budget={},
execution_mandate=execution_mandates.admission(
roots=[f"cell:{dataset.active_cell.pk}"]
),
)
def test_observation_blocks_delegated_preparation_at_the_actual_task_admission():
experiment, user, dataset = setup_experiment()
assignment = admitted(experiment, user, dataset.active_cell, authority="observe")
with pytest.raises(DatasetError) as refused:
lifecycle.start(
lifecycle.NativeGrant(
experiment.project,
user,
parent_assignment=assignment,
execution_mandate=assignment.execution_mandate,
),
StartTask(dataset=dataset.pk, objective="Prepare", request_key="delegated"),
)
assert getattr(refused.value, "code", None) == "permission_denied"
assert not assignment.workshop_tasks.exists()
def test_parent_cancellation_blocks_workshop_effects_after_delegation():
experiment, user, dataset = setup_experiment()
source = dataset.active_cell
assignment = admitted(experiment, user, source)
task = lifecycle.start(
lifecycle.NativeGrant(
experiment.project,
user,
parent_assignment=assignment,
execution_mandate=assignment.execution_mandate,
),
StartTask(dataset=dataset.pk, objective="Prepare", request_key="delegated"),
)
action, _ = lifecycle.claim(task.pk, 0, "prepare_workshop_environment", {})
research.stop(assignment)
turn = workshop_agent.Turn(task, source, {"turn": 1, "publications": []}, action)
with pytest.raises(DatasetError) as refused:
turn.prepare("New preparation", {})
assert getattr(refused.value, "code", None) in {"permission_denied", "dataset_busy"}
assert not DatasetPipelineRun.objects.filter(dataset=task.dataset).exists()
def test_workshop_reads_new_published_versions_but_rejects_changed_pinned_content():
experiment, user, dataset = setup_experiment()
pinned = dataset.active_cell
assignment = admitted(experiment, user, pinned)
task = lifecycle.start(
lifecycle.NativeGrant(
experiment.project,
user,
parent_assignment=assignment,
execution_mandate=assignment.execution_mandate,
),
StartTask(dataset=dataset.pk, objective="Prepare", request_key="delegated"),
)
unadmitted = Cell.objects.create(dataset=dataset, position=1, title="New version")
path = paths.cell_path(dataset.pk, unadmitted.pk)
store.write_rows(path, [{"input": "unadmitted", "expected_output": "new"}])
measure.frame(dataset, unadmitted, path)
lifecycle.source(task, unadmitted)
pinned.fingerprint = "f" * 64
with pytest.raises(InputValidationError, match="fingerprint"):
lifecycle.source(task, pinned)
def test_delegated_workshop_history_cannot_import_another_tasks_source_scope():
experiment, user, dataset = setup_experiment()
context = Dataset.objects.create(project=experiment.project, name="Restricted reference")
land.land_rows(context, [{"input": "private reference", "expected_output": "secret answer"}])
prior = lifecycle.start(
lifecycle.NativeGrant(experiment.project, user),
StartTask(
dataset=dataset.pk,
objective="Compare both inputs",
context_datasets=[context.pk],
request_key="broad-history",
),
)
workshop_agent.settle(
prior, workshop_agent.load(prior), "completed", "The reference says secret answer"
)
assignment = admitted(experiment, user, dataset.active_cell)
task = lifecycle.start(
lifecycle.NativeGrant(
experiment.project,
user,
parent_assignment=assignment,
execution_mandate=assignment.execution_mandate,
),
StartTask(
dataset=dataset.pk,
objective="Inspect only the admitted input",
request_key="narrow-history",
),
)
assert conversation.history(task) == []
source, previous = workshop_agent.pinned(task)
assert workshop_agent.briefing(task, source, previous)["conversation"] == []
assert prior.chat_events.filter(message__text="The reference says secret answer").exists()
def test_child_source_selection_requires_project_authority_and_preserves_pins():
_, _, dataset = setup_experiment()
parent = execution_mandates.admission(roots=[f"dataset:{dataset.pk}"])
child = execution_mandates.admission(roots=[f"cell:{dataset.active_cell.pk}"])
with pytest.raises(InputValidationError, match="project authority"):
execution_mandates.intersect(parent, child)
inherited = execution_mandates.intersect(parent, child, project=dataset.project)
assert inherited["sources"][0]["fingerprint"] == dataset.active_cell.fingerprint
_, _, foreign = setup_experiment()
child = execution_mandates.admission(roots=[f"cell:{foreign.active_cell.pk}"])
with pytest.raises(InputValidationError, match="project"):
execution_mandates.intersect(parent, child, project=dataset.project)
@pytest.mark.parametrize(
"changed", ["stop", "deadline", "missing", "malformed", "request_key", "contradictory"]
)
def test_adaptive_child_checks_its_retained_parent_before_workshop_admission(changed):
experiment, user = flow()
parent, receipt, child = investigating(experiment, user)
assert execution_mandates.require(child, "prepare")["authority"] == "act"
if changed == "stop":
with patch("overbae.tasks.research.settle_stop.delay"):
research.stop(parent)
elif changed == "deadline":
parent.deadline = timezone.now() - timedelta(seconds=1)
parent.save(update_fields=["deadline"])
elif changed == "request_key":
child.request_key = "unrelated-child"
child.save(update_fields=["request_key"])
else:
task = child.specification["task"]
if changed == "contradictory":
task["controller_action"] = str(receipt.action_id)
else:
task["flow_run"] = str(uuid4()) if changed == "missing" else "not-a-uuid"
child.save(update_fields=["specification"])
child.refresh_from_db()
assert child.state == "running"
source = child.specification["task"]["inputs"]["data"]
with pytest.raises(InputValidationError):
lifecycle.start(
lifecycle.NativeGrant(
child.project,
user,
parent_assignment=child,
execution_mandate=child.execution_mandate,
),
StartTask(
dataset=Cell.objects.get(pk=source["cell"]).dataset_id,
objective="Prepare development data",
request_key="after-parent-change",
),
)
assert not child.workshop_tasks.exists()
@pytest.mark.parametrize("revocation", ["user", "project"])
def test_retained_related_objects_do_not_preserve_revoked_execution_authority(revocation):
experiment, user, _ = setup_experiment()
owner = research.create(
experiment.project,
user=user,
request_key="cached-principal",
objective="Inspect retained evidence",
task={"deliverable": "Report"},
budget={},
)
assert owner.created_by.is_active and owner.project.is_active
if revocation == "user":
User.objects.filter(pk=owner.created_by_id).update(is_active=False)
else:
Project.objects.filter(pk=owner.project_id).update(is_active=False)
with pytest.raises(InputValidationError):
execution_mandates.require(owner, "read")