Skip to content

The platform for continuously improving AI agents.

3.3 KB
Raw Blame
import asyncio
from datetime import timedelta

from asgiref.sync import ThreadSensitiveContext, sync_to_async
from django.core.management.base import BaseCommand
from django.db import connections
from django.db.models import Q
from django.utils import timezone
from temporalio.common import WorkflowIDReusePolicy
from temporalio.exceptions import WorkflowAlreadyStartedError
from temporalio.worker import ActivityInboundInterceptor, Interceptor, Worker

from overbae.core import temporal
from overbae.models import WorkshopTask
from overbae.services.workshop_agent.agent import fence_run, supervise_run
from overbae.services.workshop_agent.lifecycle import TERMINAL
from overbae.services.workshop_agent.sandbox import pending
from workflows.workshop import TASK_QUEUE, WorkshopTaskWorkflow

# Seconds between looks for a task that has no run: how long a new task waits to start.
DISPATCH_SECONDS = 0.5


class DatabaseActivity(ActivityInboundInterceptor):
    async def execute_activity(self, input):
        async with ThreadSensitiveContext():
            try:
                return await self.next.execute_activity(input)
            finally:
                await sync_to_async(connections.close_all, thread_sensitive=True)()


class DatabaseInterceptor(Interceptor):
    def intercept_activity(self, next):
        return DatabaseActivity(next)


class Command(BaseCommand):
    help = "Run Data Workshop tasks: each run of a task's loop is an activity of its workflow."

    def handle(self, *args, **options):
        asyncio.run(self.serve())

    async def serve(self):
        client = await temporal.connect()
        async with Worker(
            client,
            task_queue=TASK_QUEUE,
            workflows=[WorkshopTaskWorkflow],
            activities=[supervise_run, fence_run],
            max_concurrent_activities=16,
            interceptors=[DatabaseInterceptor()],
        ):
            while True:
                await dispatch(client)
                await asyncio.sleep(DISPATCH_SECONDS)


async def dispatch(client):
    repair = (
        pending(WorkshopTask.objects.all())
        .filter(Q(state__in=[*TERMINAL, "blocked", "paused"]) | Q(result__has_key="settlement"))
        .filter(Q(dispatched_at=None) | Q(dispatched_at__lt=timezone.now() - timedelta(minutes=5)))
    )
    tasks = await sync_to_async(list, thread_sensitive=True)(
        WorkshopTask.objects.filter(
            Q(dispatched_at=None) & ~Q(state__in=TERMINAL) | Q(pk__in=repair)
        )
        .order_by("dispatched_at", "created_at", "pk")
        .values_list("pk", "dispatch_generation", "dispatched_at")[:100]
    )
    for task_id, generation, dispatched_at in tasks:
        # A run still ending is asked again at the next look: it may have read the task
        # before the change that needs a run.
        try:
            await client.start_workflow(
                WorkshopTaskWorkflow.run,
                str(task_id),
                id=f"workshop-task:{task_id}",
                task_queue=TASK_QUEUE,
                id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
            )
        except WorkflowAlreadyStartedError:
            if dispatched_at is None:
                continue
        await sync_to_async(
            WorkshopTask.objects.filter(pk=task_id, dispatch_generation=generation).update,
            thread_sensitive=True,
        )(dispatched_at=timezone.now())