chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,334 @@
|
||||
import importlib.util
|
||||
import sqlite3
|
||||
import sys
|
||||
from collections.abc import Callable, Iterator
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import Connection, create_engine, event, select
|
||||
from sqlalchemy.orm import ORMExecuteState, Session, sessionmaker
|
||||
from sqlalchemy.pool import ConnectionPoolEntry
|
||||
|
||||
from graphon.entities.pause_reason import PauseReasonType
|
||||
from graphon.enums import WorkflowExecutionStatus, WorkflowNodeExecutionStatus
|
||||
from graphon.file import FileTransferMethod, FileType
|
||||
from models.base import Base
|
||||
from models.enums import (
|
||||
AppTriggerType,
|
||||
ConversationFromSource,
|
||||
CreatorUserRole,
|
||||
ExecutionOffLoadType,
|
||||
FeedbackFromSource,
|
||||
FeedbackRating,
|
||||
MessageChainType,
|
||||
WorkflowRunTriggeredFrom,
|
||||
WorkflowTriggerStatus,
|
||||
)
|
||||
from models.model import (
|
||||
AppAnnotationHitHistory,
|
||||
AppMode,
|
||||
Conversation,
|
||||
DatasetRetrieverResource,
|
||||
Message,
|
||||
MessageAgentThought,
|
||||
MessageAnnotation,
|
||||
MessageChain,
|
||||
MessageFeedback,
|
||||
MessageFile,
|
||||
)
|
||||
from models.trigger import WorkflowTriggerLog
|
||||
from models.web import SavedMessage
|
||||
from models.workflow import (
|
||||
ConversationVariable,
|
||||
WorkflowAppLog,
|
||||
WorkflowAppLogCreatedFrom,
|
||||
WorkflowNodeExecutionModel,
|
||||
WorkflowNodeExecutionOffload,
|
||||
WorkflowNodeExecutionTriggeredFrom,
|
||||
WorkflowPause,
|
||||
WorkflowPauseReason,
|
||||
WorkflowRun,
|
||||
WorkflowType,
|
||||
)
|
||||
from repositories.factory import DifyAPIRepositoryFactory
|
||||
|
||||
TABLES = [
|
||||
Base.metadata.tables[model.__tablename__]
|
||||
for model in (
|
||||
Conversation,
|
||||
Message,
|
||||
AppAnnotationHitHistory,
|
||||
DatasetRetrieverResource,
|
||||
MessageAgentThought,
|
||||
MessageChain,
|
||||
MessageFile,
|
||||
MessageAnnotation,
|
||||
MessageFeedback,
|
||||
SavedMessage,
|
||||
ConversationVariable,
|
||||
WorkflowRun,
|
||||
WorkflowNodeExecutionModel,
|
||||
WorkflowNodeExecutionOffload,
|
||||
WorkflowAppLog,
|
||||
WorkflowPause,
|
||||
WorkflowPauseReason,
|
||||
WorkflowTriggerLog,
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
class _CeleryStub:
|
||||
def task(self, *_args: object, **_kwargs: object) -> Callable[[Callable[..., object]], Callable[..., object]]:
|
||||
def decorator(func: Callable[..., object]) -> Callable[..., object]:
|
||||
return func
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
class _AppStub(ModuleType):
|
||||
celery = _CeleryStub()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cleanup_module(monkeypatch: pytest.MonkeyPatch) -> ModuleType:
|
||||
# Load a private copy so the Celery stub cannot leak through the schedule package's import cache.
|
||||
path = Path(__file__).resolve().parents[3] / "schedule" / "clean_workflow_runlogs_precise.py"
|
||||
spec = importlib.util.spec_from_file_location("_test_clean_workflow_runlogs_precise", path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setitem(sys.modules, "app", _AppStub("app"))
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session_maker() -> Iterator[sessionmaker[Session]]:
|
||||
engine = create_engine("sqlite:///:memory:")
|
||||
|
||||
@event.listens_for(engine, "connect")
|
||||
def configure_sqlite(connection: sqlite3.Connection, _record: ConnectionPoolEntry) -> None:
|
||||
connection.isolation_level = None
|
||||
connection.execute("PRAGMA foreign_keys=ON")
|
||||
|
||||
@event.listens_for(engine, "begin")
|
||||
def begin_transaction(connection: Connection) -> None:
|
||||
# Python 3.12's SQLite legacy mode otherwise releases a savepoint outside the outer transaction.
|
||||
connection.exec_driver_sql("BEGIN")
|
||||
|
||||
try:
|
||||
Base.metadata.create_all(engine, tables=TABLES)
|
||||
yield sessionmaker(bind=engine, expire_on_commit=False)
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def _seed_batch(session: Session) -> WorkflowRun:
|
||||
tenant_id, app_id, workflow_id, user_id = (str(uuid4()) for _ in range(4))
|
||||
run_id, conversation_id, message_id, node_execution_id = (str(uuid4()) for _ in range(4))
|
||||
run = WorkflowRun(
|
||||
id=run_id,
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
workflow_id=workflow_id,
|
||||
type=WorkflowType.CHAT,
|
||||
triggered_from=WorkflowRunTriggeredFrom.APP_RUN,
|
||||
version="1",
|
||||
status=WorkflowExecutionStatus.SUCCEEDED,
|
||||
created_by_role=CreatorUserRole.ACCOUNT,
|
||||
created_by=user_id,
|
||||
)
|
||||
conversation = Conversation(
|
||||
id=conversation_id,
|
||||
app_id=app_id,
|
||||
mode=AppMode.ADVANCED_CHAT,
|
||||
name="cleanup test",
|
||||
_inputs={},
|
||||
from_source=ConversationFromSource.CONSOLE,
|
||||
)
|
||||
session.add_all([run, conversation])
|
||||
session.flush()
|
||||
pause = WorkflowPause(workflow_id=workflow_id, workflow_run_id=run_id, state_object_key="pause-state")
|
||||
annotation = MessageAnnotation(
|
||||
app_id=app_id,
|
||||
question="question",
|
||||
content="answer",
|
||||
account_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
message_id=message_id,
|
||||
)
|
||||
session.add_all(
|
||||
[
|
||||
Message(
|
||||
id=message_id,
|
||||
app_id=app_id,
|
||||
conversation_id=conversation_id,
|
||||
workflow_run_id=run_id,
|
||||
_inputs={},
|
||||
query="question",
|
||||
message={},
|
||||
answer="answer",
|
||||
message_unit_price=Decimal(0),
|
||||
answer_unit_price=Decimal(0),
|
||||
currency="USD",
|
||||
from_source=ConversationFromSource.CONSOLE,
|
||||
),
|
||||
annotation,
|
||||
AppAnnotationHitHistory(
|
||||
app_id=app_id,
|
||||
annotation_id=annotation.id,
|
||||
source="api",
|
||||
question="question",
|
||||
account_id=user_id,
|
||||
score=1.0,
|
||||
message_id=message_id,
|
||||
annotation_question="question",
|
||||
annotation_content="answer",
|
||||
),
|
||||
DatasetRetrieverResource(
|
||||
message_id=message_id,
|
||||
position=1,
|
||||
dataset_id=str(uuid4()),
|
||||
dataset_name="dataset",
|
||||
document_id=None,
|
||||
document_name="document",
|
||||
data_source_type=None,
|
||||
segment_id=None,
|
||||
score=None,
|
||||
content="content",
|
||||
hit_count=None,
|
||||
word_count=None,
|
||||
segment_position=None,
|
||||
index_node_hash=None,
|
||||
retriever_from="dev",
|
||||
created_by=user_id,
|
||||
),
|
||||
MessageAgentThought(
|
||||
message_id=message_id,
|
||||
position=1,
|
||||
created_by_role=CreatorUserRole.ACCOUNT,
|
||||
created_by=user_id,
|
||||
),
|
||||
MessageChain(message_id=message_id, type=MessageChainType.SYSTEM, input=None, output=None),
|
||||
MessageFile(
|
||||
message_id=message_id,
|
||||
type=FileType.IMAGE,
|
||||
transfer_method=FileTransferMethod.REMOTE_URL,
|
||||
created_by_role=CreatorUserRole.ACCOUNT,
|
||||
created_by=user_id,
|
||||
),
|
||||
MessageFeedback(
|
||||
app_id=app_id,
|
||||
conversation_id=conversation_id,
|
||||
message_id=message_id,
|
||||
rating=FeedbackRating.LIKE,
|
||||
from_source=FeedbackFromSource.ADMIN,
|
||||
),
|
||||
SavedMessage(
|
||||
app_id=app_id,
|
||||
message_id=message_id,
|
||||
created_by_role=CreatorUserRole.ACCOUNT,
|
||||
created_by=user_id,
|
||||
),
|
||||
ConversationVariable(id=str(uuid4()), conversation_id=conversation_id, app_id=app_id, data="{}"),
|
||||
WorkflowNodeExecutionModel(
|
||||
id=node_execution_id,
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
workflow_id=workflow_id,
|
||||
triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
|
||||
workflow_run_id=run_id,
|
||||
index=1,
|
||||
node_id="start",
|
||||
node_type="start",
|
||||
title="Start",
|
||||
status=WorkflowNodeExecutionStatus.SUCCEEDED,
|
||||
created_by_role=CreatorUserRole.ACCOUNT,
|
||||
created_by=user_id,
|
||||
),
|
||||
WorkflowNodeExecutionOffload(
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
node_execution_id=node_execution_id,
|
||||
type_=ExecutionOffLoadType.INPUTS,
|
||||
file_id=str(uuid4()),
|
||||
),
|
||||
WorkflowAppLog(
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
workflow_id=workflow_id,
|
||||
workflow_run_id=run_id,
|
||||
created_from=WorkflowAppLogCreatedFrom.SERVICE_API,
|
||||
created_by_role=CreatorUserRole.ACCOUNT,
|
||||
created_by=user_id,
|
||||
),
|
||||
pause,
|
||||
WorkflowPauseReason(pause_id=pause.id, type_=PauseReasonType.SCHEDULED_PAUSE),
|
||||
WorkflowTriggerLog(
|
||||
tenant_id=tenant_id,
|
||||
app_id=app_id,
|
||||
workflow_id=workflow_id,
|
||||
workflow_run_id=run_id,
|
||||
root_node_id=None,
|
||||
trigger_metadata="{}",
|
||||
trigger_type=AppTriggerType.TRIGGER_SCHEDULE,
|
||||
trigger_data="{}",
|
||||
inputs="{}",
|
||||
outputs=None,
|
||||
status=WorkflowTriggerStatus.SUCCEEDED,
|
||||
error=None,
|
||||
queue_name="workflow",
|
||||
celery_task_id=None,
|
||||
created_by_role=CreatorUserRole.ACCOUNT,
|
||||
created_by=user_id,
|
||||
),
|
||||
]
|
||||
)
|
||||
session.flush()
|
||||
return run
|
||||
|
||||
|
||||
def _row_ids(session: Session) -> dict[str, set[str]]:
|
||||
return {table.name: set(session.scalars(select(table.c.id))) for table in TABLES}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("outcome", ["commit", "rollback", "failure"])
|
||||
def test_delete_batch_keeps_cascade_in_caller_transaction(
|
||||
cleanup_module: ModuleType,
|
||||
session_maker: sessionmaker[Session],
|
||||
outcome: str,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
with session_maker.begin() as session:
|
||||
_seed_batch(session)
|
||||
retained_rows = _row_ids(session)
|
||||
run = _seed_batch(session)
|
||||
original_rows = _row_ids(session)
|
||||
|
||||
repository = DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_maker)
|
||||
with session_maker() as session:
|
||||
if outcome == "failure":
|
||||
|
||||
@event.listens_for(session, "do_orm_execute")
|
||||
def fail_run_deletion(state: ORMExecuteState) -> None:
|
||||
if state.is_delete and state.bind_mapper is not None and state.bind_mapper.class_ is WorkflowRun:
|
||||
raise RuntimeError("Fail after deleting related rows")
|
||||
|
||||
assert cleanup_module._delete_batch(session, repository, [run], attempt_count=0) is (outcome != "failure")
|
||||
assert session.in_transaction()
|
||||
assert not session.in_nested_transaction()
|
||||
assert _row_ids(session) == (original_rows if outcome == "failure" else retained_rows)
|
||||
if outcome == "failure":
|
||||
assert "Fail after deleting related rows" in caplog.text
|
||||
|
||||
if outcome == "rollback":
|
||||
session.rollback()
|
||||
else:
|
||||
session.commit()
|
||||
|
||||
with session_maker() as session:
|
||||
assert _row_ids(session) == (retained_rows if outcome == "commit" else original_rows)
|
||||
@@ -0,0 +1,179 @@
|
||||
"""The scheduled collector reuses existing Celery workers and bounded HTTP."""
|
||||
|
||||
from collections.abc import Iterator
|
||||
from datetime import timedelta
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from celery.contrib.testing.app import setup_default_app
|
||||
|
||||
from configs.extra.agent_backend_config import AgentBackendConfig
|
||||
from dify_app import DifyApp
|
||||
from extensions import ext_celery
|
||||
from schedule.collect_agent_sandbox_usage import collect_agent_sandbox_usage
|
||||
from tests.helpers.unit.config_override import config_overrides_context
|
||||
|
||||
PROJECT = "431de237-596f-4d59-8a85-20a9846bf243"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def restore_celery_app_state() -> Iterator[None]:
|
||||
# init_app changes Celery's process-wide current/default app; close() alone
|
||||
# leaves later shared tasks pointing at the now-unregistered test app.
|
||||
with setup_default_app(collect_agent_sandbox_usage.app):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def configured_collection() -> Iterator[None]:
|
||||
with config_overrides_context(
|
||||
AGENT_SANDBOX_METERING_ENABLED=True,
|
||||
AGENT_SANDBOX_METERING_PROJECT_ID=PROJECT,
|
||||
AGENT_BACKEND_BASE_URL="http://agent_backend:5001/",
|
||||
AGENT_BACKEND_API_TOKEN="backend-token",
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
def response(payload: object, status: int = 200) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
status, json=payload, request=httpx.Request("POST", "http://agent_backend:5001/internal/e2b/usage/collect")
|
||||
)
|
||||
|
||||
|
||||
def test_task_uses_configured_routing_deadlines_and_single_authenticated_call(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
post = MagicMock(return_value=response({"completed": True}))
|
||||
monkeypatch.setattr("schedule.collect_agent_sandbox_usage.ssrf_proxy.post", post)
|
||||
assert collect_agent_sandbox_usage() is True
|
||||
post.assert_called_once_with(
|
||||
"http://agent_backend:5001/internal/e2b/usage/collect",
|
||||
headers={"Authorization": "Bearer backend-token"},
|
||||
json={"project_id": PROJECT},
|
||||
max_retries=0,
|
||||
timeout=260,
|
||||
)
|
||||
dispatch = MagicMock()
|
||||
monkeypatch.setattr(collect_agent_sandbox_usage.app, "send_task", dispatch)
|
||||
collect_agent_sandbox_usage.apply_async()
|
||||
assert dispatch.call_args.kwargs.get("queue") is None
|
||||
assert collect_agent_sandbox_usage.soft_time_limit == 270
|
||||
assert collect_agent_sandbox_usage.time_limit == 300
|
||||
|
||||
|
||||
def test_disabled_job_makes_no_http_request(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
post = MagicMock()
|
||||
monkeypatch.setattr("schedule.collect_agent_sandbox_usage.ssrf_proxy.post", post)
|
||||
with config_overrides_context(AGENT_SANDBOX_METERING_ENABLED=False):
|
||||
assert collect_agent_sandbox_usage() is False
|
||||
post.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"missing", ["AGENT_BACKEND_BASE_URL", "AGENT_BACKEND_API_TOKEN", "AGENT_SANDBOX_METERING_PROJECT_ID"]
|
||||
)
|
||||
def test_incomplete_configuration_only_fails_collection_job(missing: str, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
post = MagicMock()
|
||||
monkeypatch.setattr("schedule.collect_agent_sandbox_usage.ssrf_proxy.post", post)
|
||||
with config_overrides_context(**{missing: ""}):
|
||||
with pytest.raises(ValueError, match="requires backend URL, token, and project"):
|
||||
collect_agent_sandbox_usage()
|
||||
post.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [{"completed": False}, {"completed": "true"}, {"unexpected": True}])
|
||||
def test_incomplete_or_invalid_scan_is_a_job_failure_without_retry(
|
||||
payload: dict[str, object], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
post = MagicMock(return_value=response(payload))
|
||||
monkeypatch.setattr("schedule.collect_agent_sandbox_usage.ssrf_proxy.post", post)
|
||||
with pytest.raises((ValueError, RuntimeError)):
|
||||
collect_agent_sandbox_usage()
|
||||
assert post.call_count == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [403, 503, 504])
|
||||
def test_backend_failure_does_not_trigger_http_retry(status: int, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
post = MagicMock(return_value=response({"detail": "unavailable"}, status))
|
||||
monkeypatch.setattr("schedule.collect_agent_sandbox_usage.ssrf_proxy.post", post)
|
||||
with pytest.raises(httpx.HTTPStatusError):
|
||||
collect_agent_sandbox_usage()
|
||||
assert post.call_count == 1
|
||||
|
||||
|
||||
def test_transport_failure_is_logged_without_credentials_or_raw_message(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
post = MagicMock(side_effect=httpx.ReadTimeout("do-not-log-secret"))
|
||||
monkeypatch.setattr("schedule.collect_agent_sandbox_usage.ssrf_proxy.post", post)
|
||||
with pytest.raises(httpx.ReadTimeout):
|
||||
collect_agent_sandbox_usage()
|
||||
assert post.call_count == 1
|
||||
assert "Background sandbox usage collection failed" in caplog.text
|
||||
assert "do-not-log-secret" not in caplog.text
|
||||
assert "backend-token" not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled", [False, True])
|
||||
@pytest.mark.parametrize("interval", [90, "90"])
|
||||
def test_beat_registers_only_enabled_collection_with_expiring_schedule(
|
||||
enabled: bool, interval: int | str, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(ext_celery, "setup_workflow_warm_shutdown_handler", lambda: None)
|
||||
with config_overrides_context(
|
||||
AGENT_SANDBOX_METERING_ENABLED=enabled,
|
||||
AGENT_SANDBOX_METERING_INTERVAL_SECONDS=interval,
|
||||
DISABLE_TELEMETRY=True,
|
||||
):
|
||||
celery = ext_celery.init_app(DifyApp(__name__))
|
||||
try:
|
||||
assert "schedule.collect_agent_sandbox_usage" in celery.conf.imports
|
||||
schedule = celery.conf.beat_schedule.get("collect_agent_sandbox_usage")
|
||||
if enabled:
|
||||
assert schedule == {
|
||||
"task": "schedule.collect_agent_sandbox_usage.collect_agent_sandbox_usage",
|
||||
"schedule": timedelta(seconds=90),
|
||||
"options": {"expires": 90},
|
||||
}
|
||||
else:
|
||||
assert schedule is None
|
||||
finally:
|
||||
celery.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw_interval", ["0", "-1", "not-a-number", "1.5", "9" * 30])
|
||||
def test_invalid_interval_env_only_disables_optional_schedule(
|
||||
raw_interval: str, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
monkeypatch.setenv("AGENT_SANDBOX_METERING_INTERVAL_SECONDS", raw_interval)
|
||||
config = AgentBackendConfig()
|
||||
assert raw_interval == config.AGENT_SANDBOX_METERING_INTERVAL_SECONDS
|
||||
monkeypatch.setattr(ext_celery, "setup_workflow_warm_shutdown_handler", lambda: None)
|
||||
with config_overrides_context(
|
||||
AGENT_SANDBOX_METERING_INTERVAL_SECONDS=config.AGENT_SANDBOX_METERING_INTERVAL_SECONDS,
|
||||
ENABLE_CONVERSATION_CLEANUP_TASK=True,
|
||||
CONVERSATION_CLEANUP_TASK_INTERVAL=2,
|
||||
DISABLE_TELEMETRY=True,
|
||||
):
|
||||
app = DifyApp(__name__)
|
||||
celery = ext_celery.init_app(app)
|
||||
try:
|
||||
assert app.extensions["celery"] is celery
|
||||
assert "collect_agent_sandbox_usage" not in celery.conf.beat_schedule
|
||||
assert "schedule.collect_agent_sandbox_usage" in celery.conf.imports
|
||||
assert celery.conf.beat_schedule["conversation_cleanup_sweeper"] == {
|
||||
"task": "tasks.delete_conversation_task.sweep_deleted_conversations",
|
||||
"schedule": timedelta(minutes=2),
|
||||
}
|
||||
finally:
|
||||
celery.close()
|
||||
assert "Skipping sandbox usage schedule" in caplog.text
|
||||
assert all(raw_interval not in record.getMessage() for record in caplog.records)
|
||||
|
||||
|
||||
def test_manual_collection_does_not_depend_on_beat_interval(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
post = MagicMock(return_value=response({"completed": True}))
|
||||
monkeypatch.setattr("schedule.collect_agent_sandbox_usage.ssrf_proxy.post", post)
|
||||
with config_overrides_context(AGENT_SANDBOX_METERING_INTERVAL_SECONDS="invalid"):
|
||||
assert collect_agent_sandbox_usage() is True
|
||||
post.assert_called_once()
|
||||
Reference in new issue
Block a user