From f5bc919473a65ba22192eee940e86c36712aa3a9 Mon Sep 17 00:00:00 2001 From: Davide Silvestri <75379892+silvestrid@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:39:52 +0100 Subject: [PATCH] feat(celery): make every task work on a threads worker, and use one in dev (#6926) * chore(dev): run one threads Celery worker with beat in dev The Docker and native dev stacks start a single Celery worker for every queue, with redbeat embedded, instead of a worker, an export worker and a beat process. It uses a new ThreadsPool that sends worker_process_init, so telemetry and the lazy import check still run under the threads pool. * fix(ws): stop closing every event loop's Redis pools after a broadcast send_messages_to_channel_group called channel_layer.close_pools(), which closes the pools of every event loop, including the ones other worker threads are still sending with. Under the threads pool about a third of broadcasts failed with "attached to a different loop" and some hung. channels_redis now closes a loop's pools itself when that loop closes. * fix(telemetry): keep Celery trace context per thread on threads workers The Celery instrumentation keys a running task's span, context token and start time by the task's id. A task replaced with self.replace(), like every automation node, keeps its id, and on a threads worker the replacement can start in another thread before the original ends. The original then ended the replacement's span and detached its context from the wrong thread, logging "Failed to detach context" and leaving its own context on the thread. That state is now kept per thread. * feat(celery): enforce soft and hard time limits in ThreadsPool Celery's own threads pool ignores soft_time_limit and time_limit, so on a threads worker tasks that rely on them would run on. ThreadsPool now raises the limit in the task's thread, only while that task runs, so a limit never reaches the next task of the thread. EMAIL_TIMEOUT stops a silent SMTP server from blocking a worker thread forever. * fix(chat-runs): cancel a run that keeps going after its deadline The deadline only asks a run to stop. A run whose tools or provider call ignore that request now gets 60 more seconds, is then cancelled, and is saved as timed out. Celery's limit moves after that, so the run's own stop always comes first. On a threads worker this is the only way to end it, because a time limit can't reach a thread waiting inside async_to_sync. * fix(premium): share one capped thread pool across AI field generations Each generation started its own pool of BASEROW_AI_FIELD_MAX_CONCURRENT_GENERATIONS threads, so a threads worker running several jobs multiplied the threads and model calls. All generations in a process now share one pool of that size. A prefork process runs one job at a time, so nothing changes there. * feat(celery): cancel queries at the hard limit and report overdue tasks ThreadsPool checks every running task's time limits from one watchdog thread, like the prefork pool's timeout handler, instead of starting timer threads for each task. At the hard limit it also cancels the query the task's thread is running, which the limit's exception can't interrupt. A thread can't be killed, so a task still running 60 seconds after its hard limit is reported to Sentry instead. Every limit reached is counted in baserow.celery.task.time_limit, per task and limit. * fix(airtable): time out requests to Airtable Two Airtable import requests had no timeout, so a server that stopped answering held the import, and on a threads worker its thread, forever. All Airtable requests now use the same 3 minute read timeout. * fix(celery): load sentry_sdk only when reporting an overdue task The overdue report imported sentry_sdk at the top of baserow.config.celery, which every process imports, so it was loaded even with Sentry off. * chore: add a changelog entry for the Celery task timeouts * fix(celery): raise threads pool time limits at the task's next query An exception raised into a thread from outside can land right after a lock is taken and before the code that releases it, leaving the lock held for every thread of the worker. The pool now marks a reached limit and the task's own next query raises it, once, through a connection execute wrapper. The hard limit still cancels the running query, and raises TimeLimitExceeded whatever the soft limit is. Limits end before Celery's success callback runs. Savepoint queries are never interrupted, through a helper shared with the periodic field update deadline. * fix(celery): apply the worker default time limits on the threads pool Celery passes CELERY_TASK_SOFT_TIME_LIMIT and CELERY_TASK_TIME_LIMIT to the pool and None per task when a task sets no limit. The prefork pool falls back to the pool's values; the threads pool now does too. * fix(celery): keep threads pool time limits until running tasks end The watchdog stopped before on_stop waited for the running tasks, so a task passing its limit during a warm shutdown was never stopped or reported. * chore: name the emails the SMTP timeout covers in the changelog EMAIL_TIMEOUT applies to the instance's own emails only. Automation and builder SMTP steps already time out after 30 seconds. * chore(dev): drop dev.sh tabs for the removed Celery workers The export and beat services are disabled, so attaching to them made the script exit before opening the remaining tabs. * test(celery): cover thread time limits and savepoint rollback * fix(ai): use one generation slot for nonpositive limits * fix(chat): warn that an action may finish after a reply times out * docs(celery): explain which timeout guarantees require prefork * docs(celery): record the threads pool decision and task contract * fix(chat): keep the worker slot until started tools finish * fix(chat): warn visitors about repeating a timed-out request * docs(chat): clarify when the stop grace period begins --- backend/justfile | 58 +-- backend/src/baserow/config/celery.py | 300 ++++++++++++++++ backend/src/baserow/config/settings/base.py | 2 + .../contrib/database/airtable/constants.py | 3 + .../contrib/database/airtable/handler.py | 12 +- .../baserow/contrib/database/fields/tasks.py | 16 +- .../src/baserow/core/chat_runs/constants.py | 6 +- backend/src/baserow/core/chat_runs/runner.py | 26 +- backend/src/baserow/core/psycopg.py | 14 + backend/src/baserow/core/telemetry/celery.py | 64 +++- backend/src/baserow/ws/tasks.py | 2 - .../baserow/config/test_celery_config.py | 331 +++++++++++++++++- .../baserow/core/chat_runs/test_runner.py | 24 +- .../baserow/core/telemetry/test_celery.py | 49 ++- .../tests/baserow/ws/test_ws_channel_layer.py | 38 ++ ..._emails_and_airtable_imports_time_out.json | 13 + dev.sh | 2 - docker-compose.dev.yml | 40 +-- docs/decisions/010-background-ai-chat-runs.md | 8 +- docs/decisions/016-agent-channels.md | 6 +- ...018-celery-threads-and-task-time-limits.md | 67 ++++ docs/development/background-chat-runs.md | 8 + .../running-the-dev-env-locally.md | 43 ++- .../running-the-dev-env-with-docker.md | 4 +- .../api/agent_public_chat/serializers.py | 11 +- .../baserow_enterprise/assistant/assistant.py | 47 +-- .../agent/test_public_chat.py | 9 +- .../assistant/runs/test_run_drain.py | 68 ++++ .../baserow_enterprise/locales/en.json | 3 +- .../pages/publicAgentChat.vue | 8 +- .../unit/enterprise/publicAgentChat.spec.js | 45 ++- .../unit/enterprise/utils/assistant.spec.js | 1 + justfile | 6 +- .../config/settings/settings.py | 11 +- .../src/baserow_premium/fields/job_types.py | 60 ++-- .../test_ai_parallel_execution.py | 67 ++++ web-frontend/modules/agent/locales/en.json | 2 +- 37 files changed, 1264 insertions(+), 210 deletions(-) create mode 100644 changelog/entries/unreleased/bug/6931_ai_replies_emails_and_airtable_imports_time_out.json create mode 100644 docs/decisions/018-celery-threads-and-task-time-limits.md diff --git a/backend/justfile b/backend/justfile index a5fc44a38f..d0e8f68615 100644 --- a/backend/justfile +++ b/backend/justfile @@ -600,11 +600,10 @@ run-celery-beat: _check-dev # Celery settings celery_log_level := env("CELERY_LOG_LEVEL", "INFO") # INFO default, override with CELERY_LOG_LEVEL=DEBUG -# Use 'solo' pool on macOS to avoid fork() issues causing SIGSEGV -# Options: solo (single-threaded), threads, prefork (default, problematic on macOS) -celery_pool := env("CELERY_POOL", "solo") +# 'custom' is baserow.config.celery:ThreadsPool; 'solo' runs one task at a time, handy for breakpoints +celery_pool := env("CELERY_POOL", "custom") -# Run all Celery workers and beat together for development +# Run one Celery worker for every queue, with beat inside it, for development [group('2 - development')] run-dev-celery: _check-dev #!/usr/bin/env bash @@ -612,54 +611,21 @@ run-dev-celery: _check-dev {{ _load_env }} LOG_FILE="${BASEROW_CELERY_LOG_FILE:-${BASEROW_LOCAL_DEV_PREFIX:-/tmp/baserow}-celery.log}" - - # ANSI color codes - COLOR_WORKER=$'\033[38;5;39m' # Blue for worker - COLOR_EXPORT=$'\033[38;5;208m' # Orange for export - COLOR_BEAT=$'\033[38;5;129m' # Purple for beat - COLOR_RESET=$'\033[0m' - - # Function to prefix output with colored process name and tee to log file - prefix_output() { - local prefix="$1" - local color="$2" - while IFS= read -r line; do - # Colored output to terminal, plain prefix to log file - echo "${color}[$prefix]${COLOR_RESET} $line" - echo "[$prefix] $line" >> "$LOG_FILE" - done - } + > "$LOG_FILE" cleanup() { - echo "" - echo "Stopping all Celery processes..." - kill $WORKER_PID $EXPORT_PID $BEAT_PID 2>/dev/null || true - wait $WORKER_PID $EXPORT_PID $BEAT_PID 2>/dev/null || true - echo "All Celery processes stopped." + kill $WORKER_PID 2>/dev/null || true + wait $WORKER_PID 2>/dev/null || true } trap cleanup EXIT INT TERM - # Clear log file on start - > "$LOG_FILE" - - echo "Starting Celery worker (celery,automation_workflow queues)..." - {{ uv_run }} celery -A baserow worker -Q celery,automation_workflow -n default-worker@%h -l {{ celery_log_level }} --pool {{ celery_pool }} 2>&1 | prefix_output "WORKER" "$COLOR_WORKER" & + echo "Starting Celery worker with beat on every queue (pool: {{ celery_pool }}). Logs: $LOG_FILE" + CELERY_CUSTOM_WORKER_POOL=baserow.config.celery:ThreadsPool {{ uv_run }} celery -A baserow worker \ + -Q celery,export,automation_workflow,chat_run -n default-worker@%h -l {{ celery_log_level }} \ + --pool {{ celery_pool }} -c 25 -B --scheduler redbeat.RedBeatScheduler \ + > >(tee -a "$LOG_FILE") 2>&1 & WORKER_PID=$! - - echo "Starting Celery export worker (export,chat_run queues)..." - {{ uv_run }} celery -A baserow worker -Q export,chat_run --disable-prefetch -n export-worker@%h -l {{ celery_log_level }} --pool {{ celery_pool }} 2>&1 | prefix_output "EXPORT" "$COLOR_EXPORT" & - EXPORT_PID=$! - - echo "Starting Celery beat with redbeat scheduler..." - {{ uv_run }} celery -A baserow beat -l {{ celery_log_level }} -S redbeat.RedBeatScheduler 2>&1 | prefix_output "BEAT" "$COLOR_BEAT" & - BEAT_PID=$! - - echo "" - echo "All Celery processes started (pool: {{ celery_pool }}). Press Ctrl+C to stop." - echo "Logs: $LOG_FILE" - echo "" - - wait + wait $WORKER_PID # Run any command in the venv with `uv run *args` [group('2 - development')] diff --git a/backend/src/baserow/config/celery.py b/backend/src/baserow/config/celery.py index 6972acac21..767191db33 100644 --- a/backend/src/baserow/config/celery.py +++ b/backend/src/baserow/config/celery.py @@ -1,8 +1,20 @@ import contextlib +import functools +import threading +import time +from typing import Any, Callable + +from django.db import OperationalError, connections from celery import Celery, signals +from celery.concurrency import thread +from celery.concurrency.base import apply_target +from celery.exceptions import SoftTimeLimitExceeded, TimeLimitExceeded +from loguru import logger +from opentelemetry import metrics from baserow.config.helpers import check_lazy_loaded_libraries +from baserow.core.psycopg import is_query_canceled_error, is_savepoint_sql from baserow.core.telemetry.tasks import BaserowTelemetryTask app = Celery("baserow") @@ -11,6 +23,294 @@ app.autodiscover_tasks() app.Task = BaserowTelemetryTask +# Like the prefork pool's timeout handler, a limit acts up to this late. +_TIME_LIMIT_CHECK_INTERVAL = 1.0 +# A task still running this long after its hard limit holds its thread for good. +_OVERDUE_AFTER_SECONDS = 60 + +task_time_limit_counter = metrics.get_meter("baserow.celery").create_counter( + name="baserow.celery.task.time_limit", + description="Time limits reached by Baserow Celery tasks in a threads pool", + unit="1", +) + + +class _TaskRun: + """ + A task running in a pool thread. Its time limits are raised by the task's own + next query, like a database error, and never from another thread: an exception + raised from outside can land after a lock is taken and before the code that + releases it, which would block every thread of the worker. + """ + + def __init__(self, task_name: str) -> None: + self._task_name = task_name + self._databases = connections.all(initialized_only=False) + self._lock = threading.Lock() + self._running = True + self._limits: list[tuple[float, Callable[[], None]]] = [] + self._reached_limit: SoftTimeLimitExceeded | TimeLimitExceeded | None = None + + def set_time_limits( + self, + soft_timeout: float | None, + timeout: float | None, + timeout_callback: Callable[[bool, float], None] | None, + ) -> None: + """ + :param soft_timeout: Seconds after which the task's next query raises + `SoftTimeLimitExceeded`. Ignored unless earlier than the hard limit. + :param timeout: Seconds after which the task's running query is cancelled + and it, or the next one, raises `TimeLimitExceeded`. A task that runs no + query isn't stopped, and is reported a while later instead. + :param timeout_callback: Celery's callback, which logs the soft limit. + """ + + def on_soft_timeout() -> None: + self._count("soft") + if timeout_callback: + timeout_callback(True, soft_timeout) + self._raise_at_next_query(SoftTimeLimitExceeded()) + + def on_timeout() -> None: + self._count("hard") + logger.error( + f"Hard time limit ({timeout}s) exceeded for {self._task_name}." + ) + self._raise_at_next_query(TimeLimitExceeded(timeout)) + self.cancel_queries() + + started = time.monotonic() + if soft_timeout and (not timeout or soft_timeout < timeout): + self._limits.append((started + soft_timeout, on_soft_timeout)) + if timeout: + self._limits.append((started + timeout, on_timeout)) + self._limits.append( + (started + timeout + _OVERDUE_AFTER_SECONDS, self._report_overdue) + ) + self._limits.sort(key=lambda limit: limit[0]) + + def check_time_limits(self, now: float) -> None: + """ + Acts on the limits reached by now, in order. Only the pool's watchdog thread + calls it. + """ + + with self._lock: + if not self._running: + return + while self._limits and self._limits[0][0] <= now: + _, act = self._limits.pop(0) + act() + + def call(self, target: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: + """ + Calls the task in its thread with the time limits raised at its queries, + and ends them as it returns, before Celery's callbacks run. + """ + + try: + with contextlib.ExitStack() as stack: + for database in self._databases: + stack.enter_context( + database.execute_wrapper(self._raise_reached_limit) + ) + return target(*args, **kwargs) + finally: + self.end() + + def _raise_reached_limit( + self, + execute: Callable[..., Any], + sql: Any, + params: Any, + many: bool, + context: dict[str, Any], + ) -> Any: + """ + A `connection.execute_wrapper` that raises a reached limit once, before the + query or instead of the error of the query the hard limit cancelled. + Savepoint queries are left alone, so an atomic block exits whole. + """ + + if not is_savepoint_sql(sql) and (limit := self._take_reached_limit()): + raise limit + try: + return execute(sql, params, many, context) + except OperationalError as exc: + if is_query_canceled_error(exc) and (limit := self._take_reached_limit()): + raise limit from exc + raise + + def _raise_at_next_query( + self, limit: SoftTimeLimitExceeded | TimeLimitExceeded + ) -> None: + with self._lock: + if self._running: + self._reached_limit = limit + + def _take_reached_limit( + self, + ) -> SoftTimeLimitExceeded | TimeLimitExceeded | None: + with self._lock: + limit, self._reached_limit = self._reached_limit, None + return limit + + def cancel_queries(self) -> None: + """ + Cancels the queries the task's thread is running, so the hard limit + reaches a task waiting for one. + """ + + with self._lock: + if not self._running: + return + for database in self._databases: + if database.connection is None: + continue + try: + database.connection.cancel() + except Exception as exc: + logger.warning( + f"Could not cancel the query of {self._task_name}: {exc}" + ) + + def _report_overdue(self) -> None: + self._count("overdue") + message = ( + f"Celery task {self._task_name} is still running " + f"{_OVERDUE_AFTER_SECONDS}s after its hard time limit" + ) + logger.warning(message) + # Imported here so that sentry_sdk stays unloaded while Sentry is off. + import sentry_sdk + + with sentry_sdk.new_scope() as scope: + scope.fingerprint = ["celery-task-overdue", self._task_name] + scope.set_tag("task_name", self._task_name) + sentry_sdk.capture_message(message, level="error") + + def _count(self, limit: str) -> None: + task_time_limit_counter.add(1, {"task_name": self._task_name, "limit": limit}) + + def end(self) -> None: + """ + Stops the time limits, and drops one that wasn't raised yet. + """ + + with self._lock: + self._running = False + self._reached_limit = None + + +class _TimeLimitWatchdog: + """ + One thread that checks the time limits of every running task of a pool, like + the prefork pool's timeout handler, so no task needs a timer thread of its own. + """ + + def __init__(self) -> None: + self._runs: set[_TaskRun] = set() + self._lock = threading.Lock() + self._stopped = threading.Event() + threading.Thread( + target=self._watch, name="time-limit-watchdog", daemon=True + ).start() + + def add(self, run: _TaskRun) -> None: + with self._lock: + self._runs.add(run) + + def remove(self, run: _TaskRun) -> None: + with self._lock: + self._runs.discard(run) + + def stop(self) -> None: + self._stopped.set() + + def _watch(self) -> None: + while not self._stopped.wait(_TIME_LIMIT_CHECK_INTERVAL): + with self._lock: + runs = list(self._runs) + now = time.monotonic() + for run in runs: + try: + run.check_time_limits(now) + except Exception as exc: + logger.opt(exception=exc).error("Could not check a time limit.") + + +class ThreadsPool(thread.TaskPool): + """ + Celery's threads pool, with the soft and hard time limits that Celery's own + threads pool ignores, raised at the task's queries. It also sends + ``worker_process_init`` like the solo pool does, so the per-process setup + (telemetry, lazy import checks) runs in the single worker process. Select it + with ``-P custom`` and + ``CELERY_CUSTOM_WORKER_POOL=baserow.config.celery:ThreadsPool``. + """ + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self._watchdog = _TimeLimitWatchdog() + signals.worker_process_init.send(sender=None) + + def on_stop(self) -> None: + # Stopped last, so the limits still reach the tasks it waits for. + super().on_stop() + self._watchdog.stop() + + def on_apply( + self, + target: Callable[..., Any], + args: tuple[Any, ...] | None = None, + kwargs: dict[str, Any] | None = None, + callback: Callable[..., Any] | None = None, + accept_callback: Callable[..., Any] | None = None, + soft_timeout: float | None = None, + timeout: float | None = None, + timeout_callback: Callable[[bool, float], None] | None = None, + **_: Any, + ) -> thread.ApplyResult: + future = self.executor.submit( + self._run_with_time_limits, + target, + args, + kwargs, + callback, + accept_callback, + soft_timeout or self.options.get("soft_timeout"), + timeout or self.options.get("timeout"), + timeout_callback, + ) + return thread.ApplyResult(future) + + def _run_with_time_limits( + self, + target: Callable[..., Any], + args: tuple[Any, ...] | None, + kwargs: dict[str, Any] | None, + callback: Callable[..., Any] | None, + accept_callback: Callable[..., Any] | None, + soft_timeout: float | None, + timeout: float | None, + timeout_callback: Callable[[bool, float], None] | None, + ) -> None: + # Celery passes the task name as the first argument of its trace function. + run = _TaskRun(args[0] if args else getattr(target, "__name__", "unknown")) + run.set_time_limits(soft_timeout, timeout, timeout_callback) + self._watchdog.add(run) + try: + apply_target( + functools.partial(run.call, target), + args, + kwargs, + callback, + accept_callback, + ) + finally: + self._watchdog.remove(run) + def clear_local(*args, **kwargs): """ diff --git a/backend/src/baserow/config/settings/base.py b/backend/src/baserow/config/settings/base.py index ce18b78e43..6c888db2cd 100644 --- a/backend/src/baserow/config/settings/base.py +++ b/backend/src/baserow/config/settings/base.py @@ -1534,6 +1534,8 @@ if os.getenv("EMAIL_SMTP", ""): EMAIL_SSL_CERTFILE = os.getenv("EMAIL_SMTP_SSL_CERTFILE_PATH", None) EMAIL_SSL_KEYFILE = os.getenv("EMAIL_SMTP_SSL_KEYFILE_PATH", None) + # A silent SMTP server would block a threads-pool worker forever. + EMAIL_TIMEOUT = 60 else: CELERY_EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" diff --git a/backend/src/baserow/contrib/database/airtable/constants.py b/backend/src/baserow/contrib/database/airtable/constants.py index 0f02084b97..de618c1602 100644 --- a/backend/src/baserow/contrib/database/airtable/constants.py +++ b/backend/src/baserow/contrib/database/airtable/constants.py @@ -113,3 +113,6 @@ AIRTABLE_GALLERY_VIEW_COVER_CROP_TYPE = "crop" AIRTABLE_DOWNLOAD_FILE_TYPE_FETCH = "fetch" AIRTABLE_DOWNLOAD_FILE_TYPE_ATTACHMENT_ENDPOINT = "attachment_endpoint" + +# Airtable can be slow to respond. Bounds each read, not a whole download. +AIRTABLE_REQUEST_TIMEOUT_SECONDS = 3 * 60 diff --git a/backend/src/baserow/contrib/database/airtable/handler.py b/backend/src/baserow/contrib/database/airtable/handler.py index 90491c2057..01cf5d4e7b 100644 --- a/backend/src/baserow/contrib/database/airtable/handler.py +++ b/backend/src/baserow/contrib/database/airtable/handler.py @@ -24,6 +24,7 @@ from baserow.contrib.database.airtable.constants import ( AIRTABLE_EXPORT_JOB_CONVERTING, AIRTABLE_EXPORT_JOB_DOWNLOADING_BASE, AIRTABLE_EXPORT_JOB_DOWNLOADING_FILES, + AIRTABLE_REQUEST_TIMEOUT_SECONDS, AIRTABLE_SHARE_TYPE_BASE, AIRTABLE_SHARE_TYPE_VIEW, ) @@ -115,7 +116,11 @@ def download_airtable_file( try: if download_file.type == AIRTABLE_DOWNLOAD_FILE_TYPE_FETCH: - response = requests.get(download_file.url, headers=headers) # noqa: S113 + response = requests.get( + download_file.url, + headers=headers, + timeout=AIRTABLE_REQUEST_TIMEOUT_SECONDS, + ) elif download_file.type == AIRTABLE_DOWNLOAD_FILE_TYPE_ATTACHMENT_ENDPOINT: response = AirtableHandler.fetch_attachment( row_id=download_file.row_id, @@ -244,11 +249,12 @@ class AirtableHandler: """ url = f"{AIRTABLE_BASE_URL}/{share_id}" - response = requests.get( # noqa: S113 + response = requests.get( url, headers=BASE_HEADERS, cookies=config.get_session_cookies(), allow_redirects=False, + timeout=AIRTABLE_REQUEST_TIMEOUT_SECONDS, ) if response.status_code == 302 and response.headers.get( @@ -347,7 +353,7 @@ class AirtableHandler: "x-user-locale": "en", **headers, }, - timeout=3 * 60, # it can take quite a while for Airtable to respond. + timeout=AIRTABLE_REQUEST_TIMEOUT_SECONDS, **kwargs, ) # nosec diff --git a/backend/src/baserow/contrib/database/fields/tasks.py b/backend/src/baserow/contrib/database/fields/tasks.py index 8f951bbc08..d228a3b1d7 100644 --- a/backend/src/baserow/contrib/database/fields/tasks.py +++ b/backend/src/baserow/contrib/database/fields/tasks.py @@ -25,7 +25,11 @@ from baserow.contrib.database.table.models import RichTextFieldMention from baserow.contrib.database.views.handler import ViewSubscriptionHandler from baserow.contrib.database.views.models import View, ViewSubscription from baserow.core.models import Template, Workspace -from baserow.core.psycopg import is_query_canceled_error, tighten_statement_timeout +from baserow.core.psycopg import ( + is_query_canceled_error, + is_savepoint_sql, + tighten_statement_timeout, +) from baserow.core.telemetry.utils import add_baserow_trace_attrs, baserow_trace tracer = trace.get_tracer(__name__) @@ -58,10 +62,6 @@ RUN_LOCK_TTL = BATCH_UPDATE_HARD_TIME_LIMIT + 60 # them by this deadline instead. BATCH_UPDATE_DEADLINE_MARGIN_SECONDS = 10 -# Django runs these to end a nested atomic block. They must run even after the -# deadline or a failed query, or the transaction can't be cleaned up. -_SAVEPOINT_SQL_PREFIXES = ("SAVEPOINT", "RELEASE SAVEPOINT", "ROLLBACK TO SAVEPOINT") - class PeriodicFieldUpdateTimeBudgetExceeded(SoftTimeLimitExceeded): """ @@ -93,11 +93,7 @@ def _statement_deadline(deadline: float): def wrapper(execute, sql, params, many, context): db = context["connection"] - if ( - not db.in_atomic_block - or db.needs_rollback - or (isinstance(sql, str) and sql.startswith(_SAVEPOINT_SQL_PREFIXES)) - ): + if not db.in_atomic_block or db.needs_rollback or is_savepoint_sql(sql): return execute(sql, params, many, context) time_left_ms = _ensure_time_left(deadline) diff --git a/backend/src/baserow/core/chat_runs/constants.py b/backend/src/baserow/core/chat_runs/constants.py index 2f05e353f6..7508971f4b 100644 --- a/backend/src/baserow/core/chat_runs/constants.py +++ b/backend/src/baserow/core/chat_runs/constants.py @@ -55,8 +55,10 @@ FLUSH_INTERVAL_SECONDS = 0.25 LEASE_RENEW_INTERVAL_SECONDS = 2.0 LEASE_DURATION = timedelta(seconds=60) RUN_DEADLINE_SECONDS = 900 -# Room to drain tools and save the outcome after the deadline stops the run. -RUN_TIME_LIMIT_SECONDS = RUN_DEADLINE_SECONDS + 120 +# Grace for started tools after the worker observes Stop or reaches its deadline. +RUN_DRAIN_SECONDS = 60 +# Room to save the outcome after the drain. +RUN_TIME_LIMIT_SECONDS = RUN_DEADLINE_SECONDS + RUN_DRAIN_SECONDS + 60 # Bounds the channel layer send that tells followers a run changed. PUSH_TIMEOUT_SECONDS = 2.0 diff --git a/backend/src/baserow/core/chat_runs/runner.py b/backend/src/baserow/core/chat_runs/runner.py index 08b31c5305..f6713e0c3e 100644 --- a/backend/src/baserow/core/chat_runs/runner.py +++ b/backend/src/baserow/core/chat_runs/runner.py @@ -1,5 +1,4 @@ import asyncio -from contextlib import suppress from django.db import transaction @@ -12,6 +11,7 @@ from baserow.core.tools.errors import describe_failure from .buffer import close_buffer_redis from .constants import ( RUN_DEADLINE_SECONDS, + RUN_DRAIN_SECONDS, ChatRunErrorCode, ChatRunEventKind, ChatRunStopReason, @@ -46,9 +46,23 @@ async def run_chat_run(run: ChatRun, run_type: ChatRunType) -> None: deadline = asyncio.get_running_loop().call_later( RUN_DEADLINE_SECONDS, journal.request_stop, ChatRunStopReason.TIMEOUT ) + execution = asyncio.create_task(run_type.execute(run, journal)) + stop = asyncio.create_task(journal.wait_for_stop()) try: try: - outcome = await run_type.execute(run, journal) + await asyncio.wait((execution, stop), return_when=asyncio.FIRST_COMPLETED) + if not execution.done(): + await asyncio.wait((execution,), timeout=RUN_DRAIN_SECONDS) + if execution.done(): + outcome = execution.result() + else: + logger.warning("Chat run {} exceeded its stop grace period", run.id) + if journal.stop_reason == ChatRunStopReason.CANCELLED: + outcome = ChatRunOutcome(ChatRunStatus.CANCELLED) + else: + outcome = ChatRunOutcome( + ChatRunStatus.FAILED, ChatRunErrorCode.TIMEOUT + ) except Exception as exc: logger.error("Chat run {} failed ({})", run.id, describe_failure(exc)) outcome = ChatRunOutcome(ChatRunStatus.FAILED, ChatRunErrorCode.FAILED) @@ -62,12 +76,14 @@ async def run_chat_run(run: ChatRun, run_type: ChatRunType) -> None: await journal.publish_finished(snapshot) finally: deadline.cancel() + execution.cancel() + stop.cancel() for task in background: task.cancel() - for task in background: - with suppress(asyncio.CancelledError): - await task + await asyncio.gather(*background, stop, return_exceptions=True) await close_buffer_redis() + # Prefork can enforce its hard limit only while this Celery task is active. + await asyncio.gather(execution, return_exceptions=True) @with_usable_db_connection diff --git a/backend/src/baserow/core/psycopg.py b/backend/src/baserow/core/psycopg.py index 7a298a4ea9..7d03ac7bd4 100644 --- a/backend/src/baserow/core/psycopg.py +++ b/backend/src/baserow/core/psycopg.py @@ -1,3 +1,5 @@ +from typing import Any + from django.db import IntegrityError, OperationalError from django.db.backends.postgresql.psycopg_any import is_psycopg3 @@ -63,6 +65,18 @@ def tighten_statement_timeout(cursor, timeout_ms: int) -> None: cursor.execute(_TIGHTEN_STATEMENT_TIMEOUT_SQL, [timeout, timeout]) +_SAVEPOINT_SQL_PREFIXES = ("SAVEPOINT", "RELEASE SAVEPOINT", "ROLLBACK TO SAVEPOINT") + + +def is_savepoint_sql(sql: Any) -> bool: + """ + Whether the query is one of the savepoint statements Django runs to enter and + exit a nested atomic block. + """ + + return isinstance(sql, str) and sql.startswith(_SAVEPOINT_SQL_PREFIXES) + + def is_query_canceled_error(exc: Exception) -> bool: return isinstance(exc, OperationalError) and isinstance( exc.__cause__, errors.QueryCanceled diff --git a/backend/src/baserow/core/telemetry/celery.py b/backend/src/baserow/core/telemetry/celery.py index 9bb19fe419..7fc94384b5 100644 --- a/backend/src/baserow/core/telemetry/celery.py +++ b/backend/src/baserow/core/telemetry/celery.py @@ -1,4 +1,7 @@ +import threading +from collections.abc import Iterator, MutableMapping from timeit import default_timer +from typing import Any from django.conf import settings @@ -37,6 +40,54 @@ task_open_transaction_counter = meter.create_counter( ) +class _PerThreadDict(MutableMapping): + """ + A dict each thread sees on its own. The Celery instrumentation keys a task's + state by the task's id, but on a threads worker two tasks can share an id at + once: a task replaced with `self.replace()` keeps its id, and the replacement + can start before the original ends. All signals of a task run in its thread. + """ + + def __init__(self) -> None: + self._local = threading.local() + + def _dict(self) -> dict: + if not hasattr(self._local, "dict"): + self._local.dict = {} + return self._local.dict + + def __getitem__(self, key: Any) -> Any: + return self._dict()[key] + + def __setitem__(self, key: Any, value: Any) -> None: + self._dict()[key] = value + + def __delitem__(self, key: Any) -> None: + del self._dict()[key] + + def __iter__(self) -> Iterator: + return iter(self._dict()) + + def __len__(self) -> int: + return len(self._dict()) + + +_task_contexts_lock = threading.Lock() + + +def _keep_task_contexts_per_thread(task) -> None: + """ + Makes the upstream instrumentation store the spans of a task per thread, in the + dict it keeps on the task. + """ + + if task is None or isinstance(getattr(task, utils.CTX_KEY, None), _PerThreadDict): + return + with _task_contexts_lock: + if not isinstance(getattr(task, utils.CTX_KEY, None), _PerThreadDict): + setattr(task, utils.CTX_KEY, _PerThreadDict()) + + def _get_task_queue(task) -> str: request = task.request delivery_info = getattr(request, "delivery_info", None) or {} @@ -77,9 +128,19 @@ class BaserowCeleryInstrumentor(CeleryInstrumentor): _is_instrumented_by_opentelemetry = False def __init__(self): - self._baserow_task_started_at = {} + self._baserow_task_started_at = _PerThreadDict() + + @property + def task_id_to_start_time(self) -> MutableMapping: + return self._task_id_to_start_time + + @task_id_to_start_time.setter + def task_id_to_start_time(self, value: dict) -> None: + # The upstream instrumentation resets it with a plain dict. + self._task_id_to_start_time = _PerThreadDict() def _trace_before_publish(self, *args, **kwargs): + _keep_task_contexts_per_thread(utils.retrieve_task_from_sender(kwargs)) super()._trace_before_publish(*args, **kwargs) _inject_force_full_trace_baggage(kwargs.get("headers")) @@ -90,6 +151,7 @@ class BaserowCeleryInstrumentor(CeleryInstrumentor): if task is None or task_id is None: return + _keep_task_contexts_per_thread(task) self.update_task_duration_time(task_id) self._baserow_task_started_at[task_id] = default_timer() diff --git a/backend/src/baserow/ws/tasks.py b/backend/src/baserow/ws/tasks.py index c1ca793f26..74fb780552 100644 --- a/backend/src/baserow/ws/tasks.py +++ b/backend/src/baserow/ws/tasks.py @@ -243,8 +243,6 @@ async def send_messages_to_channel_group( await channel_layer.group_send( channel_group_message.channel_group_name, channel_group_message.message ) - if hasattr(channel_layer, "close_pools"): - await channel_layer.close_pools() @app.task(bind=True) diff --git a/backend/tests/baserow/config/test_celery_config.py b/backend/tests/baserow/config/test_celery_config.py index f2d0ff0f34..3aeefceb80 100644 --- a/backend/tests/baserow/config/test_celery_config.py +++ b/backend/tests/baserow/config/test_celery_config.py @@ -1,13 +1,23 @@ +import queue +import threading +import time from types import SimpleNamespace -from unittest.mock import patch +from unittest.mock import Mock, patch from django.contrib.auth import get_user_model from django.db import connection, transaction import pytest -from celery import signals +from celery import concurrency, signals +from celery.exceptions import SoftTimeLimitExceeded, TimeLimitExceeded -from baserow.config.celery import app, recover_from_open_db_transaction +from baserow.config.celery import ( + ThreadsPool, + _TaskRun, + app, + recover_from_open_db_transaction, +) +from baserow.core.models import Workspace @pytest.mark.django_db @@ -196,3 +206,318 @@ def test_eager_task_keeps_callers_transaction(mock_capture_message): assert connection.in_atomic_block mock_capture_message.assert_not_called() + + +def test_threads_pool_runs_worker_process_init_handlers(): + received = [] + + def handler(**kwargs): + received.append(kwargs) + + signals.worker_process_init.connect(handler) + try: + pool_cls = concurrency.get_implementation("baserow.config.celery:ThreadsPool") + pool = pool_cls(limit=1) + finally: + signals.worker_process_init.disconnect(handler) + + assert len(received) == 1 + pool.executor.shutdown() + + +@pytest.fixture +def threads_pool(monkeypatch): + monkeypatch.setattr("baserow.config.celery._TIME_LIMIT_CHECK_INTERVAL", 0.01) + pool = ThreadsPool(limit=1) + yield pool + pool.on_stop() + + +def _apply( + pool: ThreadsPool, + fn, + timeouts: list | None = None, + callback=None, + **limits, +) -> queue.Queue: + results = queue.Queue() + timeouts = [] if timeouts is None else timeouts + + def put_result(result): + if callback: + callback() + results.put(result) + + pool.apply_async( + _closing_connections(fn), + callback=put_result, + timeout_callback=lambda soft, timeout: timeouts.append((soft, timeout)), + **limits, + ) + return results + + +def _closing_connections(fn): + def run(): + try: + return fn() + finally: + connection.close() + + return run + + +def _query(): + with connection.cursor() as cursor: + cursor.execute("SELECT 1") + + +def _query_until_the_soft_limit_then_clean_up(): + deadline = time.monotonic() + 3 + try: + while time.monotonic() < deadline: + _query() + time.sleep(0.01) + except SoftTimeLimitExceeded: + _query() + return "soft" + return "no soft limit" + + +def _query_ignoring_the_soft_limit_until_the_hard_limit(): + started = time.monotonic() + while time.monotonic() - started < 3: + try: + _query() + time.sleep(0.01) + except SoftTimeLimitExceeded: + continue + except TimeLimitExceeded: + return "hard" + return "no hard limit" + + +def _query_for(seconds: float): + def run(): + started = time.monotonic() + while time.monotonic() - started < seconds: + _query() + time.sleep(0.01) + return "done" + + return run + + +def _query_ignoring_every_limit_for(seconds: float): + def run(): + started = time.monotonic() + while time.monotonic() - started < seconds: + try: + _query() + time.sleep(0.01) + except (SoftTimeLimitExceeded, TimeLimitExceeded): + continue + return "done" + + return run + + +@pytest.mark.django_db(transaction=True) +def test_threads_pool_raises_the_soft_time_limit_once_at_the_next_query(threads_pool): + timeouts = [] + + results = _apply( + threads_pool, + _query_until_the_soft_limit_then_clean_up, + timeouts, + soft_timeout=0.1, + timeout=5, + ) + + assert results.get(timeout=5) == "soft" + assert timeouts == [(True, 0.1)] + + +@pytest.mark.django_db(transaction=True) +@pytest.mark.parametrize("soft_timeout", [0.1, 0.2, 0.4]) +def test_threads_pool_raises_the_hard_time_limit_whatever_the_soft_one( + threads_pool, soft_timeout +): + results = _apply( + threads_pool, + _query_ignoring_the_soft_limit_until_the_hard_limit, + soft_timeout=soft_timeout, + timeout=0.2, + ) + + assert results.get(timeout=5) == "hard" + + +@pytest.mark.django_db(transaction=True) +@pytest.mark.parametrize( + "defaults,task,expected", + [ + ({"soft_timeout": 0.1}, _query_until_the_soft_limit_then_clean_up, "soft"), + ({"timeout": 0.1}, _query_ignoring_the_soft_limit_until_the_hard_limit, "hard"), + ], +) +def test_threads_pool_applies_the_worker_default_time_limits( + monkeypatch, defaults, task, expected +): + monkeypatch.setattr("baserow.config.celery._TIME_LIMIT_CHECK_INTERVAL", 0.01) + pool = ThreadsPool(limit=1, **defaults) + try: + results = _apply(pool, task) + + assert results.get(timeout=5) == expected + finally: + pool.on_stop() + + +@pytest.mark.django_db(transaction=True) +def test_threads_pool_cancels_the_query_running_at_the_hard_limit(threads_pool): + def run_long_query(): + started = time.monotonic() + try: + with connection.cursor() as cursor: + cursor.execute("SELECT pg_sleep(30)") + except TimeLimitExceeded: + return time.monotonic() - started + + results = _apply(threads_pool, run_long_query, soft_timeout=0.1, timeout=0.2) + + assert results.get(timeout=10) < 5 + + +def test_threads_pool_reports_a_query_free_task_without_interrupting_it( + threads_pool, monkeypatch +): + reported = threading.Event() + monkeypatch.setattr("baserow.config.celery._OVERDUE_AFTER_SECONDS", 0.01) + monkeypatch.setattr("sentry_sdk.capture_message", lambda *a, **kw: reported.set()) + + results = _apply( + threads_pool, lambda: reported.wait(3), soft_timeout=0.1, timeout=0.2 + ) + + assert results.get(timeout=5) is True + + +@pytest.mark.django_db(transaction=True) +def test_pending_soft_limit_allows_a_nested_transaction_to_roll_back(): + run = _TaskRun("nested_transaction") + run.set_time_limits(1, None, None) + + def task(): + with transaction.atomic(): + Workspace.objects.create(name="kept") + try: + with transaction.atomic(): + Workspace.objects.create(name="rolled back") + run.check_time_limits(float("inf")) + raise ValueError("abort the inner transaction") + except (ValueError, SoftTimeLimitExceeded): + pass + + run.call(task) + + names = Workspace.objects.filter(name__in=["kept", "rolled back"]).values_list( + "name", flat=True + ) + assert list(names) == ["kept"] + + +@pytest.mark.django_db(transaction=True) +def test_threads_pool_time_limits_end_before_celerys_callback( + threads_pool, limits_reached +): + results = _apply( + threads_pool, + lambda: "done", + callback=_closing_connections(lambda: (time.sleep(0.3), _query())), + soft_timeout=0.1, + timeout=0.2, + ) + + assert results.get(timeout=5) == "done" + assert limits_reached() == ([], 0) + + +@pytest.mark.django_db(transaction=True) +def test_threads_pool_keeps_the_time_limits_while_it_stops(threads_pool): + results = _apply( + threads_pool, + _query_ignoring_the_soft_limit_until_the_hard_limit, + soft_timeout=0.1, + timeout=0.2, + ) + + threads_pool.on_stop() + + assert results.get(timeout=5) == "hard" + + +@pytest.fixture +def limits_reached(monkeypatch): + monkeypatch.setattr("baserow.config.celery._OVERDUE_AFTER_SECONDS", 0.1) + counter, capture_message = Mock(), Mock() + monkeypatch.setattr("baserow.config.celery.task_time_limit_counter", counter) + monkeypatch.setattr("sentry_sdk.capture_message", capture_message) + + def reached() -> tuple[list[str], int]: + limits = [call.args[1]["limit"] for call in counter.add.call_args_list] + return limits, capture_message.call_count + + return reached + + +@pytest.mark.django_db(transaction=True) +def test_threads_pool_reports_a_task_still_running_after_its_hard_limit( + threads_pool, limits_reached +): + results = _apply( + threads_pool, + _query_ignoring_every_limit_for(1), + soft_timeout=0.1, + timeout=0.2, + ) + + assert results.get(timeout=5) == "done" + assert limits_reached() == (["soft", "hard", "overdue"], 1) + + +@pytest.mark.django_db(transaction=True) +def test_threads_pool_reports_no_task_that_stops_at_its_hard_limit( + threads_pool, limits_reached +): + results = _apply( + threads_pool, + _query_ignoring_the_soft_limit_until_the_hard_limit, + soft_timeout=0.1, + timeout=0.2, + ) + + assert results.get(timeout=5) == "hard" + time.sleep(0.3) + assert limits_reached() == (["soft", "hard"], 0) + + +def test_threads_pool_time_limits_start_no_thread_per_task(threads_pool): + without_limits = _apply(threads_pool, threading.active_count) + with_limits = _apply( + threads_pool, threading.active_count, soft_timeout=10, timeout=20 + ) + + assert without_limits.get(timeout=5) == with_limits.get(timeout=5) + + +@pytest.mark.django_db(transaction=True) +def test_threads_pool_time_limits_of_a_finished_task_spare_the_next_one( + threads_pool, +): + first = _apply(threads_pool, lambda: "first", soft_timeout=0.1, timeout=0.2) + assert first.get(timeout=5) == "first" + + second = _apply(threads_pool, _query_for(0.5)) + + assert second.get(timeout=5) == "done" diff --git a/backend/tests/baserow/core/chat_runs/test_runner.py b/backend/tests/baserow/core/chat_runs/test_runner.py index 91fded708c..14cdfb7264 100644 --- a/backend/tests/baserow/core/chat_runs/test_runner.py +++ b/backend/tests/baserow/core/chat_runs/test_runner.py @@ -5,7 +5,7 @@ from django.db import OperationalError, connection import pytest from asgiref.sync import async_to_sync -from baserow.core.chat_runs.constants import ChatRunStopReason +from baserow.core.chat_runs.constants import ChatRunErrorCode, ChatRunStopReason from baserow.core.chat_runs.handler import ChatRunHandler from baserow.core.chat_runs.models import ChatRun, ChatRunStatus from baserow.core.chat_runs.runner import _finish, run_chat_run @@ -202,3 +202,25 @@ def test_the_deadline_asks_the_run_to_stop( fake_run_type.execute = execute async_to_sync(run_chat_run)(run, fake_run_type) assert reasons == [ChatRunStopReason.TIMEOUT] + + +def test_a_run_that_ignores_the_deadline_ends_as_timed_out( + create_run, fake_run_type, output_buffer, monkeypatch +): + run = create_run(claim=True) + monkeypatch.setattr("baserow.core.chat_runs.runner.RUN_DEADLINE_SECONDS", 0.01) + monkeypatch.setattr("baserow.core.chat_runs.runner.RUN_DRAIN_SECONDS", 0.05) + + async def execute(run, journal): + await asyncio.Event().wait() + + async def run_with_guard(): + await asyncio.wait_for(run_chat_run(run, fake_run_type), 5) + + fake_run_type.execute = execute + async_to_sync(run_with_guard)() + run.refresh_from_db() + assert (run.status, run.error_code) == ( + ChatRunStatus.FAILED, + ChatRunErrorCode.TIMEOUT, + ) diff --git a/backend/tests/baserow/core/telemetry/test_celery.py b/backend/tests/baserow/core/telemetry/test_celery.py index b55c213c10..482c0eddbe 100644 --- a/backend/tests/baserow/core/telemetry/test_celery.py +++ b/backend/tests/baserow/core/telemetry/test_celery.py @@ -1,3 +1,5 @@ +import logging +import threading from types import SimpleNamespace from unittest.mock import MagicMock, patch @@ -33,8 +35,8 @@ def _instrumentor_with_memory_exporter(provider=None): provider = provider or TracerProvider() provider.add_span_processor(SimpleSpanProcessor(exporter)) instrumentor = object.__new__(BaserowCeleryInstrumentor) + instrumentor.__init__() instrumentor._tracer = provider.get_tracer(__name__) - instrumentor._baserow_task_started_at = {} instrumentor.task_id_to_start_time = {} instrumentor.metrics = {"flower.task.runtime.seconds": MagicMock()} return instrumentor, provider, exporter @@ -226,3 +228,48 @@ def test_force_full_trace_is_added_to_published_task_baggage(): ) assert baggage.get_baggage("user.id", context=extracted_context) == "42" provider.shutdown() + + +def test_tasks_sharing_an_id_on_two_threads_keep_their_own_traces(caplog): + # A task replaced with `self.replace()` keeps its id, and on a threads worker + # the replacement can start before the original ends. + instrumentor, provider, exporter = _instrumentor_with_memory_exporter() + task = _fake_task() + first_started, second_started, first_ended = (threading.Event() for _ in "abc") + left_current = {} + + def run(name, start_after, started, end_after, ended): + start_after.wait(5) + instrumentor._trace_prerun(task=task, task_id="task-1") + started.set() + end_after.wait(5) + instrumentor._trace_postrun(task=task, task_id="task-1", state="SUCCESS") + left_current[name] = trace.get_current_span() + ended.set() + + go, done = threading.Event(), threading.Event() + go.set() + threads = [ + threading.Thread( + target=run, args=("first", go, first_started, second_started, first_ended) + ), + threading.Thread( + target=run, + args=("second", first_started, second_started, first_ended, done), + ), + ] + with ( + caplog.at_level(logging.WARNING), + patch("baserow.core.telemetry.celery.task_duration_histogram"), + ): + for thread in threads: + thread.start() + for thread in threads: + thread.join(10) + + assert len({span.context.span_id for span in exporter.get_finished_spans()}) == 2 + assert left_current == {"first": trace.INVALID_SPAN, "second": trace.INVALID_SPAN} + assert [ + r.getMessage() for r in caplog.records if r.levelno >= logging.WARNING + ] == [] + provider.shutdown() diff --git a/backend/tests/baserow/ws/test_ws_channel_layer.py b/backend/tests/baserow/ws/test_ws_channel_layer.py index 1ba7311b1d..47dfcb4438 100644 --- a/backend/tests/baserow/ws/test_ws_channel_layer.py +++ b/backend/tests/baserow/ws/test_ws_channel_layer.py @@ -1,4 +1,6 @@ import asyncio +import queue +import threading import time from contextlib import asynccontextmanager from unittest.mock import patch @@ -7,7 +9,11 @@ from django.test.utils import override_settings import msgpack import pytest +from asgiref.sync import async_to_sync from channels_redis.core import RedisChannelLayer +from fakeredis import FakeServer +from fakeredis.aioredis import FakeAsyncConnection +from redis.asyncio import ConnectionPool from baserow.ws.channel_layer import ( COMPRESSED_MSGPACK_SERIALIZER_FORMAT, @@ -15,6 +21,8 @@ from baserow.ws.channel_layer import ( CompressedMsgPackSerializer, RetryingRedisChannelLayer, ) +from baserow.ws.tasks import send_messages_to_channel_group +from baserow.ws.types import ChannelGroupMessage LARGE_MESSAGE = { "type": "broadcast_to_group", @@ -246,3 +254,33 @@ async def test_a_group_discarded_during_a_renewal_is_not_added_again( await renewal assert channel_layer_redis.zscore(f"asgi:group:{last_group}", CHANNEL) is None + + +def test_messages_sent_from_many_threads_at_once_all_arrive(): + # Each thread gets its own event loop and its own pool, like in a threads + # Celery worker, where closing every loop's pools broke the other threads. + server = FakeServer() + layer = RetryingRedisChannelLayer(hosts=[{"address": "redis://fake"}]) + message = ChannelGroupMessage("users", {"type": "test", "record": False}) + outcomes = queue.Queue() + + def send_many() -> None: + try: + for _ in range(25): + async_to_sync(send_messages_to_channel_group)(layer, message) + outcomes.put("ok") + except Exception as exc: + outcomes.put(repr(exc)) + + with patch.object( + RetryingRedisChannelLayer, + "create_pool", + lambda self, index: ConnectionPool( + connection_class=FakeAsyncConnection, server=server + ), + ): + for _ in range(8): + threading.Thread(target=send_many, daemon=True).start() + results = [outcomes.get(timeout=30) for _ in range(8)] + + assert results == ["ok"] * 8 diff --git a/changelog/entries/unreleased/bug/6931_ai_replies_emails_and_airtable_imports_time_out.json b/changelog/entries/unreleased/bug/6931_ai_replies_emails_and_airtable_imports_time_out.json new file mode 100644 index 0000000000..b7be953a5a --- /dev/null +++ b/changelog/entries/unreleased/bug/6931_ai_replies_emails_and_airtable_imports_time_out.json @@ -0,0 +1,13 @@ +{ + "type": "bug", + "message": "AI replies, emails and Airtable imports time out", + "issue_origin": "github", + "issue_number": 6931, + "domain": "core", + "bullet_points": [ + "AI replies have 60 seconds to finish after their 15-minute deadline. A tool already running may still finish after the chat is available again.", + "Notification, invite and password reset emails time out after 60 seconds", + "Airtable requests time out after 3 minutes" + ], + "created_at": "2026-11-30" +} diff --git a/dev.sh b/dev.sh index 46f690ff98..557550bb13 100755 --- a/dev.sh +++ b/dev.sh @@ -488,8 +488,6 @@ if [ "$dont_attach" != true ] && [ "$up" = true ] ; then launch_tab_and_attach "backend" "backend" launch_tab_and_attach "web frontend" "web-frontend" launch_tab_and_attach "celery" "celery" - launch_tab_and_attach "export worker" "celery-export-worker" - launch_tab_and_attach "beat worker" "celery-beat-worker" if [ "$dev" = true ] ; then launch_tab_and_exec "web frontend lint" \ diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index ffb8f8a8c6..04cbdaf3d7 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -127,8 +127,9 @@ services: celery: image: baserow_backend:dev user: "${UID}:${GID}" - command: "watch-py celery-worker" + command: "watch-py celery-worker -Q celery,export,automation_workflow,chat_run -P custom -c 25 -B --scheduler redbeat.RedBeatScheduler" environment: + - CELERY_CUSTOM_WORKER_POOL=baserow.config.celery:ThreadsPool - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 - OTEL_TRACES_SAMPLER=always_on - BASEROW_DANGEROUS_SILKY_ANALYZE_QUERIES @@ -146,43 +147,12 @@ services: depends_on: - otel-collector + # The celery service runs every queue and beat in dev. celery-export-worker: - image: baserow_backend:dev - user: "${UID}:${GID}" - command: "watch-py celery-exportworker" - environment: - - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 - - OTEL_TRACES_SAMPLER=always_on - - BASEROW_DANGEROUS_SILKY_ANALYZE_QUERIES - - BASEROW_ASSISTANT_PHOENIX_URL=${BASEROW_ASSISTANT_PHOENIX_URL:-} - - BASEROW_ASSISTANT_PHOENIX_API_KEY=${BASEROW_ASSISTANT_PHOENIX_API_KEY:-} - volumes: - - ./docs:/baserow/docs - - ./backend:/baserow/backend - - ./premium/backend/:/baserow/premium/backend - - ./enterprise/backend/:/baserow/enterprise/backend - - ./deploy/plugins:/baserow/plugins - # Open stdin and tty so when attaching key input works as expected. - stdin_open: true - tty: true - depends_on: - - otel-collector + profiles: ["disabled"] celery-beat-worker: - image: baserow_backend:dev - user: "${UID}:${GID}" - command: "watch-py celery-beat" - environment: - - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 - - OTEL_TRACES_SAMPLER=always_on - volumes: - - ./backend:/baserow/backend - - ./premium/backend/:/baserow/premium/backend - - ./enterprise/backend/:/baserow/enterprise/backend - - ./deploy/plugins:/baserow/plugins - # Open stdin and tty so when attaching key input works as expected. - stdin_open: true - tty: true + profiles: ["disabled"] celery-flower: image: baserow_backend:dev diff --git a/docs/decisions/010-background-ai-chat-runs.md b/docs/decisions/010-background-ai-chat-runs.md index a66a033536..97c19becd9 100644 --- a/docs/decisions/010-background-ai-chat-runs.md +++ b/docs/decisions/010-background-ai-chat-runs.md @@ -56,8 +56,12 @@ Enforce one active run per conversation, per-user limits, execution deadlines, a not-started timeout for queued runs no worker picks up, atomic claims and terminal transitions. The run engine never restarts failed or interrupted runs or replays their tool effects. Provider-request and validation retries within a -live run remain product behavior. Stop is run-scoped and finishes after active -tools drain; committed changes remain. +live run remain product behavior. Stop is run-scoped. When the worker observes +Stop or reaches the run's deadline, whichever comes first, it gives active tools +up to 60 seconds to finish. If that grace period expires, the runner records the +run as stopped or timed out and the chat can accept the next message. The Celery +task keeps its worker slot while a previously started tool finishes. That tool +can still make changes after the chat reopens. Committed changes remain. ### 2. Stream and replay over HTTP diff --git a/docs/decisions/016-agent-channels.md b/docs/decisions/016-agent-channels.md index f1bded4e8e..906e740a60 100644 --- a/docs/decisions/016-agent-channels.md +++ b/docs/decisions/016-agent-channels.md @@ -103,8 +103,10 @@ the visitor's and the agent's messages. ### 4. A visitor sees text only -The visitor API exposes a message's id, role, content, status and time. Steps, tool -calls, approvals, error codes, senders and other conversations stay private. +The visitor API exposes a message's id, role, content, status and time. A +`timed_out` flag lets the page warn that repeating a request could repeat an +action. Steps, tool calls, approvals, error codes, senders and other +conversations stay private. The answer streams only when the reply can't call a tool. What a reply writes before it calls a tool isn't its answer, and can't be told from the answer while it arrives, diff --git a/docs/decisions/018-celery-threads-and-task-time-limits.md b/docs/decisions/018-celery-threads-and-task-time-limits.md new file mode 100644 index 0000000000..3440141725 --- /dev/null +++ b/docs/decisions/018-celery-threads-and-task-time-limits.md @@ -0,0 +1,67 @@ +# ADR 018: Use Celery threads for I/O concurrency with cooperative time limits + +| | | +| ------ | ---------------------------------------------- | +| Status | Proposed | +| Date | 2026-12-02 | +| Issue | https://github.com/baserow/baserow/issues/6931 | +| Author | Davide Silvestri (@silvestrid) | + +## Summary + +Run the development queues and beat in one threaded Celery worker. Offer threads +as a production opt-in in the next rollout step. Prefork remains the production +default and the appropriate choice when a task requires forced termination. + +## Context + +With prefork, each concurrent task needs a child process with Django loaded. +Keeping just one slot saves memory, but a long export or model call can occupy +that worker while other tasks wait. On the laptop measured for this change, +the prefork dev setup used 1.3–3.6 GB. The single threaded worker used +0.3–0.6 GB. Threads can share that memory and make progress while another task +waits for I/O. [Development measurements](https://github.com/baserow/baserow/pull/6926) + +## Decision + +Prefork can terminate and replace one child at the hard limit. Python has no +safe equivalent for a running thread. Injecting an exception as a thread +acquires a lock can leave the lock held. Restarting the process would interrupt +every task in the worker. + +On threads, Baserow delivers a pending time limit at the task thread's next +ordinary Django query. At the hard limit it also asks PostgreSQL to cancel a +query already running on that thread's connections. Code waiting elsewhere can +continue past either limit. The worker reports a task still running 60 seconds +after its hard limit and keeps serving work on its remaining slots. + +### Contract for task authors + +- **Bound blocking calls where they happen.** Give network and other blocking + I/O finite timeouts. For multiple calls or retries, carry a deadline through + the operation so each attempt uses the time remaining. A single Redis send + can do useful work without ever reaching a SQL query. +- **Give long loops a place to stop.** Check the deadline between bounded + batches, before starting more work. Let time-limit exceptions unwind the + current operation and release locks and connections. A broad exception + handler that retries the same work can keep the worker slot occupied. +- **Account for work handed off.** Cancelling a wait can leave a tool thread + running or a remote request already accepted. A timeout alone does not make + retrying a write safe. For example, a chat accepts another message after its + grace period, and warns that an earlier tool may still finish a write. + [Background chat runs](../development/background-chat-runs.md) + +## Consequences + +A cooperative task can stop at a safe boundary. If a library blocks indefinitely +or ignores cancellation, the slot stays occupied until the task exits. Use the +overdue metric and Sentry report to identify that task and fix the blocking +operation. Workloads that need their local execution stopped independently +belong on prefork. Neither pool can recall an external request or undo a +committed write. + +Threads also share CPU and the worker's process memory limit. A process crash +loses all active tasks in that worker, and increasing concurrency can open more +database connections. Before changing the production default, use the opt-in +rollout to evaluate overdue tasks, worker memory, connection use and queue wait +times. [Rollout plan](https://github.com/baserow/baserow/issues/6931) diff --git a/docs/development/background-chat-runs.md b/docs/development/background-chat-runs.md index 4e98f7170a..e78af7a659 100644 --- a/docs/development/background-chat-runs.md +++ b/docs/development/background-chat-runs.md @@ -96,6 +96,14 @@ Stop is a separate HTTP request: `POST /api/chat-runs//cancel/` calls `ChatRunHandler.request_cancel`. A queued run ends immediately. A running run gets a cancellation flag, which the worker observes through `keep_alive`. +At 15 minutes the runner asks the adapter to stop starting work. A user can also +press Stop. From the first stop signal, tools have 60 seconds to finish. If that +grace expires, the runner saves the original reason (stopped or timed out) and +the chat accepts another message. The Celery task keeps its slot while Kuma +drains tools it already started. Prefork can still kill the child at the task's +17-minute hard limit. On threads a tool can keep running, so its blocking calls +need their own timeouts. + Some adapter hooks have more than one caller context. `on_run_not_started` can run in an HTTP request that cancels a queued run or fails to enqueue it, or in the `sweep_chat_runs` maintenance task. That task also calls `on_run_lost` for diff --git a/docs/development/running-the-dev-env-locally.md b/docs/development/running-the-dev-env-locally.md index 0d039d328f..b685484892 100644 --- a/docs/development/running-the-dev-env-locally.md +++ b/docs/development/running-the-dev-env-locally.md @@ -105,14 +105,14 @@ The `just dev up` command orchestrates: 1. **Docker services**: PostgreSQL, Redis, Mailhog, OpenTelemetry collector 2. **Database migrations**: Applied automatically 3. **Backend server**: Django development server on port 8000 -4. **Celery workers**: Background task processing (main, export, beat scheduler) +4. **Celery worker**: One worker for every queue, with the beat scheduler inside it 5. **Frontend server**: Nuxt development server on port 3000 ``` just dev up ├── Docker: db, redis, mailhog, otel-collector ├── Backend: Django dev server (port 8000) -├── Celery: main worker + export worker + beat scheduler +├── Celery: one worker for every queue, with beat └── Frontend: Nuxt dev server (port 3000) ``` @@ -234,7 +234,7 @@ cd backend just run-dev-server ``` -### 4. Run Celery Workers (separate terminal) +### 4. Run the Celery Worker (separate terminal) ```bash cd backend @@ -408,13 +408,42 @@ kill -9 $(lsof -i :8000 | awk 'NR==2 {print $2}') kill -9 $(lsof -i :3000 | awk 'NR==2 {print $2}') ``` -### Celery Crashes on macOS +### Celery Pool -The justfile defaults to `solo` pool on macOS to avoid fork() issues: +For the rollout decision and the contract for new tasks, see +[ADR 018](../decisions/018-celery-threads-and-task-time-limits.md). + +The dev worker runs concurrent tasks in one Python process. Threads share the +memory used to load Django and let other tasks run while one waits for I/O. +They also avoid fork crashes on macOS. With `prefork`, each task slot has its +own child process. Celery can kill and replace that child at the hard time limit. +Python cannot safely kill one thread. An exception injected while the thread +holds a lock can leave other tasks blocked, and killing the process interrupts +every task in it. + +On Baserow's threads pool, a soft limit raises `SoftTimeLimitExceeded` at the +task thread's next ordinary Django query. At the hard limit, the watchdog also +asks PostgreSQL to cancel any query running on that thread's connections. The +cancelled query or the next ordinary query raises `TimeLimitExceeded`. The +exception is delivered once so cleanup can still use the database. A task +blocked on a socket, computing in Python, or catching the exception can keep +its slot past the deadline. After 60 more seconds the watchdog records +`overdue` in `baserow.celery.task.time_limit` and reports the task to Sentry +when configured. The slot becomes available when the task exits. + +Give blocking calls their own timeouts and check a deadline between batches +of long-running work. A WebSocket disconnect task can do its entire job in +Redis, so its socket timeout matters even if it never queries PostgreSQL. +Threads share CPU and the process memory limit too. CPU-heavy Python work +competes with other tasks, and a process crash loses every task running in +that worker. Use prefork when a task requires forced termination or process +isolation. With either pool, a timeout can leave committed writes and external +requests in effect. + +Use `solo` to run one task at a time, for example with breakpoints: ```bash -# Force a different pool if needed -CELERY_POOL=threads just b run-dev-celery +CELERY_POOL=solo just b run-dev-celery ``` ### Frontend Build Errors diff --git a/docs/development/running-the-dev-env-with-docker.md b/docs/development/running-the-dev-env-with-docker.md index 704e8e8ca1..51b15c119b 100644 --- a/docs/development/running-the-dev-env-with-docker.md +++ b/docs/development/running-the-dev-env-with-docker.md @@ -55,9 +55,7 @@ The Docker dev environment runs these services: |---------|-------------|------| | `web-frontend` | Nuxt.js frontend with hot reload | 3000 | | `backend` | Django API server with hot reload | 8000 | -| `celery` | Background task worker | - | -| `celery-export-worker` | Export-specific worker | - | -| `celery-beat-worker` | Scheduled task runner | - | +| `celery` | Background task worker for every queue, with embedded beat. See [threads pool and time limits](running-the-dev-env-locally.md#celery-pool). | - | | `db` | PostgreSQL database | 5432 | | `redis` | Redis cache and message broker | 6379 | | `caddy` | Reverse proxy for media files | 4000 | diff --git a/enterprise/backend/src/baserow_enterprise/api/agent_public_chat/serializers.py b/enterprise/backend/src/baserow_enterprise/api/agent_public_chat/serializers.py index 583fefe432..4bd750df2a 100644 --- a/enterprise/backend/src/baserow_enterprise/api/agent_public_chat/serializers.py +++ b/enterprise/backend/src/baserow_enterprise/api/agent_public_chat/serializers.py @@ -3,6 +3,7 @@ from rest_framework import serializers from baserow.api.chat_runs.serializers import ChatRunStreamQuerySerializer from baserow.contrib.agent.api.serializers import AgentMessageContentSerializer from baserow.contrib.agent.models import AgentMessage +from baserow.core.chat_runs.constants import ChatRunErrorCode from baserow_enterprise.agent.constants import ( PUBLIC_CHAT_PASSWORD_MAX_LENGTH, PUBLIC_CHAT_START_KEY_PATTERN, @@ -65,12 +66,20 @@ class PublicChatAuthResponseSerializer(serializers.Serializer): ) +class PublicChatTimeoutField(serializers.BooleanField): + def to_representation(self, error_code): + return error_code == ChatRunErrorCode.TIMEOUT + + class PublicChatMessageSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source="uuid") + timed_out = PublicChatTimeoutField( + source="error_code", read_only=True, default=False + ) class Meta: model = AgentMessage - fields = ("id", "role", "content", "status", "created_on") + fields = ("id", "role", "content", "status", "created_on", "timed_out") class PublicChatConversationSerializer(serializers.Serializer): diff --git a/enterprise/backend/src/baserow_enterprise/assistant/assistant.py b/enterprise/backend/src/baserow_enterprise/assistant/assistant.py index 28beaaedfd..44f39b464d 100644 --- a/enterprise/backend/src/baserow_enterprise/assistant/assistant.py +++ b/enterprise/backend/src/baserow_enterprise/assistant/assistant.py @@ -726,7 +726,7 @@ class BackgroundAssistant(Assistant): ) -> ChatRunOutcome: """ Answers the prompt until it is done or the journal asks the run to stop. - It returns only once every tool call it started has ended. + It waits for started tools even if the runner has already saved the outcome. :param prompt: The human message the run answers. :param ui_context: What the user was looking at when sending it. @@ -740,12 +740,24 @@ class BackgroundAssistant(Assistant): await asyncio.wait({work, stop}, return_when=asyncio.FIRST_COMPLETED) finally: stop.cancel() - await asyncio.gather(stop, return_exceptions=True) - - if work.done(): - await self._tool_executor.drain() - else: - await self._wind_down(work) + stop_started = None + if not work.done(): + stop_started = time.monotonic() + self._tool_helpers.cancel() + work.cancel() + drain = self._tool_executor.drain() + try: + # A released chat can still have a tool running in this worker. + await asyncio.shield(drain) + finally: + await drain + await asyncio.gather(work, stop, return_exceptions=True) + if stop_started is not None: + logger.info( + "The tools of chat run {} stopped {:.2f}s after the run was asked to stop", + self._journal.run.id, + time.monotonic() - stop_started, + ) if not work.cancelled() and work.exception() is not None: logger.warning( "Kuma could not answer in chat {} ({})", @@ -754,27 +766,6 @@ class BackgroundAssistant(Assistant): ) return self._outcome(prompt) - async def _wind_down(self, work: asyncio.Task[None]) -> None: - """ - Stops the agent: tools see the cancel flag and the agent task is - cancelled. Then it waits for every tool call the agent started, with no - time limit, so the run never reports that it stopped while a tool can - still write. The worker's hard time limit is the backstop. - - :param work: The task producing the answer. - """ - - self._tool_helpers.cancel() - work.cancel() - stop_started = time.monotonic() - await self._tool_executor.drain() - await asyncio.gather(work, return_exceptions=True) - logger.info( - "The tools of chat run {} stopped {:.2f}s after the run was asked to stop", - self._journal.run.id, - time.monotonic() - stop_started, - ) - async def _produce( self, prompt: str, ui_context: UIContext, generate_title: bool ) -> None: diff --git a/enterprise/backend/tests/baserow_enterprise_tests/agent/test_public_chat.py b/enterprise/backend/tests/baserow_enterprise_tests/agent/test_public_chat.py index 9506e3f304..137707fc2f 100644 --- a/enterprise/backend/tests/baserow_enterprise_tests/agent/test_public_chat.py +++ b/enterprise/backend/tests/baserow_enterprise_tests/agent/test_public_chat.py @@ -31,7 +31,7 @@ from baserow_premium.license.models import License from tests.baserow.contrib.agent.conftest import configured_agent # noqa: F401 from tests.baserow.contrib.agent.utils import hold_a_workspace_run -MESSAGE_FIELDS = ["content", "created_on", "id", "role", "status"] +MESSAGE_FIELDS = ["content", "created_on", "id", "role", "status", "timed_out"] def url(slug: str, view: str) -> str: @@ -429,6 +429,13 @@ def test_a_conversation_shows_only_the_text_of_the_visitor_and_the_agent( (str(reply.uuid), "assistant"), ] assert [sorted(item) for item in messages] == [MESSAGE_FIELDS, MESSAGE_FIELDS] + assert not any(item["timed_out"] for item in messages) + + reply.status = "failed" + reply.error_code = "timeout" + reply.save(update_fields=["status", "error_code"]) + shown = read(api_client, chat, encode_conversation_token(chat, conversation)) + assert shown.json()["messages"][-1]["timed_out"] is True def a_running_reply(api_client, data_fixture, chat) -> str: diff --git a/enterprise/backend/tests/baserow_enterprise_tests/assistant/runs/test_run_drain.py b/enterprise/backend/tests/baserow_enterprise_tests/assistant/runs/test_run_drain.py index 4363a962f8..8c6a150c16 100644 --- a/enterprise/backend/tests/baserow_enterprise_tests/assistant/runs/test_run_drain.py +++ b/enterprise/backend/tests/baserow_enterprise_tests/assistant/runs/test_run_drain.py @@ -1,16 +1,22 @@ import asyncio import threading import time +from concurrent.futures import ThreadPoolExecutor from typing import Any +from django.db import connections + import pytest from asgiref.sync import async_to_sync, sync_to_async from pydantic_ai.models.function import FunctionModel from baserow.contrib.database.models import Database +from baserow.core.chat_runs.constants import ChatRunErrorCode from baserow.core.chat_runs.handler import ChatRunHandler +from baserow.core.chat_runs.journal import ChatRunJournal from baserow.core.chat_runs.models import ChatRunStatus from baserow.core.chat_runs.tasks import execute_chat_run +from baserow.core.models import Workspace from baserow_enterprise.assistant.assistant import BackgroundAssistant from baserow_enterprise.assistant.deps import ToolHelpers from baserow_enterprise.assistant.retrying_model import RetryingModel @@ -64,6 +70,68 @@ def test_a_stopped_run_finishes_only_after_its_running_tool_ends( assert not Database.objects.filter(name="Kuma DB").exists() +@pytest.mark.django_db(transaction=True) +@pytest.mark.parametrize("user_stopped", [False, True], ids=["deadline", "stop"]) +def test_expired_drain_releases_the_chat_but_keeps_the_task_until_the_tool_exits( + assistant_run, kuma_model, mocker, monkeypatch, fast_journal, user_stopped +): + run = assistant_run(content="Create a database") + release, published = threading.Event(), threading.Event() + + def slow_tool(ctx, builder_type, name): + if user_stopped: + ChatRunHandler().request_cancel(run.id) + if release.wait(10): + Workspace.objects.filter(pk=run.workspace_id).update(name=name) + + publish_finished = ChatRunJournal.publish_finished + + async def record_publication(journal, snapshot): + await publish_finished(journal, snapshot) + published.set() + + def run_task(): + try: + execute_chat_run(str(run.id)) + finally: + connections.close_all() + + mocker.patch.object(ChatRunJournal, "publish_finished", record_publication) + mocker.patch( + "baserow_enterprise.assistant.tools.core.helpers.find_builder", + side_effect=slow_tool, + ) + kuma_model(create_a_database) + monkeypatch.setattr( + "baserow.core.chat_runs.runner.RUN_DEADLINE_SECONDS", 60 if user_stopped else 2 + ) + monkeypatch.setattr("baserow.core.chat_runs.runner.RUN_DRAIN_SECONDS", 0.1) + with ThreadPoolExecutor(1) as worker: + task = worker.submit(run_task) + try: + assert published.wait(6) + run.refresh_from_db() + expected = ( + (ChatRunStatus.CANCELLED, "") + if user_stopped + else (ChatRunStatus.FAILED, ChatRunErrorCode.TIMEOUT) + ) + assert (run.status, run.error_code) == expected + assert (run.outcome["run_status"], run.outcome["error_code"]) == expected + next_run = ChatRunHandler().create_run( + run.run_type, run.chat_id, run.workspace, run.created_by, run.context + ) + assert next_run.status == ChatRunStatus.QUEUED + with pytest.raises(TimeoutError): + task.result(timeout=0.1) + finally: + release.set() + task.result(timeout=5) + + run.workspace.refresh_from_db() + assert run.workspace.name == "Kuma DB" + + @pytest.mark.django_db(transaction=True) def test_stop_accepted_before_tool_dispatch_prevents_the_write( assistant_run, kuma_model, monkeypatch diff --git a/enterprise/web-frontend/modules/baserow_enterprise/locales/en.json b/enterprise/web-frontend/modules/baserow_enterprise/locales/en.json index f4660e1046..e7b92cb853 100644 --- a/enterprise/web-frontend/modules/baserow_enterprise/locales/en.json +++ b/enterprise/web-frontend/modules/baserow_enterprise/locales/en.json @@ -693,7 +693,7 @@ "runStopped": "You stopped Kuma. Any changes already saved are kept.", "runErrorInterrupted": "Kuma was interrupted. Some changes may already have been made, so check them, then tell Kuma how to continue.", "runErrorNotStarted": "Kuma couldn't start on this message because no worker picked it up. Nothing was changed.", - "runErrorTimeout": "Kuma ran out of time before finishing. Some changes may already have been made.", + "runErrorTimeout": "Kuma ran out of time. An action already in progress may still finish. Check its result before trying again.", "runErrorFailed": "Something went wrong while Kuma was working. Some changes may already have been made.", "runErrorPersistFailed": "Kuma finished, but its answer couldn't be saved. The changes it made are kept.", "runErrorModelUnavailable": "Kuma's AI model isn't available right now, so nothing was changed.", @@ -1269,6 +1269,7 @@ "newConversation": "New conversation", "waiting": "Waiting for the team to approve a step.", "failed": "Something went wrong. Send your message again.", + "timedOut": "This reply timed out. If you asked for an action, it may still finish. Sending the same request again could repeat it.", "unavailable": "This chat is no longer available.", "restoreFailed": "Couldn't load your conversation. Trying again…", "stopped": "Stopped.", diff --git a/enterprise/web-frontend/modules/baserow_enterprise/pages/publicAgentChat.vue b/enterprise/web-frontend/modules/baserow_enterprise/pages/publicAgentChat.vue index ceca01eda9..7b0efd5109 100644 --- a/enterprise/web-frontend/modules/baserow_enterprise/pages/publicAgentChat.vue +++ b/enterprise/web-frontend/modules/baserow_enterprise/pages/publicAgentChat.vue @@ -114,7 +114,13 @@ v-if="isFailed(message)" class="chat-message__bubble chat-message__bubble--error" > - {{ $t('publicAgentChat.failed') }} + {{ + $t( + message.timed_out + ? 'publicAgentChat.timedOut' + : 'publicAgentChat.failed' + ) + }}
{{ $t('publicAgentChat.stopped') }} diff --git a/enterprise/web-frontend/test/unit/enterprise/publicAgentChat.spec.js b/enterprise/web-frontend/test/unit/enterprise/publicAgentChat.spec.js index d8769b7c98..e37621f503 100644 --- a/enterprise/web-frontend/test/unit/enterprise/publicAgentChat.spec.js +++ b/enterprise/web-frontend/test/unit/enterprise/publicAgentChat.spec.js @@ -410,26 +410,33 @@ describe('usePublicAgentChat', () => { wrapper.unmount() }) - test('a conversation shows the title in a header and a stopped reply without text as stopped', async () => { - localStorage.setItem( - STORAGE_KEY, - JSON.stringify({ conversationToken: 'conversation' }) - ) - mocks.service.getConversation.mockResolvedValue({ - data: { messages: [visitor, reply('cancelled')], run_id: null }, - }) - const wrapper = await mountSuspended(PublicAgentChatPage, { - route: `/public/agent-chat/${SLUG}`, - }) - await flushPromises() + test.each([ + [reply('cancelled'), 'publicAgentChat.stopped'], + [reply('failed'), 'publicAgentChat.failed'], + [{ ...reply('failed'), timed_out: true }, 'publicAgentChat.timedOut'], + ])( + 'shows the title and the notice for a saved reply %j', + async (message, notice) => { + localStorage.setItem( + STORAGE_KEY, + JSON.stringify({ conversationToken: 'conversation' }) + ) + mocks.service.getConversation.mockResolvedValue({ + data: { messages: [visitor, message], run_id: null }, + }) + const wrapper = await mountSuspended(PublicAgentChatPage, { + route: `/public/agent-chat/${SLUG}`, + }) + await flushPromises() - expect( - wrapper.findAll('.chat-message__bubble').map((bubble) => bubble.text()) - ).toEqual(['Hello', 'publicAgentChat.stopped']) - expect(wrapper.get('.public-agent-chat__title').text()).toBe('Support') - expect(wrapper.find('.public-agent-chat__intro').exists()).toBe(false) - wrapper.unmount() - }) + expect( + wrapper.findAll('.chat-message__bubble').map((bubble) => bubble.text()) + ).toEqual(['Hello', notice]) + expect(wrapper.get('.public-agent-chat__title').text()).toBe('Support') + expect(wrapper.find('.public-agent-chat__intro').exists()).toBe(false) + wrapper.unmount() + } + ) test('a stored conversation is restored and followed; a refused one is forgotten', async () => { localStorage.setItem( diff --git a/enterprise/web-frontend/test/unit/enterprise/utils/assistant.spec.js b/enterprise/web-frontend/test/unit/enterprise/utils/assistant.spec.js index 10638e02b5..719641b6d0 100644 --- a/enterprise/web-frontend/test/unit/enterprise/utils/assistant.spec.js +++ b/enterprise/web-frontend/test/unit/enterprise/utils/assistant.spec.js @@ -6,6 +6,7 @@ describe('runOutcomeKey', () => { test.each([ ['cancelled', '', 'assistant.runStopped'], ['cancelled', 'interrupted', 'assistant.runErrorInterrupted'], + ['failed', 'timeout', 'assistant.runErrorTimeout'], ['failed', 'not_started', 'assistant.runErrorNotStarted'], ['failed', 'added_later', 'assistant.runErrorFailed'], [null, null, null], diff --git a/justfile b/justfile index 6bafd61432..f6559f072e 100644 --- a/justfile +++ b/justfile @@ -261,7 +261,7 @@ _dev-start: # Start docker services (redis, db, mailhog, otel-collector) echo "==> Starting Docker services (redis, db, mailhog, otel-collector)..." - just dc-dev up -d --scale backend=0 --scale web-frontend=0 --scale celery=0 --scale celery-beat-worker=0 --scale celery-export-worker=0 --scale storybook=0 + just dc-dev up -d --scale backend=0 --scale web-frontend=0 --scale celery=0 --scale storybook=0 # Wait for services to be ready echo "==> Waiting for PostgreSQL to be ready..." @@ -686,7 +686,7 @@ _dc-dev-tmux: create_window "backend" "just dc-dev exec backend bash" "just dc-dev logs -f backend" create_window "frontend" "just dc-dev exec web-frontend bash" "just dc-dev logs -f web-frontend" - create_window "celery" "just dc-dev exec celery bash" "just dc-dev logs -f celery celery-beat-worker celery-export-worker" + create_window "celery" "just dc-dev exec celery bash" "just dc-dev logs -f celery" create_window "db" "just dc-dev exec db psql -U baserow" "just dc-dev logs -f db" create_window "redis" "just dc-dev exec redis redis-cli" "just dc-dev logs -f redis" # Inbound email receiver (mox): `just dc-dev up` starts it when @@ -789,8 +789,6 @@ _dc-dev-tabs *ARGS: launch_tab_and_attach "backend" "backend" launch_tab_and_attach "web frontend" "web-frontend" launch_tab_and_attach "celery" "celery" - launch_tab_and_attach "export worker" "celery-export-worker" - launch_tab_and_attach "beat worker" "celery-beat-worker" # Inbound email receiver (mox), started by `just dc-dev up` when # .env.docker-dev sets both variables. if grep -qE '^BASEROW_INBOUND_EMAIL_DOMAIN=.+' .env.docker-dev 2>/dev/null \ diff --git a/premium/backend/src/baserow_premium/config/settings/settings.py b/premium/backend/src/baserow_premium/config/settings/settings.py index 6e02c3492f..3069d5aadc 100644 --- a/premium/backend/src/baserow_premium/config/settings/settings.py +++ b/premium/backend/src/baserow_premium/config/settings/settings.py @@ -2,6 +2,8 @@ import os from django.core.exceptions import ImproperlyConfigured +from loguru import logger + from baserow.config.settings.utils import try_int @@ -37,10 +39,17 @@ def setup(settings): ) # Used to limit thread pool size for running AI field generation in parallel - settings.BASEROW_AI_FIELD_MAX_CONCURRENT_GENERATIONS = try_int( + max_generations = try_int( os.getenv("BASEROW_AI_FIELD_MAX_CONCURRENT_GENERATIONS"), 5 ) + if max_generations < 1: + logger.warning( + "BASEROW_AI_FIELD_MAX_CONCURRENT_GENERATIONS must be positive. Using 1." + ) + max_generations = 1 + settings.BASEROW_AI_FIELD_MAX_CONCURRENT_GENERATIONS = max_generations + # Debounce time for AI field generation, if changes are triggered from # auto-update feature. In seconds. settings.BASEROW_AI_FIELD_AUTO_UPDATE_DEBOUNCE_TIME = try_int( diff --git a/premium/backend/src/baserow_premium/fields/job_types.py b/premium/backend/src/baserow_premium/fields/job_types.py index c127c83204..44539c00c4 100644 --- a/premium/backend/src/baserow_premium/fields/job_types.py +++ b/premium/backend/src/baserow_premium/fields/job_types.py @@ -4,6 +4,7 @@ from datetime import datetime, timezone from queue import Empty, Queue from typing import Any, NamedTuple, Type +from django.conf import settings from django.contrib.auth.models import AbstractUser from django.db import DEFAULT_DB_ALIAS from django.db.models import Exists, OuterRef, QuerySet @@ -63,6 +64,12 @@ from .handler import AIFieldHandler from .models import AIField, AIFieldScheduledUpdate, GenerateAIValuesJob from .visitors import get_ai_prompt_error +# One pool per process, so jobs running side by side on threads share the cap. +_generation_executor = ThreadPoolExecutor( + settings.BASEROW_AI_FIELD_MAX_CONCURRENT_GENERATIONS, + thread_name_prefix="ai-field-generation", +) + class AIValueUpdate(NamedTuple): row: Type[GeneratedTableModel] @@ -396,9 +403,8 @@ class AIValueGenerator: field context to work, but also utilizes Job object as a sender for generation error signal, and Progress object to mark the progress of processing. - Internally, this schedules processing of each row to a separate thread using a - thread pool controlled by a `concurrent.futures.ThreadPoolExecutor`. Because we - use threads, a general rule is to run all code that needs a database connection in + Internally, this schedules processing of each row on a thread pool shared by + every generation in the process. Because we use threads, a general rule is to run all code that needs a database connection in the same, one (main) thread. The code that issues http requests to the model, should be run in a separate thread. @@ -560,9 +566,8 @@ class AIValueGenerator: """ Generate AI model value for selected rows in parallel. - This will call the AI model generator for several rows at once. Each row is - processed in a separate thread, and the number of worker threads is fixed, - controlled by AIField.ai_max_concurrent_generations value. + This will call the AI model generator for several rows at once, on the + process-wide pool of BASEROW_AI_FIELD_MAX_CONCURRENT_GENERATIONS threads. When there an error occurs during the processing in a worker thread, it won't be propagated immediately. Instead, it's pushed to the queue and handled as a @@ -580,32 +585,31 @@ class AIValueGenerator: rows_iter = iter(rows.iterator(chunk_size=200)) - with ThreadPoolExecutor(self.max_concurrency) as executor: - while True: - try: - # Allow to schedule only a limited number of futures, so we don't - # populate executor's backlog with an excessive amount of rows - # to process. We add new rows to process only if there's a - # 'free slot' in the executor. - while self.can_schedule_next(): - self.schedule_next_row(rows_iter, executor) + while True: + try: + # Allow to schedule only a limited number of futures, so we don't + # populate executor's backlog with an excessive amount of rows + # to process. We add new rows to process only if there's a + # 'free slot' in the executor. + while self.can_schedule_next(): + self.schedule_next_row(rows_iter, _generation_executor) - except StopIteration: - self.stop_scheduling_rows() + except StopIteration: + self.stop_scheduling_rows() - try: - processed = self.results_queue.get(block=True, timeout=0.01) - self.handle_result(processed) + try: + processed = self.results_queue.get(block=True, timeout=0.01) + self.handle_result(processed) - # Queue is empty, no processed results available yet; continue polling. - except Empty: - pass - except Exception as e: - logger.opt(exception=e).error(f"Error when handing result: {e}") - self.stop_scheduling_rows() + # Queue is empty, no processed results available yet; continue polling. + except Empty: + pass + except Exception as e: + logger.opt(exception=e).error(f"Error when handing result: {e}") + self.stop_scheduling_rows() - if self.is_finished(): - break + if self.is_finished(): + break self.raise_if_error() diff --git a/premium/backend/tests/baserow_premium_tests/generative_ai/test_ai_parallel_execution.py b/premium/backend/tests/baserow_premium_tests/generative_ai/test_ai_parallel_execution.py index 38407f9963..8d343d3b54 100644 --- a/premium/backend/tests/baserow_premium_tests/generative_ai/test_ai_parallel_execution.py +++ b/premium/backend/tests/baserow_premium_tests/generative_ai/test_ai_parallel_execution.py @@ -1,4 +1,8 @@ +import threading +import time +from concurrent.futures import ThreadPoolExecutor from io import BytesIO +from types import SimpleNamespace from unittest import mock import pytest @@ -7,9 +11,25 @@ from baserow.contrib.database.rows.handler import RowHandler from baserow.core.generative_ai.exceptions import GenerativeAIPromptError from baserow.core.storage import get_default_storage from baserow.core.user_files.handler import UserFileHandler +from baserow_premium.config.settings.settings import setup from baserow_premium.fields.job_types import AIValueGenerator +@pytest.mark.parametrize( + "configured,expected", [("0", 1), ("-1", 1), ("1", 1), ("3", 3), ("invalid", 5)] +) +def test_ai_generation_concurrency_setting(monkeypatch, configured, expected, mocker): + monkeypatch.setenv("BASEROW_AI_FIELD_MAX_CONCURRENT_GENERATIONS", configured) + warn = mocker.patch("baserow_premium.config.settings.settings.logger.warning") + config = SimpleNamespace() + setup(config) + assert config.BASEROW_AI_FIELD_MAX_CONCURRENT_GENERATIONS == expected + if configured in ("0", "-1"): + assert "BASEROW_AI_FIELD_MAX_CONCURRENT_GENERATIONS" in warn.call_args.args[0] + else: + warn.assert_not_called() + + @pytest.mark.django_db def test_ai_parallel_execution(premium_data_fixture): storage = get_default_storage() @@ -119,3 +139,50 @@ def test_ai_parallel_execution_with_error(premium_data_fixture): assert gen.finished == 5 assert gen.error_msg is not None assert on_progress_mock.called + + +@pytest.mark.django_db +def test_concurrent_generations_share_one_thread_limit(premium_data_fixture): + user = premium_data_fixture.create_user() + ai_field = premium_data_fixture.create_ai_field( + table=premium_data_fixture.create_database_table(user=user) + ) + lock = threading.Lock() + running = [] + peak = [] + + def generate(field, row, *args, **kwargs): + with lock: + running.append(row) + peak.append(len(running)) + time.sleep(0.02) + with lock: + running.remove(row) + return "value" + + def process(generator, first_id): + rows = [SimpleNamespace(id=first_id + i) for i in range(10)] + generator.process(SimpleNamespace(iterator=lambda chunk_size: iter(rows))) + + generators = [AIValueGenerator(user, ai_field) for _ in range(3)] + with ( + mock.patch( + "baserow_premium.fields.job_types._generation_executor", + ThreadPoolExecutor(2), + ), + mock.patch( + "baserow_premium.fields.handler.AIFieldHandler.generate_value_with_ai", + side_effect=generate, + ), + ): + threads = [ + threading.Thread(target=process, args=(generator, index * 100)) + for index, generator in enumerate(generators) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(10) + + assert [generator.finished for generator in generators] == [10, 10, 10] + assert max(peak) == 2 diff --git a/web-frontend/modules/agent/locales/en.json b/web-frontend/modules/agent/locales/en.json index d7fffaa3ec..16921fc02a 100644 --- a/web-frontend/modules/agent/locales/en.json +++ b/web-frontend/modules/agent/locales/en.json @@ -213,7 +213,7 @@ "replyStopped": "Stopped.", "replyStoppedBy": "Stopped by {name}.", "replyCancelledBeforeStart": "Cancelled before it started.", - "replyTimedOut": "This reply took too long and was stopped.", + "replyTimedOut": "This reply timed out. An action already in progress may still finish. Check its result before trying again.", "replyInterrupted": "This reply was interrupted.", "replyNotStarted": "The agent couldn’t start replying. Send your message again.", "replyNotReady": "The agent wasn’t ready to reply. Check its configuration and send your message again.",