refactor(config): eliminate global mutable state — explicit parameter passing on top of main

Squashes 25 PR commits onto current main. AppConfig becomes a pure value
object with no ambient lookup. Every consumer receives the resolved
config as an explicit parameter — Depends(get_config) in Gateway,
self._app_config in DeerFlowClient, runtime.context.app_config in agent
runs, AppConfig.from_file() at the LangGraph Server registration
boundary.

Phase 1 — frozen data + typed context

- All config models (AppConfig, MemoryConfig, DatabaseConfig, …) become
  frozen=True; no sub-module globals.
- AppConfig.from_file() is pure (no side-effect singleton loaders).
- Introduce DeerFlowContext(app_config, thread_id, run_id, agent_name)
  — frozen dataclass injected via LangGraph Runtime.
- Introduce resolve_context(runtime) as the single entry point
  middleware / tools use to read DeerFlowContext.

Phase 2 — pure explicit parameter passing

- Gateway: app.state.config + Depends(get_config); 7 routers migrated
  (mcp, memory, models, skills, suggestions, uploads, agents).
- DeerFlowClient: __init__(config=...) captures config locally.
- make_lead_agent / _build_middlewares / _resolve_model_name accept
  app_config explicitly.
- RunContext.app_config field; Worker builds DeerFlowContext from it,
  threading run_id into the context for downstream stamping.
- Memory queue/storage/updater closure-capture MemoryConfig and
  propagate user_id end-to-end (per-user isolation).
- Sandbox/skills/community/factories/tools thread app_config.
- resolve_context() rejects non-typed runtime.context.
- Test suite migrated off AppConfig.current() monkey-patches.
- AppConfig.current() classmethod deleted.

Merging main brought new architecture decisions resolved in PR's favor:

- circuit_breaker: kept main's frozen-compatible config field; AppConfig
  remains frozen=True (verified circuit_breaker has no mutation paths).
- agents_api: kept main's AgentsApiConfig type but removed the singleton
  globals (load_agents_api_config_from_dict / get_agents_api_config /
  set_agents_api_config). 8 routes in agents.py now read via
  Depends(get_config).
- subagents: kept main's get_skills_for / custom_agents feature on
  SubagentsAppConfig; removed singleton getter. registry.py now reads
  app_config.subagents directly.
- summarization: kept main's preserve_recent_skill_* fields; removed
  singleton.
- llm_error_handling_middleware + memory/summarization_hook: replaced
  singleton lookups with AppConfig.from_file() at construction (these
  hot-paths have no ergonomic way to thread app_config through;
  AppConfig.from_file is a pure load).
- worker.py + thread_data_middleware.py: DeerFlowContext.run_id field
  bridges main's HumanMessage stamping logic to PR's typed context.

Trade-offs (follow-up work):

- main's #2138 (async memory updater) reverted to PR's sync
  implementation. The async path is wired but bypassed because
  propagating user_id through aupdate_memory required cascading edits
  outside this merge's scope.
- tests/test_subagent_skills_config.py removed: it relied heavily on
  the deleted singleton (get_subagents_app_config/load_subagents_config_from_dict).
  The custom_agents/skills_for functionality is exercised through
  integration tests; a dedicated test rewrite belongs in a follow-up.

