Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions api/schedule/check_upgradable_plugin_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
import time

import click
from celery import shared_task
from sqlalchemy import select

import app
from core.db.session_factory import session_factory
from core.helper.marketplace import fetch_global_plugin_manifest
from extensions.ext_database import db
from models.account import TenantPluginAutoUpgradeStrategy, TenantPluginAutoUpgradeStrategySetting
from tasks import process_tenant_plugin_autoupgrade_check_task as check_task

Expand All @@ -21,22 +21,23 @@
CACHE_REDIS_TTL = check_task.CACHE_REDIS_TTL


@app.celery.task(queue="plugin")
@shared_task(queue="plugin")
def check_upgradable_plugin_task():
click.echo(click.style("Start check upgradable plugin.", fg="green"))
start_at = time.perf_counter()

now_seconds_of_day = time.time() % 86400 - 30 # we assume the tz is UTC
click.echo(click.style(f"Now seconds of day: {now_seconds_of_day}", fg="green"))

strategies = db.session.scalars(
select(TenantPluginAutoUpgradeStrategy).where(
TenantPluginAutoUpgradeStrategy.upgrade_time_of_day >= now_seconds_of_day,
TenantPluginAutoUpgradeStrategy.upgrade_time_of_day
< now_seconds_of_day + AUTO_UPGRADE_MINIMAL_CHECKING_INTERVAL,
TenantPluginAutoUpgradeStrategy.strategy_setting != TenantPluginAutoUpgradeStrategySetting.DISABLED,
)
).all()
with session_factory.create_session() as session:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Take the session as a required parameter instead of reaching for a global (@with_session injects it in controllers). If this code must open and commit its own short transaction, take the session factory as a parameter instead (e.g. in __init__). Then tests pass sqlite_session / sqlite_session_factory directly and need no monkeypatch, and can assert the committed row from another session instead of counting commits.

dify-codereview · inject-session Learned from an earlier review. Reply here if this is wrong.

strategies = session.scalars(
select(TenantPluginAutoUpgradeStrategy).where(
TenantPluginAutoUpgradeStrategy.upgrade_time_of_day >= now_seconds_of_day,
TenantPluginAutoUpgradeStrategy.upgrade_time_of_day
< now_seconds_of_day + AUTO_UPGRADE_MINIMAL_CHECKING_INTERVAL,
TenantPluginAutoUpgradeStrategy.strategy_setting != TenantPluginAutoUpgradeStrategySetting.DISABLED,
)
).all()

total_strategies = len(strategies)
click.echo(click.style(f"Total strategies: {total_strategies}", fg="green"))
Expand Down
43 changes: 22 additions & 21 deletions api/schedule/clean_embedding_cache_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,40 @@
import time

import click
from celery import shared_task
from sqlalchemy import select, text
from sqlalchemy.exc import SQLAlchemyError

import app
from configs import dify_config
from extensions.ext_database import db
from core.db.session_factory import session_factory
from models.dataset import Embedding


@app.celery.task(queue="dataset")
@shared_task(queue="dataset")
def clean_embedding_cache_task():
click.echo(click.style("Start clean embedding cache.", fg="green"))
clean_days = int(dify_config.PLAN_SANDBOX_CLEAN_DAY_SETTING)
start_at = time.perf_counter()
thirty_days_ago = datetime.datetime.now() - datetime.timedelta(days=clean_days)
while True:
try:
embedding_ids = db.session.scalars(
select(Embedding.id)
.where(Embedding.created_at < thirty_days_ago)
.order_by(Embedding.created_at.desc())
.limit(100)
).all()
except SQLAlchemyError:
raise
if embedding_ids:
for embedding_id in embedding_ids:
db.session.execute(
text("DELETE FROM embeddings WHERE id = :embedding_id"), {"embedding_id": embedding_id}
)
with session_factory.create_session() as session:
while True:
try:
embedding_ids = session.scalars(
select(Embedding.id)
.where(Embedding.created_at < thirty_days_ago)
.order_by(Embedding.created_at.desc())
.limit(100)
).all()
except SQLAlchemyError:
raise
if embedding_ids:
for embedding_id in embedding_ids:
session.execute(
text("DELETE FROM embeddings WHERE id = :embedding_id"), {"embedding_id": embedding_id}
)

db.session.commit()
else:
break
session.commit()
else:
break
end_at = time.perf_counter()
click.echo(click.style(f"Cleaned embedding cache from db success latency: {end_at - start_at}", fg="green"))
21 changes: 11 additions & 10 deletions api/schedule/clean_oauth_access_tokens_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@
from datetime import UTC, datetime, timedelta

import click
from celery import shared_task
from sqlalchemy import delete, or_, select

import app
from configs import dify_config
from extensions.ext_database import db
from core.db.session_factory import session_factory
from models.oauth import OAuthAccessToken

logger = logging.getLogger(__name__)

DELETE_BATCH_SIZE = 500


