Skip to content

The platform for continuously improving AI agents.

9.9 KB
Raw Blame
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
from unittest.mock import patch

import pytest
from django.db import close_old_connections, transaction
from factories import make_project, make_user

from overbae.models import ResearchAgent, ResearchAssignment, ResearchWake
from overbae.services import (
    research,
    research_agent,
    research_wakes,
    research_workspace,
)
from overbae.tasks.research import advance, reconcile

# Wakes are recorded after commit, so these run in real transactions.
pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("state-machines")]


def assignment():
    user = make_user()
    return research.create(
        make_project(member=user),
        user=user,
        request_key="wake",
        objective="Inspect retained experiment evidence",
        task={"deliverable": "A retained report"},
        budget={},
    )


def test_benchmark_progress_waits_for_a_result_or_failure():
    benchmark = {
        "id": "retained",
        "state": "preparing",
        "stages": {"prepare": {"state": "running"}},
        "costs": {},
    }
    before = research_agent.evidence_identity({"benchmarks": [benchmark]})
    benchmark.update(
        state="predicting",
        stages={"prepare": {"state": "completed"}, "predict": {"state": "running"}},
        costs={"estimated_usd": 0.2},
    )
    assert research_agent.evidence_identity({"benchmarks": [benchmark]}) == before
    benchmark["stages"]["predict"]["error"] = "Worker failed"
    assert research_agent.evidence_identity({"benchmarks": [benchmark]}) != before
    benchmark.update(state="completed", stages={}, results={"completion": {"status": "complete"}})
    assert research_agent.evidence_identity({"benchmarks": [benchmark]}) != before


def test_notifications_coalesce_and_a_later_event_is_delivered():
    run = assignment()
    expected = {str(value) for value in run.agents.values_list("pk", flat=True)}
    with patch("overbae.tasks.research.advance.delay") as sent:
        research.event(run, "measurement", {"step": 1})
        research.event(run, "measurement", {"step": 2})
        research_wakes.deliver()
        assert {call.args[0] for call in sent.call_args_list} == expected
        assert sent.call_count == len(expected)
        research_wakes.deliver()
        assert sent.call_count == len(expected)
        research.event(run, "measurement", {"step": 3})
        research_wakes.deliver()
        assert sent.call_count == 2 * len(expected)


def test_broker_failure_leaves_a_durable_pending_wake():
    run = assignment()
    with (
        patch("overbae.tasks.research.advance.delay", side_effect=ConnectionError("broker")),
        pytest.raises(ConnectionError),
    ):
        research_wakes.deliver()
    wake = ResearchWake.objects.get(assignment=run)
    assert wake.generation > wake.delivered_generation
    with patch("overbae.tasks.research.advance.delay") as sent:
        research_wakes.deliver()
        assert sent.called
    wake.refresh_from_db()
    assert wake.generation == wake.delivered_generation


def test_rolled_back_evidence_cannot_publish_a_wake():
    run = assignment()
    generation = ResearchWake.objects.get(assignment=run).generation
    with pytest.raises(ValueError), transaction.atomic():
        research.event(run, "measurement", {"step": 99})
        raise ValueError("reject evidence")
    assert ResearchWake.objects.get(assignment=run).generation == generation
    assert not run.events.filter(payload__step=99).exists()


def test_wake_request_holds_no_row_lock_inside_the_writers_transaction():
    run = assignment()

    def lock_from_another_connection():
        close_old_connections()
        try:
            with transaction.atomic():
                ResearchWake.objects.select_for_update(nowait=True).get(assignment=run)
        finally:
            close_old_connections()

    with transaction.atomic():
        research.event(run, "measurement", {"step": 1})
        with ThreadPoolExecutor(max_workers=1) as pool:
            pool.submit(lock_from_another_connection).result(timeout=5)


def test_completed_child_wakes_its_controller_without_restarting_the_child():
    parent = assignment()
    child = research.create(
        parent.project,
        user=parent.created_by,
        request_key="child",
        objective="Inspect data",
        task={"controller_assignment": str(parent.pk)},
        budget={},
    )
    with patch("overbae.tasks.research.advance.delay"):
        research_wakes.deliver()
    child.state = "completed"
    child.save(update_fields=["state"])
    research.event(child, "completed", {})
    with patch("overbae.tasks.research.advance.delay") as sent:
        research_wakes.deliver()
        assert {call.args[0] for call in sent.call_args_list} == {
            str(value) for value in parent.agents.values_list("pk", flat=True)
        }