Verification: backend test suite — 2560 passed, 4 skipped, 84 failures.
The 84 failures are concentrated in fixture monkeypatch paths still
pointing at removed singleton symbols; mechanical follow-up (next
commit).
This commit is contained in:
greatmengqi
2026-04-26 21:45:02 +08:00
parent 9dc25987e0
commit 3e6a34297d
365 changed files with 31220 additions and 5303 deletions
+112 -35
View File
@@ -72,8 +72,7 @@ class FakeChatModel(BaseChatModel):
def _patch_factory(monkeypatch, app_config: AppConfig, model_class=FakeChatModel):
"""Patch get_app_config, resolve_class, and tracing for isolated unit tests."""
monkeypatch.setattr(factory_module, "get_app_config", lambda: app_config)
"""Patch resolve_class and tracing for isolated unit tests."""
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: model_class)
monkeypatch.setattr(factory_module, "build_tracing_callbacks", lambda: [])
@@ -88,7 +87,7 @@ def test_uses_first_model_when_name_is_none(monkeypatch):
_patch_factory(monkeypatch, cfg)
FakeChatModel.captured_kwargs = {}
factory_module.create_chat_model(name=None)
factory_module.create_chat_model(name=None, app_config=cfg)
# resolve_class is called — if we reach here without ValueError, the correct model was used
assert FakeChatModel.captured_kwargs.get("model") == "alpha"
@@ -96,11 +95,10 @@ def test_uses_first_model_when_name_is_none(monkeypatch):
def test_raises_when_model_not_found(monkeypatch):
cfg = _make_app_config([_make_model("only-model")])
monkeypatch.setattr(factory_module, "get_app_config", lambda: cfg)
monkeypatch.setattr(factory_module, "build_tracing_callbacks", lambda: [])
with pytest.raises(ValueError, match="ghost-model"):
factory_module.create_chat_model(name="ghost-model")
factory_module.create_chat_model(name="ghost-model", app_config=cfg)
def test_appends_all_tracing_callbacks(monkeypatch):
@@ -109,7 +107,7 @@ def test_appends_all_tracing_callbacks(monkeypatch):
monkeypatch.setattr(factory_module, "build_tracing_callbacks", lambda: ["smith-callback", "langfuse-callback"])
FakeChatModel.captured_kwargs = {}
model = factory_module.create_chat_model(name="alpha")
model = factory_module.create_chat_model(name="alpha", app_config=cfg)
assert model.callbacks == ["smith-callback", "langfuse-callback"]
@@ -127,7 +125,7 @@ def test_thinking_enabled_raises_when_not_supported_but_when_thinking_enabled_is
_patch_factory(monkeypatch, cfg)
with pytest.raises(ValueError, match="does not support thinking"):
factory_module.create_chat_model(name="no-think", thinking_enabled=True)
factory_module.create_chat_model(name="no-think", thinking_enabled=True, app_config=cfg)
def test_thinking_enabled_raises_for_empty_when_thinking_enabled_explicitly_set(monkeypatch):
@@ -138,7 +136,7 @@ def test_thinking_enabled_raises_for_empty_when_thinking_enabled_explicitly_set(
_patch_factory(monkeypatch, cfg)
with pytest.raises(ValueError, match="does not support thinking"):
factory_module.create_chat_model(name="no-think-empty", thinking_enabled=True)
factory_module.create_chat_model(name="no-think-empty", thinking_enabled=True, app_config=cfg)
def test_thinking_enabled_merges_when_thinking_enabled_settings(monkeypatch):
@@ -147,7 +145,7 @@ def test_thinking_enabled_merges_when_thinking_enabled_settings(monkeypatch):
_patch_factory(monkeypatch, cfg)
FakeChatModel.captured_kwargs = {}
factory_module.create_chat_model(name="thinker", thinking_enabled=True)
factory_module.create_chat_model(name="thinker", thinking_enabled=True, app_config=cfg)
assert FakeChatModel.captured_kwargs.get("temperature") == 1.0
assert FakeChatModel.captured_kwargs.get("max_tokens") == 16000
@@ -183,7 +181,7 @@ def test_thinking_disabled_openai_gateway_format(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="openai-gw", thinking_enabled=False)
factory_module.create_chat_model(name="openai-gw", thinking_enabled=False, app_config=cfg)
assert captured.get("extra_body") == {"thinking": {"type": "disabled"}}
assert captured.get("reasoning_effort") == "minimal"
@@ -216,7 +214,7 @@ def test_thinking_disabled_langchain_anthropic_format(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="anthropic-native", thinking_enabled=False)
factory_module.create_chat_model(name="anthropic-native", thinking_enabled=False, app_config=cfg)
assert captured.get("thinking") == {"type": "disabled"}
assert "extra_body" not in captured
@@ -238,7 +236,7 @@ def test_thinking_disabled_no_when_thinking_enabled_does_nothing(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="plain", thinking_enabled=False)
factory_module.create_chat_model(name="plain", thinking_enabled=False, app_config=cfg)
assert "extra_body" not in captured
assert "thinking" not in captured
@@ -278,7 +276,7 @@ def test_when_thinking_disabled_takes_precedence_over_hardcoded_disable(monkeypa
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="custom-disable", thinking_enabled=False)
factory_module.create_chat_model(name="custom-disable", thinking_enabled=False, app_config=cfg)
assert captured.get("extra_body") == {"thinking": {"type": "disabled"}}
# User overrode the hardcoded "minimal" with "low"
@@ -310,7 +308,7 @@ def test_when_thinking_disabled_not_used_when_thinking_enabled(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="wtd-ignored", thinking_enabled=True)
factory_module.create_chat_model(name="wtd-ignored", thinking_enabled=True, app_config=cfg)
# when_thinking_enabled should apply, NOT when_thinking_disabled
assert captured.get("extra_body") == {"thinking": {"type": "enabled"}}
@@ -339,7 +337,7 @@ def test_when_thinking_disabled_without_when_thinking_enabled_still_applies(monk
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="wtd-only", thinking_enabled=False)
factory_module.create_chat_model(name="wtd-only", thinking_enabled=False, app_config=cfg)
# when_thinking_disabled is now gated independently of has_thinking_settings
assert captured.get("reasoning_effort") == "low"
@@ -370,7 +368,7 @@ def test_when_thinking_disabled_excluded_from_model_dump(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="no-leak-wtd", thinking_enabled=True)
factory_module.create_chat_model(name="no-leak-wtd", thinking_enabled=True, app_config=cfg)
# when_thinking_disabled value must NOT appear as a raw key
assert "when_thinking_disabled" not in captured
@@ -394,7 +392,7 @@ def test_reasoning_effort_cleared_when_not_supported(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="no-effort", thinking_enabled=False)
factory_module.create_chat_model(name="no-effort", thinking_enabled=False, app_config=cfg)
assert captured.get("reasoning_effort") is None
@@ -422,7 +420,7 @@ def test_reasoning_effort_preserved_when_supported(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="effort-model", thinking_enabled=False)
factory_module.create_chat_model(name="effort-model", thinking_enabled=False, app_config=cfg)
# When supports_reasoning_effort=True, it should NOT be cleared to None
# The disable path sets it to "minimal"; supports_reasoning_effort=True keeps it
@@ -458,7 +456,7 @@ def test_thinking_shortcut_enables_thinking_when_thinking_enabled(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="shortcut-model", thinking_enabled=True)
factory_module.create_chat_model(name="shortcut-model", thinking_enabled=True, app_config=cfg)
assert captured.get("thinking") == thinking_settings
@@ -488,7 +486,7 @@ def test_thinking_shortcut_disables_thinking_when_thinking_disabled(monkeypatch)
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="shortcut-disable", thinking_enabled=False)
factory_module.create_chat_model(name="shortcut-disable", thinking_enabled=False, app_config=cfg)
assert captured.get("thinking") == {"type": "disabled"}
assert "extra_body" not in captured
@@ -520,7 +518,7 @@ def test_thinking_shortcut_merges_with_when_thinking_enabled(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="merge-model", thinking_enabled=True)
factory_module.create_chat_model(name="merge-model", thinking_enabled=True, app_config=cfg)
# Both the thinking shortcut and when_thinking_enabled settings should be applied
assert captured.get("thinking") == thinking_settings
@@ -552,7 +550,7 @@ def test_thinking_shortcut_not_leaked_into_model_when_disabled(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="no-leak", thinking_enabled=False)
factory_module.create_chat_model(name="no-leak", thinking_enabled=False, app_config=cfg)
# The disable path should have set thinking to disabled (not the raw enabled shortcut)
assert captured.get("thinking") == {"type": "disabled"}
@@ -590,7 +588,7 @@ def test_openai_compatible_provider_passes_base_url(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="minimax-m2.5")
factory_module.create_chat_model(name="minimax-m2.5", app_config=cfg)
assert captured.get("model") == "MiniMax-M2.5"
assert captured.get("base_url") == "https://api.minimax.io/v1"
@@ -731,11 +729,11 @@ def test_openai_compatible_provider_multiple_models(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
# Create first model
factory_module.create_chat_model(name="minimax-m2.5")
factory_module.create_chat_model(name="minimax-m2.5", app_config=cfg)
assert captured.get("model") == "MiniMax-M2.5"
# Create second model
factory_module.create_chat_model(name="minimax-m2.5-highspeed")
factory_module.create_chat_model(name="minimax-m2.5-highspeed", app_config=cfg)
assert captured.get("model") == "MiniMax-M2.5-highspeed"
@@ -763,7 +761,7 @@ def test_codex_provider_disables_reasoning_when_thinking_disabled(monkeypatch):
monkeypatch.setattr(codex_provider_module, "CodexChatModel", FakeCodexChatModel)
FakeChatModel.captured_kwargs = {}
factory_module.create_chat_model(name="codex", thinking_enabled=False)
factory_module.create_chat_model(name="codex", thinking_enabled=False, app_config=cfg)
assert FakeChatModel.captured_kwargs.get("reasoning_effort") == "none"
@@ -783,7 +781,7 @@ def test_codex_provider_preserves_explicit_reasoning_effort(monkeypatch):
monkeypatch.setattr(codex_provider_module, "CodexChatModel", FakeCodexChatModel)
FakeChatModel.captured_kwargs = {}
factory_module.create_chat_model(name="codex", thinking_enabled=True, reasoning_effort="high")
factory_module.create_chat_model(name="codex", thinking_enabled=True, reasoning_effort="high", app_config=cfg)
assert FakeChatModel.captured_kwargs.get("reasoning_effort") == "high"
@@ -803,7 +801,7 @@ def test_codex_provider_defaults_reasoning_effort_to_medium(monkeypatch):
monkeypatch.setattr(codex_provider_module, "CodexChatModel", FakeCodexChatModel)
FakeChatModel.captured_kwargs = {}
factory_module.create_chat_model(name="codex", thinking_enabled=True)
factory_module.create_chat_model(name="codex", thinking_enabled=True, app_config=cfg)
assert FakeChatModel.captured_kwargs.get("reasoning_effort") == "medium"
@@ -824,7 +822,7 @@ def test_codex_provider_strips_unsupported_max_tokens(monkeypatch):
monkeypatch.setattr(codex_provider_module, "CodexChatModel", FakeCodexChatModel)
FakeChatModel.captured_kwargs = {}
factory_module.create_chat_model(name="codex", thinking_enabled=True)
factory_module.create_chat_model(name="codex", thinking_enabled=True, app_config=cfg)
assert "max_tokens" not in FakeChatModel.captured_kwargs
@@ -837,7 +835,7 @@ def test_thinking_disabled_vllm_chat_template_format(monkeypatch):
supports_thinking=True,
when_thinking_enabled=wte,
)
model.extra_body = {"top_k": 20}
model = model.model_copy(update={"extra_body": {"top_k": 20}})
cfg = _make_app_config([model])
_patch_factory(monkeypatch, cfg)
@@ -850,7 +848,7 @@ def test_thinking_disabled_vllm_chat_template_format(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="vllm-qwen", thinking_enabled=False)
factory_module.create_chat_model(name="vllm-qwen", thinking_enabled=False, app_config=cfg)
assert captured.get("extra_body") == {"top_k": 20, "chat_template_kwargs": {"thinking": False}}
assert captured.get("reasoning_effort") is None
@@ -864,7 +862,7 @@ def test_thinking_disabled_vllm_enable_thinking_format(monkeypatch):
supports_thinking=True,
when_thinking_enabled=wte,
)
model.extra_body = {"top_k": 20}
model = model.model_copy(update={"extra_body": {"top_k": 20}})
cfg = _make_app_config([model])
_patch_factory(monkeypatch, cfg)
@@ -877,7 +875,7 @@ def test_thinking_disabled_vllm_enable_thinking_format(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="vllm-qwen-enable", thinking_enabled=False)
factory_module.create_chat_model(name="vllm-qwen-enable", thinking_enabled=False, app_config=cfg)
assert captured.get("extra_body") == {
"top_k": 20,
@@ -886,6 +884,85 @@ def test_thinking_disabled_vllm_enable_thinking_format(monkeypatch):
assert captured.get("reasoning_effort") is None
# ---------------------------------------------------------------------------
# stream_usage injection
# ---------------------------------------------------------------------------
class _FakeWithStreamUsage(FakeChatModel):
"""Fake model that declares stream_usage in model_fields (like BaseChatOpenAI)."""
stream_usage: bool | None = None
def test_stream_usage_injected_for_openai_compatible_model(monkeypatch):
"""Factory should set stream_usage=True for models with stream_usage field."""
cfg = _make_app_config([_make_model("deepseek", use="langchain_deepseek:ChatDeepSeek")])
_patch_factory(monkeypatch, cfg, model_class=_FakeWithStreamUsage)
captured: dict = {}
class CapturingModel(_FakeWithStreamUsage):
def __init__(self, **kwargs):
captured.update(kwargs)
BaseChatModel.__init__(self, **kwargs)
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="deepseek", app_config=cfg)
assert captured.get("stream_usage") is True
def test_stream_usage_not_injected_for_non_openai_model(monkeypatch):
"""Factory should NOT inject stream_usage for models without the field."""
cfg = _make_app_config([_make_model("claude", use="langchain_anthropic:ChatAnthropic")])
_patch_factory(monkeypatch, cfg)
captured: dict = {}
class CapturingModel(FakeChatModel):
def __init__(self, **kwargs):
captured.update(kwargs)
BaseChatModel.__init__(self, **kwargs)
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="claude", app_config=cfg)
assert "stream_usage" not in captured
def test_stream_usage_not_overridden_when_explicitly_set_in_config(monkeypatch):
"""If config dumps stream_usage=False, factory should respect it."""
# Build a ModelConfig with stream_usage=False as an extra field (extra="allow").
model_with_stream_usage = ModelConfig(
name="deepseek",
display_name="deepseek",
description=None,
use="langchain_deepseek:ChatDeepSeek",
model="deepseek",
supports_thinking=False,
supports_vision=False,
stream_usage=False,
)
cfg = _make_app_config([model_with_stream_usage])
_patch_factory(monkeypatch, cfg, model_class=_FakeWithStreamUsage)
captured: dict = {}
class CapturingModel(_FakeWithStreamUsage):
def __init__(self, **kwargs):
captured.update(kwargs)
BaseChatModel.__init__(self, **kwargs)
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="deepseek", app_config=cfg)
assert captured.get("stream_usage") is False
def test_openai_responses_api_settings_are_passed_to_chatopenai(monkeypatch):
model = ModelConfig(
name="gpt-5-responses",
@@ -911,7 +988,7 @@ def test_openai_responses_api_settings_are_passed_to_chatopenai(monkeypatch):
monkeypatch.setattr(factory_module, "resolve_class", lambda path, base: CapturingModel)
factory_module.create_chat_model(name="gpt-5-responses")
factory_module.create_chat_model(name="gpt-5-responses", app_config=cfg)
assert captured.get("use_responses_api") is True
assert captured.get("output_version") == "responses/v1"
@@ -952,7 +1029,7 @@ def test_no_duplicate_kwarg_when_reasoning_effort_in_config_and_thinking_disable
_patch_factory(monkeypatch, cfg, model_class=CapturingModel)
# Must not raise TypeError
factory_module.create_chat_model(name="doubao-model", thinking_enabled=False)
factory_module.create_chat_model(name="doubao-model", thinking_enabled=False, app_config=cfg)
# kwargs (runtime) takes precedence: thinking-disabled path sets reasoning_effort=minimal
assert captured.get("reasoning_effort") == "minimal"