@app.celery.task(queue="retention")
@shared_task(queue="retention")
def clean_oauth_access_tokens_task():
click.echo(click.style("Start clean oauth_access_tokens.", fg="green"))
retention_days = int(dify_config.OAUTH_ACCESS_TOKEN_RETENTION_DAYS)
Expand All @@ -37,13 +37,14 @@ def clean_oauth_access_tokens_task():
)

total = 0
while True:
ids = db.session.scalars(select(OAuthAccessToken.id).where(candidates).limit(DELETE_BATCH_SIZE)).all()
if not ids:
break
db.session.execute(delete(OAuthAccessToken).where(OAuthAccessToken.id.in_(ids)))
db.session.commit()
total += len(ids)
with session_factory.create_session() as session:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Take the session as a required parameter instead of reaching for a global (@with_session injects it in controllers). If this code must open and commit its own short transaction, take the session factory as a parameter instead (e.g. in __init__). Then tests pass sqlite_session / sqlite_session_factory directly and need no monkeypatch, and can assert the committed row from another session instead of counting commits.

dify-codereview · inject-session Learned from an earlier review. Reply here if this is wrong.

while True:
ids = session.scalars(select(OAuthAccessToken.id).where(candidates).limit(DELETE_BATCH_SIZE)).all()
if not ids:
break
session.execute(delete(OAuthAccessToken).where(OAuthAccessToken.id.in_(ids)))
session.commit()
total += len(ids)