def test_recovery_scan_does_not_starve_owners_after_the_first_batch():
    run = assignment()
    ResearchAgent.objects.bulk_create(
        [
            ResearchAgent(
                assignment=run,
                request_key=f"recovery-{index}",
                fingerprint=str(index).zfill(64),
                task="Wait for retained evidence",
                state="waiting",
            )
            for index in range(105)
        ]
    )
    ResearchWake.objects.all().delete()
    with patch("overbae.tasks.research.advance.delay") as sent:
        reconcile()
    assert {call.args[0] for call in sent.call_args_list} == {
        str(value) for value in run.agents.values_list("pk", flat=True)
    }


@pytest.mark.covers("recovery")
def test_scoped_wake_drain_recovers_pending_generation_without_delivering_outside_scope():
    user = make_user()
    project = make_project(member=user)
    runs = [
        research.initialize(
            project,
            user=user,
            request_key=key,
            objective="Inspect retained evidence",
            task={"deliverable": "A retained observation"},
            budget={},
            execution_mandate={"authority": "observe", "families": ["read", "author"]},
        )
        for key in ["inside", "outside"]
    ]
    inside, outside = runs
    with patch("overbae.tasks.research.dispatch_wakes.delay"):
        for run in runs:
            research_wakes.record(run.pk)
    outside_before = ResearchWake.objects.get(assignment=outside)
    generation = outside_before.generation
    delivered = outside_before.delivered_generation
    eligible = ResearchAssignment.objects.filter(pk=inside.pk)
    with patch.object(advance, "delay") as sent:
        research_wakes.deliver(assignments=eligible)
        research_wakes.deliver(assignments=eligible)
    assert [call.args[0] for call in sent.call_args_list] == [
        str(inside.agents.get(parent__isnull=True).pk)
    ]
    inside_wake = ResearchWake.objects.get(assignment=inside)
    outside_before.refresh_from_db()
    assert inside_wake.generation == inside_wake.delivered_generation
    assert outside_before.generation == generation > delivered
    assert outside_before.delivered_generation == delivered


@pytest.mark.covers("recovery")
def test_workspace_lookup_failure_does_not_starve_unrelated_recovery(fake_modal, caplog):
    stopped = assignment()
    lead = stopped.agents.get(parent__isnull=True)
    fake_modal.sandbox_create_error = TimeoutError("Creation acknowledgement lost")
    with pytest.raises(TimeoutError):
        research_workspace.attach(lead)
    lead.refresh_from_db()
    original = deepcopy(lead.workspace)
    assert original["creation_started"] and not original.get("sandbox")
    sandbox = next(iter(fake_modal.sandboxes.values()))
    assert sandbox.options["name"] == original["name"]
    fake_modal.sandbox_create_error = None
    fake_modal.sandbox_lookup_error = TimeoutError("Provider lookup unavailable")
    with patch("overbae.tasks.research.settle_stop.delay"):
        research.stop(stopped)

    healthy = assignment()
    waiting = research_agent.lease(healthy.agents.get(parent__isnull=True).pk)
    research_agent.yield_turn(waiting, "Waiting for source evidence")
    waiting.refresh_from_db()
    assert waiting.state == "waiting" and not research_agent.wake_needed(waiting)
    research.event(healthy, "trigger_evidence", {"result": "A new retained measurement"})
    expected = {str(identifier) for identifier in healthy.agents.values_list("pk", flat=True)}
    with patch("overbae.tasks.research.advance.delay") as sent:
        # The notification was delivered, but its worker never observed the evidence.
        research_wakes.deliver()
        sent.reset_mock()
        for _ in range(2):
            reconcile()
            assert {call.args[0] for call in sent.call_args_list} == expected
            sent.assert_any_call(str(waiting.pk), wake=True)
            sent.reset_mock()
            stopped.refresh_from_db()
            lead.refresh_from_db()
            assert stopped.state == "stopping"
            assert lead.workspace == original
            assert len(fake_modal.sandboxes) == 1 and sandbox.exit_code is None
        failures = [
            record
            for record in caplog.records
            if record.name == "overbae.tasks.research" and record.exc_info
        ]
        assert len(failures) == 2
        assert all(record.args == (stopped.pk,) for record in failures)

        fake_modal.sandbox_lookup_error = None
        for _ in range(2):
            reconcile()
            sent.assert_any_call(str(waiting.pk), wake=True)
            sent.reset_mock()
            stopped.refresh_from_db()
            lead.refresh_from_db()
            assert stopped.state == "cancelled"
            assert lead.workspace["sandbox"] == sandbox.object_id
            assert lead.workspace["stopped_at"] and sandbox.exit_code == 137
            assert {
                key: lead.workspace[key] for key in ("name", "environment", "lease", "generation")
            } == {key: original[key] for key in ("name", "environment", "lease", "generation")}
            assert len(fake_modal.sandboxes) == 1