Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

feat: dispatch New Agent Beta eligibility checks (#40725)

非法操作e3ab88f6dea6
diff --git a/api/configs/feature/__init__.py b/api/configs/feature/__init__.py
index 0772b1d08d4..a4cefb4ba40 100644
--- a/api/configs/feature/__init__.py
+++ b/api/configs/feature/__init__.py
@@ -1324,6 +1324,17 @@ class MultiModalTransferConfig(BaseSettings):
)
+class NewAgentBetaConfig(BaseSettings):
+ NEW_AGENT_BETA_ACTIVITY_START_AT: datetime | None = Field(
+ description="New Agent Beta Publish window start in RFC3339 UTC (inclusive)",
+ default=None,
+ )
+ NEW_AGENT_BETA_ACTIVITY_END_AT: datetime | None = Field(
+ description="New Agent Beta Publish window end in RFC3339 UTC (exclusive)",
+ default=None,
+ )
+
+
class OpsTraceConfig(BaseSettings):
OPS_TRACE_RETRYABLE_DISPATCH_MAX_RETRIES: PositiveInt = Field(
description="Maximum retry attempts for transient ops trace provider dispatch failures.",
@@ -1641,6 +1652,7 @@ class FeatureConfig(
ModelLoadBalanceConfig,
ModerationConfig,
MultiModalTransferConfig,
+ NewAgentBetaConfig,
OpsTraceConfig,
PositionConfig,
RagEtlConfig,
diff --git a/api/extensions/ext_celery.py b/api/extensions/ext_celery.py
index 184dd5bddfa..724fb4774cc 100644
--- a/api/extensions/ext_celery.py
+++ b/api/extensions/ext_celery.py
@@ -173,6 +173,7 @@ def init_app(app: DifyApp) -> Celery:
"tasks.regenerate_summary_index_task", # summary index regeneration
"tasks.initialize_created_app_rbac_access_task", # app access initialization
"tasks.install_default_plugins_task", # tenant default plugin installation
+ "tasks.new_agent_beta_task", # New Agent Beta eligibility checks
"tasks.refresh_billing_vector_space_task", # billing vector-space cache refresh
"tasks.app_generate.resume_agent_app_task", # ENG-635: Agent v2 chat ask_human resume
"tasks.workflow_run_archive_download_tasks", # workflow-run archive download preparation
diff --git a/api/services/agent/composer_service.py b/api/services/agent/composer_service.py
index 13924aae4b1..d29d8ed6b41 100644
--- a/api/services/agent/composer_service.py
+++ b/api/services/agent/composer_service.py
@@ -67,6 +67,7 @@ from services.entities.agent_entities import (
WorkflowNodeJobConfig,
)
from tasks.collect_agent_resources_task import enqueue_agent_resource_collection
+from tasks.new_agent_beta_task import register_new_agent_beta_publish_after_commit
# WorkflowAgentNodeBinding.workflow_version tag for the draft workflow row.
# Mirrors Workflow.version when it is "draft" (see models/workflow.py).
@@ -683,6 +684,12 @@ class AgentComposerService:
app.enable_api = True
app.updated_by = account_id
session.flush()
+ register_new_agent_beta_publish_after_commit(
+ session=session,
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ snapshot_id=version.id,
+ )
return {
"result": "success",
"active_config_snapshot_id": version.id,
diff --git a/api/services/billing_service.py b/api/services/billing_service.py
index 0519f66f2c6..e4c38f8874c 100644
--- a/api/services/billing_service.py
+++ b/api/services/billing_service.py
@@ -208,6 +208,10 @@ class BillingService:
# Cache TTL: 10 minutes
_PLAN_CACHE_TTL = 600
+ @classmethod
+ def ensure_new_agent_beta_revision(cls, revision_id: str) -> None:
+ cls._send_request("POST", f"/new-agent-beta/revisions/{revision_id}/ensure")
+
@classmethod
def get_info(cls, tenant_id: str, exclude_vector_space: bool = False) -> BillingInfo:
params = {"tenant_id": tenant_id}
diff --git a/api/tasks/new_agent_beta_task.py b/api/tasks/new_agent_beta_task.py
new file mode 100644
index 00000000000..e8febca9e45
--- /dev/null
+++ b/api/tasks/new_agent_beta_task.py
@@ -0,0 +1,114 @@
+import logging
+from datetime import UTC, datetime
+
+from celery import shared_task
+from sqlalchemy import event, select
+from sqlalchemy.orm import Session
+
+from configs import dify_config
+from enums import DeploymentEdition
+from models.agent import AgentConfigRevision, AgentConfigRevisionOperation
+from services.billing_service import BillingService
+
+logger = logging.getLogger(__name__)
+
+_MAX_RETRIES = 8
+_RETRY_DELAY_SECONDS = 30
+_MAX_RETRY_DELAY_SECONDS = 900
+NEW_AGENT_BETA_QUEUE = "new_agent_beta"
+
+
+def _is_publish_in_activity_window(published_at: datetime) -> bool:
+ start = dify_config.NEW_AGENT_BETA_ACTIVITY_START_AT
+ end = dify_config.NEW_AGENT_BETA_ACTIVITY_END_AT
+ if start is None or end is None or start.tzinfo is None or end.tzinfo is None or start >= end:
+ logger.error("New Agent Beta Publish window must be a valid RFC3339 interval")
+ return False
+ if published_at.tzinfo is None:
+ published_at = published_at.replace(tzinfo=UTC)
+ else:
+ published_at = published_at.astimezone(UTC)
+ return start.astimezone(UTC) <= published_at < end.astimezone(UTC)
+
+
+def register_new_agent_beta_publish_after_commit(
+ *, session: Session, tenant_id: str, agent_id: str, snapshot_id: str
+) -> None:
+ """Best-effort registration that never changes the Publish result."""
+ if dify_config.DEPLOYMENT_EDITION != DeploymentEdition.CLOUD:
+ return
+
+ try:
+ revision = session.scalar(
+ select(AgentConfigRevision)
+ .where(
+ AgentConfigRevision.tenant_id == tenant_id,
+ AgentConfigRevision.agent_id == agent_id,
+ AgentConfigRevision.current_snapshot_id == snapshot_id,
+ AgentConfigRevision.operation == AgentConfigRevisionOperation.PUBLISH_DRAFT,
+ )
+ .limit(1)
+ )
+ if revision is None:
+ logger.error(
+ "New Agent Beta publish revision was not found, tenant_id=%s, agent_id=%s, snapshot_id=%s",
+ tenant_id,
+ agent_id,
+ snapshot_id,
+ )
+ return
+ if not _is_publish_in_activity_window(revision.created_at):
+ return
+ cancelled = False
+
+ def cancel_on_rollback(_session: Session) -> None:
+ nonlocal cancelled
+ cancelled = True
+
+ def dispatch_after_commit(_session: Session) -> None:
+ if not cancelled:
+ schedule_new_agent_beta_ensure(revision.id)
+
+ event.listen(session, "after_rollback", cancel_on_rollback, once=True)
+ event.listen(session, "after_commit", dispatch_after_commit, once=True)
+ except Exception:
+ logger.exception(
+ "Failed to register New Agent Beta publish event, tenant_id=%s, agent_id=%s, snapshot_id=%s",
+ tenant_id,
+ agent_id,
+ snapshot_id,
+ )
+
+
+@shared_task(
+ queue=NEW_AGENT_BETA_QUEUE,
+ bind=True,
+ max_retries=_MAX_RETRIES,
+ default_retry_delay=_RETRY_DELAY_SECONDS,
+ acks_late=True,
+ reject_on_worker_lost=True,
+)
+def ensure_new_agent_beta_participation_task(self, revision_id: str) -> None:
+ try:
+ BillingService.ensure_new_agent_beta_revision(revision_id)
+ except Exception as exc:
+ if self.request.retries >= _MAX_RETRIES:
+ logger.exception("New Agent Beta eligibility retry budget exhausted, revision_id=%s", revision_id)
+ raise
+
+ logger.warning(
+ "New Agent Beta eligibility request failed, scheduling retry %d/%d, revision_id=%s",
+ self.request.retries + 1,
+ _MAX_RETRIES,
+ revision_id,
+ exc_info=True,
+ )
+ countdown = min(_RETRY_DELAY_SECONDS * (2**self.request.retries), _MAX_RETRY_DELAY_SECONDS)
+ raise self.retry(exc=exc, countdown=countdown)
+
+
+def schedule_new_agent_beta_ensure(revision_id: str) -> None:
+ try:
+ ensure_new_agent_beta_participation_task.delay(revision_id)
+ except Exception:
+ logger.exception("Failed to dispatch New Agent Beta eligibility task, revision_id=%s", revision_id)
diff --git a/api/tests/unit_tests/services/agent/test_agent_services.py b/api/tests/unit_tests/services/agent/test_agent_services.py
index 459361f744d..5dbce1c2549 100644
--- a/api/tests/unit_tests/services/agent/test_agent_services.py
+++ b/api/tests/unit_tests/services/agent/test_agent_services.py
@@ -930,6 +930,7 @@ def test_publish_agent_app_draft_creates_published_snapshot(monkeypatch: pytest.
session.commit()
created: dict[str, object] = {}
calls: list[str] = []
+ register_publish_event = MagicMock()
monkeypatch.setattr(composer_service.ComposerConfigValidator, "validate_publish_payload", lambda payload: None)
monkeypatch.setattr(composer_service, "agent_has_workflow_callable_active_snapshot", lambda **_kwargs: False)
@@ -945,6 +946,7 @@ def test_publish_agent_app_draft_creates_published_snapshot(monkeypatch: pytest.
lambda **kwargs: calls.append("create_version") or created.update(kwargs) or version,
)
monkeypatch.setattr(AgentComposerService, "_serialize_version", lambda _version: {"id": _version.id})
+ monkeypatch.setattr(composer_service, "register_new_agent_beta_publish_after_commit", register_publish_event)
result = AgentComposerService.publish_agent_app_draft(
session=session,
@@ -967,6 +969,12 @@ def test_publish_agent_app_draft_creates_published_snapshot(monkeypatch: pytest.
assert app.enable_site is True
assert app.enable_api is True
assert app.updated_by == "account-1"
+ register_publish_event.assert_called_once_with(
+ session=session,
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ snapshot_id="version-2",
+ )
def test_repeated_publish_reuses_normal_draft_home_without_creating_resources(
diff --git a/api/tests/unit_tests/services/test_billing_service.py b/api/tests/unit_tests/services/test_billing_service.py
index b6d3a5c150e..5b1ce38ad4a 100644
--- a/api/tests/unit_tests/services/test_billing_service.py
+++ b/api/tests/unit_tests/services/test_billing_service.py
@@ -220,6 +220,30 @@ class TestBillingServiceSendRequest:
call_args = mock_httpx_request.call_args
assert call_args[0][0] == method
+ def test_new_agent_beta_ensure_uses_secret_authenticated_v1_base(self, mock_httpx_request, mock_billing_config):
+ mock_response = MagicMock()
+ mock_response.status_code = httpx.codes.OK
+ mock_response.json.return_value = {"status": "issued"}
+ mock_httpx_request.return_value = mock_response
+
+ BillingService.ensure_new_agent_beta_revision("revision-1")
+
+ call_args = mock_httpx_request.call_args
+ assert call_args.args == (
+ "POST",
+ "https://billing-api.example.com/new-agent-beta/revisions/revision-1/ensure",
+ )
+ assert call_args.kwargs["headers"]["Billing-Api-Secret-Key"] == "test-secret-key"
+
+ def test_new_agent_beta_ensure_requires_json_response(self, mock_httpx_request, mock_billing_config):
+ mock_response = MagicMock()
+ mock_response.status_code = httpx.codes.OK
+ mock_response.json.side_effect = json.JSONDecodeError("Expecting value", "", 0)
+ mock_httpx_request.return_value = mock_response
+
+ with pytest.raises(json.JSONDecodeError):
+ BillingService.ensure_new_agent_beta_revision("revision-1")
+
@pytest.mark.parametrize(
"status_code", [httpx.codes.BAD_REQUEST, httpx.codes.INTERNAL_SERVER_ERROR, httpx.codes.NOT_FOUND]
)
diff --git a/api/tests/unit_tests/tasks/test_new_agent_beta_task.py b/api/tests/unit_tests/tasks/test_new_agent_beta_task.py
new file mode 100644
index 00000000000..d3833f7b269
--- /dev/null
+++ b/api/tests/unit_tests/tasks/test_new_agent_beta_task.py
@@ -0,0 +1,191 @@
+from datetime import UTC, datetime
+from typing import Protocol, cast
+from unittest.mock import MagicMock
+
+import pytest
+from sqlalchemy.orm import Session
+
+from enums import DeploymentEdition
+from models.agent import AgentConfigRevision, AgentConfigRevisionOperation
+from services.billing_service import BillingService
+from tasks import new_agent_beta_task as task_module
+from tasks.new_agent_beta_task import (
+ NEW_AGENT_BETA_QUEUE,
+ ensure_new_agent_beta_participation_task,
+ register_new_agent_beta_publish_after_commit,
+ schedule_new_agent_beta_ensure,
+)
+
+
+class _TaskWithQueue(Protocol):
+ queue: str
+
+
+def _configure_cloud_publish(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(task_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.CLOUD)
+ monkeypatch.setattr(task_module.dify_config, "NEW_AGENT_BETA_ACTIVITY_START_AT", datetime(2026, 8, 12, tzinfo=UTC))
+ monkeypatch.setattr(task_module.dify_config, "NEW_AGENT_BETA_ACTIVITY_END_AT", datetime(2026, 8, 13, tzinfo=UTC))
+
+
[email protected]("sqlite_session", [(AgentConfigRevision,)], indirect=True)
+def test_publish_event_is_dispatched_only_after_commit(
+ monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
+) -> None:
+ published_at = datetime(2026, 8, 12, 1, 0)
+ _configure_cloud_publish(monkeypatch)
+ revision = AgentConfigRevision(
+ id="revision-1",
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ current_snapshot_id="snapshot-1",
+ revision=1,
+ operation=AgentConfigRevisionOperation.PUBLISH_DRAFT,
+ created_at=published_at,
+ )
+ sqlite_session.add(revision)
+ sqlite_session.flush()
+ dispatch = MagicMock()
+ monkeypatch.setattr(task_module, "schedule_new_agent_beta_ensure", dispatch)
+
+ register_new_agent_beta_publish_after_commit(
+ session=sqlite_session,
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ snapshot_id="snapshot-1",
+ )
+
+ dispatch.assert_not_called()
+ sqlite_session.commit()
+ dispatch.assert_called_once_with("revision-1")
+
+
[email protected]("sqlite_session", [(AgentConfigRevision,)], indirect=True)
+def test_rolled_back_publish_is_never_dispatched(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
+ published_at = datetime(2026, 8, 12, 1, 0)
+ _configure_cloud_publish(monkeypatch)
+ sqlite_session.add(
+ AgentConfigRevision(
+ id="revision-1",
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ current_snapshot_id="snapshot-1",
+ revision=1,
+ operation=AgentConfigRevisionOperation.PUBLISH_DRAFT,
+ created_at=published_at,
+ )
+ )
+ sqlite_session.flush()
+ dispatch = MagicMock()
+ monkeypatch.setattr(task_module, "schedule_new_agent_beta_ensure", dispatch)
+
+ register_new_agent_beta_publish_after_commit(
+ session=sqlite_session,
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ snapshot_id="snapshot-1",
+ )
+ sqlite_session.rollback()
+ sqlite_session.commit()
+
+ dispatch.assert_not_called()
+
+
+def test_non_cloud_publish_skips_revision_lookup(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(task_module.dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.COMMUNITY)
+ session = MagicMock()
+
+ register_new_agent_beta_publish_after_commit(
+ session=session,
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ snapshot_id="snapshot-1",
+ )
+
+ session.scalar.assert_not_called()
+
+
+ ("start", "end", "published_at", "expected"),
+ [
+ (datetime(2026, 8, 12, tzinfo=UTC), datetime(2026, 8, 13, tzinfo=UTC), datetime(2026, 8, 12), True),
+ (datetime(2026, 8, 12, tzinfo=UTC), datetime(2026, 8, 13, tzinfo=UTC), datetime(2026, 8, 13), False),
+ (None, datetime(2026, 8, 13, tzinfo=UTC), datetime(2026, 8, 12), False),
+ (datetime(2026, 8, 13, tzinfo=UTC), datetime(2026, 8, 12, tzinfo=UTC), datetime(2026, 8, 12), False),
+ ],
+)
+def test_publish_activity_window_is_inclusive_start_exclusive_end(
+ monkeypatch: pytest.MonkeyPatch,
+ start: datetime | None,
+ end: datetime | None,
+ published_at: datetime,
+ expected: bool,
+) -> None:
+ monkeypatch.setattr(task_module.dify_config, "NEW_AGENT_BETA_ACTIVITY_START_AT", start)
+ monkeypatch.setattr(task_module.dify_config, "NEW_AGENT_BETA_ACTIVITY_END_AT", end)
+
+ assert task_module._is_publish_in_activity_window(published_at) is expected
+
+
+def test_broker_failure_does_not_propagate(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ ensure_new_agent_beta_participation_task,
+ "delay",
+ MagicMock(side_effect=RuntimeError("broker unavailable")),
+ )
+
+ schedule_new_agent_beta_ensure("revision-1")
+
+
+def test_task_calls_billing_with_revision_id(monkeypatch: pytest.MonkeyPatch) -> None:
+ ensure = MagicMock()
+ monkeypatch.setattr(BillingService, "ensure_new_agent_beta_revision", ensure)
+
+ ensure_new_agent_beta_participation_task.run("revision-1")
+
+ ensure.assert_called_once_with("revision-1")
+
+
+def test_task_is_redelivered_when_worker_is_lost() -> None:
+ task = cast(_TaskWithQueue, ensure_new_agent_beta_participation_task)
+
+ assert task.queue == NEW_AGENT_BETA_QUEUE
+ assert ensure_new_agent_beta_participation_task.acks_late is True
+ assert ensure_new_agent_beta_participation_task.reject_on_worker_lost is True
+ assert ensure_new_agent_beta_participation_task.max_retries == 8
+
+
+def test_task_retries_billing_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+ error = RuntimeError("billing unavailable")
+ monkeypatch.setattr(BillingService, "ensure_new_agent_beta_revision", MagicMock(side_effect=error))
+ retry = MagicMock(side_effect=RuntimeError("retry scheduled"))
+ monkeypatch.setattr(ensure_new_agent_beta_participation_task, "retry", retry)
+
+ with pytest.raises(RuntimeError, match="retry scheduled"):
+ ensure_new_agent_beta_participation_task.run("revision-1")
+
+ retry.assert_called_once_with(exc=error, countdown=30)
+
+
+def test_task_caps_exponential_retry_delay(monkeypatch: pytest.MonkeyPatch) -> None:
+ error = RuntimeError("billing unavailable")
+ monkeypatch.setattr(BillingService, "ensure_new_agent_beta_revision", MagicMock(side_effect=error))
+ monkeypatch.setattr(ensure_new_agent_beta_participation_task.request, "retries", 7)
+ retry = MagicMock(side_effect=RuntimeError("retry scheduled"))
+ monkeypatch.setattr(ensure_new_agent_beta_participation_task, "retry", retry)
+
+ with pytest.raises(RuntimeError, match="retry scheduled"):
+ ensure_new_agent_beta_participation_task.run("revision-1")
+
+ retry.assert_called_once_with(exc=error, countdown=900)
+
+
+def test_billing_contract_uses_internal_ensure_endpoint(monkeypatch: pytest.MonkeyPatch) -> None:
+ send_request = MagicMock(return_value={"status": "issued"})
+ monkeypatch.setattr(BillingService, "_send_request", send_request)
+
+ BillingService.ensure_new_agent_beta_revision("revision-1")
+
+ send_request.assert_called_once_with(
+ "POST",
+ "/new-agent-beta/revisions/revision-1/ensure",
+ )