end_at = time.perf_counter()
click.echo(
Expand Down
19 changes: 10 additions & 9 deletions api/schedule/create_tidb_serverless_task.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import time

import click
from celery import shared_task
from dify_vdb_tidb_on_qdrant.tidb_service import TidbService
from sqlalchemy import func, select
from sqlalchemy.orm import Session

import app
from configs import dify_config
from extensions.ext_database import db
from core.db.session_factory import session_factory
from models.dataset import TidbAuthBinding
from models.enums import TidbAuthBindingStatus


@app.celery.task(queue="dataset")
@shared_task(queue="dataset")
def create_tidb_serverless_task():
click.echo(click.style("Start create tidb serverless task.", fg="green"))
if not dify_config.CREATE_TIDB_SERVICE_JOB_ENABLED:
Expand All @@ -30,15 +31,15 @@ def create_tidb_serverless_task():
iterations_per_thread = 20
create_clusters(iterations_per_thread)

except Exception as e:
click.echo(click.style(f"Error: {e}", fg="red"))
break
except Exception as e:
click.echo(click.style(f"Error: {e}", fg="red"))
break

end_at = time.perf_counter()
click.echo(click.style(f"Create tidb serverless task success latency: {end_at - start_at}", fg="green"))


def create_clusters(batch_size):
def create_clusters(batch_size, session: Session):
try:
# TODO: maybe we can set the default value for the following parameters in the config file
new_clusters = TidbService.batch_create_tidb_serverless_cluster(
Expand All @@ -61,7 +62,7 @@ def create_clusters(batch_size):
active=False,
status=TidbAuthBindingStatus.CREATING,
)
db.session.add(tidb_auth_binding)
db.session.commit()
session.add(tidb_auth_binding)
session.commit()
except Exception as e:
click.echo(click.style(f"Error: {e}", fg="red"))
49 changes: 26 additions & 23 deletions api/schedule/queue_monitor_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,40 @@
from datetime import datetime

import click
from celery import shared_task
from kombu.utils.url import parse_url # type: ignore
from redis import Redis

import app
from configs import dify_config
from extensions.ext_database import db
from libs.email_i18n import EmailType, get_email_i18n_service

redis_config = parse_url(dify_config.CELERY_BROKER_URL)
celery_redis = Redis(
host=str(redis_config.get("hostname") or "localhost"),
port=int(redis_config.get("port") or 6379),
password=str(pwd) if (pwd := redis_config.get("password")) is not None else None,
db=int(redis_config.get("virtual_host")) if redis_config.get("virtual_host") else 1,
ssl=dify_config.BROKER_USE_SSL,
ssl_ca_certs=dify_config.REDIS_SSL_CA_CERTS if dify_config.BROKER_USE_SSL else None,
ssl_cert_reqs=getattr(dify_config, "REDIS_SSL_CERT_REQS", None) if dify_config.BROKER_USE_SSL else None,
ssl_certfile=getattr(dify_config, "REDIS_SSL_CERTFILE", None) if dify_config.BROKER_USE_SSL else None,
ssl_keyfile=getattr(dify_config, "REDIS_SSL_KEYFILE", None) if dify_config.BROKER_USE_SSL else None,
# Add conservative socket timeouts and health checks to avoid long-lived half-open sockets
socket_timeout=5,
socket_connect_timeout=5,
health_check_interval=30,
)

logger = logging.getLogger(__name__)


@app.celery.task(queue="monitor")
def _create_celery_redis() -> Redis:
broker_url = dify_config.CELERY_BROKER_URL
if not broker_url:
raise ValueError("CELERY_BROKER_URL is required for queue monitoring")

redis_config = parse_url(broker_url)
return Redis(
host=str(redis_config.get("hostname") or "localhost"),
port=int(redis_config.get("port") or 6379),
password=str(pwd) if (pwd := redis_config.get("password")) is not None else None,
db=int(redis_config.get("virtual_host")) if redis_config.get("virtual_host") else 1,
ssl=dify_config.BROKER_USE_SSL,
ssl_ca_certs=dify_config.REDIS_SSL_CA_CERTS if dify_config.BROKER_USE_SSL else None,
ssl_cert_reqs=dify_config.REDIS_SSL_CERT_REQS if dify_config.BROKER_USE_SSL else None,
ssl_certfile=dify_config.REDIS_SSL_CERTFILE if dify_config.BROKER_USE_SSL else None,
ssl_keyfile=dify_config.REDIS_SSL_KEYFILE if dify_config.BROKER_USE_SSL else None,
# Add conservative socket timeouts and health checks to avoid long-lived half-open sockets
socket_timeout=5,
socket_connect_timeout=5,
health_check_interval=30,
)


@shared_task(queue="monitor")
def queue_monitor_task():
queue_name = "dataset"
threshold = dify_config.QUEUE_MONITOR_THRESHOLD
Expand All @@ -40,6 +45,7 @@ def queue_monitor_task():
return

try:
celery_redis = _create_celery_redis()
queue_length = celery_redis.llen(f"{queue_name}")
logger.info(click.style(f"Start monitor {queue_name}", fg="green"))

Expand Down Expand Up @@ -77,6 +83,3 @@ def queue_monitor_task():

except Exception:
logger.exception(click.style("Exception occurred during queue monitoring", fg="red"))
finally:
if db.session.is_active:
db.session.close()
6 changes: 3 additions & 3 deletions api/schedule/update_tidb_serverless_status_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@
from collections.abc import Sequence

import click
from celery import shared_task
from dify_vdb_tidb_on_qdrant.tidb_service import TidbService
from sqlalchemy import select

import app
from configs import dify_config
from extensions.ext_database import db
from core.db.session_factory import session_factory
from models.dataset import TidbAuthBinding
from models.enums import TidbAuthBindingStatus


@app.celery.task(queue="dataset")
@shared_task(queue="dataset")
def update_tidb_serverless_status_task():
click.echo(click.style("Update tidb serverless status task.", fg="green"))
start_at = time.perf_counter()
Expand Down
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""Unit tests for ``check_upgradable_plugin_task`` strategy selection.

The task dispatches upgrade checks for auto-upgrade strategies whose
``upgrade_time_of_day`` falls inside the current checking window. Sessions
are provided by the shared SQLite session factory, which proves the task no
longer depends on the global Flask-SQLAlchemy session.
"""

import time
import uuid
from unittest.mock import patch

import pytest
from sqlalchemy.orm import Session, sessionmaker

import schedule.check_upgradable_plugin_task as check_upgradable_module
from models.account import TenantPluginAutoUpgradeStrategy, TenantPluginAutoUpgradeStrategySetting
from schedule.check_upgradable_plugin_task import (
AUTO_UPGRADE_MINIMAL_CHECKING_INTERVAL,
check_upgradable_plugin_task,
)


def _make_strategy(
*, upgrade_time_of_day: int, setting: TenantPluginAutoUpgradeStrategySetting
) -> TenantPluginAutoUpgradeStrategy:
return TenantPluginAutoUpgradeStrategy(
tenant_id=str(uuid.uuid4()),
strategy_setting=setting,
upgrade_time_of_day=upgrade_time_of_day,
)


@pytest.fixture
def seeded_strategies(sqlite_session_factory: sessionmaker[Session]) -> dict[str, str]:
"""Seed strategies covering each branch of the selection window."""
window_start = int(time.time() % 86400 - 30)
in_window = window_start + 60
out_of_window = window_start + AUTO_UPGRADE_MINIMAL_CHECKING_INTERVAL + 3600

strategies = {
"in_window": _make_strategy(
upgrade_time_of_day=in_window, setting=TenantPluginAutoUpgradeStrategySetting.FIX_ONLY
),
"out_of_window": _make_strategy(
upgrade_time_of_day=out_of_window, setting=TenantPluginAutoUpgradeStrategySetting.FIX_ONLY
),
"disabled": _make_strategy(
upgrade_time_of_day=in_window, setting=TenantPluginAutoUpgradeStrategySetting.DISABLED
),
}
with sqlite_session_factory() as session:
for strategy in strategies.values():
session.add(strategy)
session.commit()
return {label: strategy.tenant_id for label, strategy in strategies.items()}


def test_dispatches_only_in_window_enabled_strategies(seeded_strategies: dict[str, str]) -> None:
with (
patch.object(check_upgradable_module, "fetch_global_plugin_manifest"),
patch.object(
check_upgradable_module.check_task, "process_tenant_plugin_autoupgrade_check_task"
) as mock_check_task,
):
check_upgradable_plugin_task()

dispatched_tenants = [call.args[0] for call in mock_check_task.delay.call_args_list]
assert dispatched_tenants == [seeded_strategies["in_window"]]
Loading
Loading