deer-flow/backend/tests/test_config_version.py
xiaodu55 64e499be98
feat(memory): redact queued memory payloads (pii_redaction follow-up) (#5577)
* feat(memory): redact queued memory payloads (pii_redaction follow-up)

Closes the remaining vector from #3190 (memory storage): request-scoped
redaction leaves originals in thread state, and MemoryMiddleware queued
that raw conversation into the durable extraction buffer — so the
extraction model's input and the persisted facts carried raw PII even
with pii_redaction.enabled.

- MemoryMiddleware gains pii_redaction_config (same pattern as
  summarization / durable-context / title); the payload returned by
  _resolve_add_args() is redacted at the enqueue boundary before
  add()/aadd(), covering both after_agent and aafter_agent
- Reuses the shared redact_text() seam from #5527 via
  active_pii_detectors/_Redactor/_redact_content; the buffered payload
  itself becomes clean, not just the extraction model's view
- Wired at the lead-agent assembly site
- Tests: queue-payload redaction enabled/disabled, detector toggles,
  message immutability, token stability across turns

* fix(memory): reserve existing placeholder indices across the queued batch

Review round 1 on #5577: thread state mixes raw user turns with
already-redacted tool results and summaries, so a token in a later
message must not collide with a new value in an earlier one. Pre-scan
the whole queued batch with redactor.reserve() before allocating.

Also extend the two MemoryMiddleware stubs in
test_lead_agent_model_resolution.py to accept the new
pii_redaction_config kwarg (CI backend-unit-tests red).

* fix(memory): redact the compaction-triggered memory_flush_hook queue too

Review round 2 on #5577: with memory + summarization enabled,
memory_flush_hook() queues list(event.messages_to_summarize) directly
into MemoryManager.add_nowait(), bypassing MemoryMiddleware entirely —
and compaction removes those messages from state right after, so the
after-agent redaction can never repair a raw batch queued there.

Extract the batch redaction (reserve pre-scan + rebuild) into a shared
redact_queued_messages() used by both MemoryMiddleware's enqueue
boundary and the hook; the hook gains an optional pii_redaction_config
wired via functools.partial at the summarization factory (subagents use
skip_memory_flush=True and are unaffected). Regression covers the hook
path enabled/disabled/absent.

* test(summarization): unwrap the partial in the factory hook identity check

edd916e wrapped memory_flush_hook in functools.partial to carry the
pii_redaction config, but missed committing the matching update to
test_factory_attaches_memory_flush_hook_by_default — a functools.partial
is not equal to its wrapped function, so the identity assertion failed
deterministically (caught by static review on #5577).

* fix(memory): cover tool-call arguments and lenient text blocks in queued payloads

Review round 4 on #5577 — two reproduced gaps still allowed raw PII into
memory payloads with pii_redaction.enabled=true:

- OpenViking retains the full message object, so parsed tool_calls args
  and provider-format arguments in additional_kwargs bypassed the
  content-only redaction; queued payloads now redact tool-call args
  recursively (and reserve them in the pre-scan).
- DeerMem's format_conversation_for_update reads p.get("text") of any
  dict block, not only type=="text" — _redact_content now redacts every
  string-valued text field so a lenient consumer cannot bypass it.

Both repro shapes are pinned as regressions.

* fix(pii): value-derived placeholders for stable capture identity

Review round 5 on #5577: sequential allocation is order-dependent — the
same unchanged message re-redacted in a later batch can get a different
token, which flips OpenViking's content-signature and replays already
recorded turns into persistent memory sessions. Placeholders are now a
pure function of the matched value (sha256-6 per category): identities
stay stable across batches, enqueues, seams, and backends with no shared
state and no stored mapping.

- _Redactor becomes stateless; the reserve machinery (index pre-scans,
  _PLACEHOLDER_PATTERN) is removed along with its call sites
- redact_texts keeps its signature, now a simple per-text redaction
- reserve-semantics tests are superseded by cross-enqueue identity tests
  (two successive captures where the second batch carries higher existing
  placeholders); the compiled-graph echo regex matches the new format

* fix(pii): 128-bit placeholder digests; redact tool-argument keys

Review round 6 on #5577:
- [P2] The 24-bit truncation collided distinct identities (reproduced:
  contact3513@ / contact3727@example.com both rendered [EMAIL_575dbb]).
  Retain 128 bits of the digest so separate people stay separate at any
  realistic volume; the compiled-graph echo regex and the AGENTS.md entry
  follow the new format.
- [P2] _redact_strings redacted values but preserved mapping keys, so
  {"contacts": {"alice@example.com": "manager"}} kept the raw email
  as a key. Redact string keys along with values; deterministic 128-bit
  tokens make distinct-key collisions a hash-collision non-event, and a
  redacted key equal to another key merges the entries. Regression pins
  the email-keyed arguments shape.

* docs(agents): trim PiiRedactionMiddleware entry; drop stale reserve wording

The chain grew past the 98304-byte AG002 hard limit again (main growth
plus the round-6 format example). Trim the entry to fit, and replace the
stale reserve-indices wording with the value-derived semantics that
replaced it.

* docs(agents): shrink PiiRedactionMiddleware entry below the chain budget

main moved (#5609) and the base comparison flipped the nearly-over chain
back to an AG002 error (98441 > 98304). Trim the entry to the facts that
are not documented elsewhere: seams, allowlist, order, enqueue boundary.

* fix(pii): letters-only value-derived tokens; wire the factory SDK path

Review round 7 on #5577:
- [P2] Hex digests carry digit runs that later digit-anchored detectors
  re-scan, corrupting minted tokens into nested placeholders (reproduced:
  user280@example.com -> [EMAIL_…[PHONE_…]…], ~1/140 emails). The 128-bit
  digest is now encoded over a-z, so a minted token survives the full
  pinned detector order.
- [P2] create_deerflow_agent (the SDK path) constructed MemoryMiddleware
  and DurableContextMiddleware without pii_redaction_config; the knob is
  now an explicit optional parameter threaded through
  _assemble_from_features (the factory reads no config files by design,
  so SDK callers pass it explicitly).
- [Nit] hoist the Command rebuild comprehension out of the per-message
  loop in _redact_result.
- [Nit] drop the dead _iter_tool_calls helper and Iterator import.

* test(factory): pin pii_redaction_config wiring; document the parameter

Review round 8 on #5577:
- [P3] test_create_deerflow_agent.py had zero coverage of the
  pii_redaction_config parameter; two regressions now assert that
  create_deerflow_agent(pii_redaction_config=cfg) builds a
  MemoryMiddleware and a DurableContextMiddleware carrying cfg, and that
  the default is None (redaction off).
- [Nit] document the parameter in the create_deerflow_agent docstring:
  None leaves redaction off; a middleware= takeover bypasses the
  assembly that would apply it.

* fix(pii): HMAC-scoped placeholder tokens; install model-bound redaction in the SDK chain

Review round 10 on #5577:
- [P2] sha256(category||value) is an unkeyed, globally deterministic
  fingerprint: a provider or memory backend can confirm candidate values
  offline and link identical values across users and threads, contradicting
  the documented no-re-identification guarantee. Placeholders are now
  HMAC-derived over a deployment-scoped token_secret (new config field);
  the docstring documents the linkability scope for both modes.
- [P2] _assemble_from_features() never appended PiiRedactionMiddleware, so
  the SDK knob enabled only the downstream seams while the primary model
  still received raw content. The middleware is now appended in the same
  relative position as the lead-agent base chain when the gate is on,
  with a model-call regression through the assembled SDK chain.

* docs(pii): document token_secret; update the placeholder format examples

Follow-up to the round-10 review on #5577:
- config.example.yaml documents the new token_secret knob: a
  deployment-scoped secret makes placeholders HMAC-derived and only
  linkable within one deployment; leaving it unset keeps publicly
  computable fingerprints (documented trade).
- the PiiRedactionConfig class docstring's placeholder example now
  matches the shipped format (128-bit HMAC digests over base-26
  letters).

* docs(pii): update the module docstring's placeholder format example

The module docstring still showed the sequential [EMAIL_1] example;
align it with the shipped value-derived format (128-bit HMAC digests
over base-26 letters).

* fix(pii): require a non-empty token_secret when redaction is enabled

Review round 11 on #5577: with the secret optional, the default enabled
configuration minted empty-key HMAC digests — publicly computable, globally
linkable fingerprints of the raw values, confirmable by offline guessing for
low-entropy identifiers such as phone numbers.

- PiiRedactionConfig now rejects enabled=true without a non-empty
  token_secret (minimum 16 characters); the unkeyed mode is gone entirely.
- The request-scoped redactor in _process_request now carries the configured
  key: it built its redactor without it, so user-message placeholders
  silently diverged from every other seam for the same value. The empty-key
  guard in _placeholder_token is the backstop that keeps every path keyed.
- Module/config docstrings and config.example.yaml no longer describe the
  placeholders as irreversible or the secret as optional; the stale
  reserve-semantics wording and the "memory path not covered" note are
  corrected.
- Regressions: validation errors for missing/blank/short secrets, and the
  user-message boundary minting the same keyed token as redact_text.

* fix(memory): redact original_user_content on queued memory payloads

Review round 12 on #5577: UploadsMiddleware preserves the raw user turn in
additional_kwargs.original_user_content, but redact_queued_messages rewrote
only content, tool_calls, and provider-format tool_calls — the queued copy
still carried the raw value, so the memory queue and backend received raw PII
with redaction enabled.

The shared helper now redacts the provenance string field on the queued copy
(same batch redactor, merged with the existing additional_kwargs rewrite,
rebuilt via model_copy — thread-state messages stay untouched), covering both
the enqueue boundary and the compaction flush hook. Regressions pin the
redacted provenance field through both paths and the untouched original.

* fix(memory): redact human_input_response on queued memory payloads

Review round 13 on #5577: clarification replies keep the raw user answer in
additional_kwargs.human_input_response.value (DeerMem reads that mapping via
its read_human_input_response mirror), but redact_queued_messages rewrote
only content, tool_calls, and original_user_content — the queued copy still
carried the raw value into the memory queue and backend.

The shared helper now rebuilds that mapping with value redacted (same batch
redactor) while preserving the protocol fields (version/kind/source/
request_id/option_id/response_kind), merged with the existing
additional_kwargs rewrite and rebuilt via model_copy so thread-state
messages stay untouched. Regressions pin the redacted value, preserved
protocol fields, the untouched original, and the flush-hook path.

* chore(config): bump config_version to 47; generate token_secret on upgrade

Review round 13 on #5577: existing deployments can legitimately sit at
config_version 46 with pii_redaction.enabled: true and no token_secret; the
mandatory-secret validator would fail their startup while config.example.yaml
still said 46, so the upgrade checker considered them current and emitted no
migration warning.

- Bump config_version to 47 so the outdated-config warning fires for v46.
- Add a v47 migration to scripts/config-upgrade.sh: when pii_redaction is
  enabled and token_secret is missing/blank, generate a random deployment-
  scoped secret (secrets.token_urlsafe) and persist it, so the upgraded
  deployment starts under the mandatory validation.
- Regressions: a v46 enabled config is flagged outdated against the real
  example; the upgrade run generates a >= 16-char secret and the result
  passes AppConfig validation; a disabled config gets no secret.
- Also switch the two v41 script tests from a hardcoded "bash" to
  SCRIPT_BASH/skipif, matching the documented Windows constraint and the
  neighboring tests (hardcoded bash resolves to the WSL stub there).

* chore(helm): sync chart config_version to 47

Review round 14 on #5577: check_config_version.sh fails whenever the chart's
embedded config_version lags config.example.yaml, and the chart workflow is
triggered by config.example.yaml — so the v47 bump left this head failing
that check. Update the values.yaml config block and the README example to
47; scripts/check_config_version.sh now passes.

---------

Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
2026-09-25 20:05:36 +08:00

628 lines
24 KiB
Python

"""Tests for config version check and upgrade logic."""
from __future__ import annotations
import logging
import os
import tempfile
from pathlib import Path
import pytest
import yaml
from support.shell import find_script_bash
from deerflow.config.app_config import AppConfig
from deerflow.config.knowledge_base_config import KnowledgeBaseConfig
from deerflow.tools.tools import get_available_tools
def test_knowledge_base_config_is_provider_agnostic() -> None:
assert set(KnowledgeBaseConfig.model_fields) == {"enabled", "scope_selection_enabled"}
config = KnowledgeBaseConfig.model_validate(
{
"enabled": True,
"scope_selection_enabled": True,
"base_url": "http://legacy-ragflow.test",
"api_key": "legacy-secret",
}
)
assert config.model_dump() == {"enabled": True, "scope_selection_enabled": True}
# Only the upgrade-script test shells out; it needs Git Bash on Windows (the
# WSL launcher and Store alias stubs cannot run the repo scripts).
SCRIPT_BASH = find_script_bash()
def _make_config_files(tmpdir: Path, user_config: dict, example_config: dict) -> Path:
"""Write user config.yaml and config.example.yaml to a temp dir, return config path."""
config_path = tmpdir / "config.yaml"
example_path = tmpdir / "config.example.yaml"
# Minimal valid config needs sandbox
defaults = {
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
}
for cfg in (user_config, example_config):
for k, v in defaults.items():
cfg.setdefault(k, v)
with open(config_path, "w", encoding="utf-8") as f:
yaml.dump(user_config, f)
with open(example_path, "w", encoding="utf-8") as f:
yaml.dump(example_config, f)
return config_path
def test_missing_version_treated_as_zero(caplog):
"""Config without config_version should be treated as version 0."""
with tempfile.TemporaryDirectory() as tmpdir:
config_path = _make_config_files(
Path(tmpdir),
user_config={}, # no config_version
example_config={"config_version": 1},
)
with caplog.at_level(logging.WARNING, logger="deerflow.config.app_config"):
AppConfig._check_config_version(
{"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"}},
config_path,
)
assert "outdated" in caplog.text
assert "version 0" in caplog.text
assert "version is 1" in caplog.text
def test_matching_version_no_warning(caplog):
"""Config with matching version should not emit a warning."""
with tempfile.TemporaryDirectory() as tmpdir:
config_path = _make_config_files(
Path(tmpdir),
user_config={"config_version": 1},
example_config={"config_version": 1},
)
with caplog.at_level(logging.WARNING, logger="deerflow.config.app_config"):
AppConfig._check_config_version(
{"config_version": 1},
config_path,
)
assert "outdated" not in caplog.text
def test_outdated_version_emits_warning(caplog):
"""Config with lower version should emit a warning."""
with tempfile.TemporaryDirectory() as tmpdir:
config_path = _make_config_files(
Path(tmpdir),
user_config={"config_version": 1},
example_config={"config_version": 2},
)
with caplog.at_level(logging.WARNING, logger="deerflow.config.app_config"):
AppConfig._check_config_version(
{"config_version": 1},
config_path,
)
assert "outdated" in caplog.text
assert "version 1" in caplog.text
assert "version is 2" in caplog.text
def test_no_example_file_no_warning(caplog):
"""If config.example.yaml doesn't exist, no warning should be emitted."""
with tempfile.TemporaryDirectory() as tmpdir:
config_path = Path(tmpdir) / "config.yaml"
with open(config_path, "w", encoding="utf-8") as f:
yaml.dump({"sandbox": {"use": "test"}}, f)
# No config.example.yaml created
with caplog.at_level(logging.WARNING, logger="deerflow.config.app_config"):
AppConfig._check_config_version({}, config_path)
assert "outdated" not in caplog.text
def test_string_config_version_does_not_raise_type_error(caplog):
"""config_version stored as a YAML string should not raise TypeError on comparison."""
with tempfile.TemporaryDirectory() as tmpdir:
config_path = _make_config_files(
Path(tmpdir),
user_config={"config_version": "1"}, # string, as YAML can produce
example_config={"config_version": 2},
)
# Must not raise TypeError: '<' not supported between instances of 'str' and 'int'
AppConfig._check_config_version({"config_version": "1"}, config_path)
def test_newer_user_version_no_warning(caplog):
"""If user has a newer version than example (edge case), no warning."""
with tempfile.TemporaryDirectory() as tmpdir:
config_path = _make_config_files(
Path(tmpdir),
user_config={"config_version": 3},
example_config={"config_version": 2},
)
with caplog.at_level(logging.WARNING, logger="deerflow.config.app_config"):
AppConfig._check_config_version(
{"config_version": 3},
config_path,
)
assert "outdated" not in caplog.text
@pytest.mark.skipif(SCRIPT_BASH is None, reason="repo shell-script tests need Git Bash on Windows")
def test_version_26_config_upgrades_to_checkpoint_channel_mode(tmp_path, caplog):
"""A v26 user config must be flagged outdated and merge the new persisted field.
`database.checkpoint_channel_mode` shipped with config_version 27; the
upgrade path must add it with the safe default (``full``) without touching
the user's existing database backend settings. Uses the repository's real
config.example.yaml and the real config-upgrade script.
"""
import subprocess
repo_root = Path(__file__).resolve().parents[2]
example_src = repo_root / "config.example.yaml"
example_data = yaml.safe_load(example_src.read_text(encoding="utf-8"))
expected_version = example_data["config_version"]
assert expected_version > 26, "config.example.yaml must be bumped past 26 for checkpoint_channel_mode"
config_path = tmp_path / "config.yaml"
(tmp_path / "config.example.yaml").write_text(example_src.read_text(encoding="utf-8"), encoding="utf-8")
user_config = {
"config_version": 26,
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
"database": {"backend": "sqlite", "sqlite_dir": "custom-data"},
}
config_path.write_text(yaml.dump(user_config), encoding="utf-8")
with caplog.at_level(logging.WARNING, logger="deerflow.config.app_config"):
AppConfig._check_config_version(dict(user_config), config_path)
assert "outdated" in caplog.text
assert "(version 26)" in caplog.text
env = {**os.environ, "DEER_FLOW_CONFIG_PATH": str(config_path)}
result = subprocess.run(
[SCRIPT_BASH, str(repo_root / "scripts" / "config-upgrade.sh")],
env=env,
capture_output=True,
text=True,
timeout=120,
)
assert result.returncode == 0, result.stderr
upgraded = yaml.safe_load(config_path.read_text(encoding="utf-8"))
assert upgraded["config_version"] == expected_version
assert upgraded["database"]["checkpoint_channel_mode"] == "full"
assert upgraded["database"]["backend"] == "sqlite"
assert upgraded["database"]["sqlite_dir"] == "custom-data"
assert upgraded["verification"]["receipts_enabled"] is True
assert upgraded["verification"]["receipts_render_mode"] == "delegation_only"
assert upgraded["verification"]["judge_enabled"] is False
assert upgraded["verification"]["judge_model_name"] is None
@pytest.mark.skipif(SCRIPT_BASH is None, reason="repo shell-script tests need Git Bash on Windows")
def test_version_41_config_moves_legacy_ragflow_settings_to_tool(tmp_path):
"""The v46 migration keeps provider settings on the RAGFlow tool entry."""
import subprocess
repo_root = Path(__file__).resolve().parents[2]
example_src = repo_root / "config.example.yaml"
expected_version = yaml.safe_load(example_src.read_text(encoding="utf-8"))["config_version"]
assert expected_version >= 46
config_path = tmp_path / "config.yaml"
legacy = {
"config_version": 41,
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
"knowledge_base": {
"enabled": True,
"scope_selection_enabled": True,
"base_url": "http://legacy-ragflow:9380",
"api_key": "$LEGACY_RAGFLOW_API_KEY",
"page_size": 12,
},
"tools": [
{
"name": "knowledge_search",
"group": "knowledge",
"use": "deerflow.community.ragflow.tools:knowledge_search_tool",
# Explicit tool values win over the legacy global value.
"api_key": "$CURRENT_RAGFLOW_API_KEY",
}
],
}
config_path.write_text(yaml.dump(legacy), encoding="utf-8")
env = {**os.environ, "DEER_FLOW_CONFIG_PATH": str(config_path)}
result = subprocess.run(
[SCRIPT_BASH, str(repo_root / "scripts" / "config-upgrade.sh")],
env=env,
capture_output=True,
text=True,
timeout=120,
)
assert result.returncode == 0, result.stderr
upgraded = yaml.safe_load(config_path.read_text(encoding="utf-8"))
assert upgraded["config_version"] == expected_version, result.stdout + result.stderr
assert upgraded["knowledge_base"] == {
"enabled": True,
"scope_selection_enabled": True,
}
tool = upgraded["tools"][0]
assert tool["base_url"] == "http://legacy-ragflow:9380"
assert tool["page_size"] == 12
assert tool["api_key"] == "$CURRENT_RAGFLOW_API_KEY"
@pytest.mark.skipif(SCRIPT_BASH is None, reason="repo shell-script tests need Git Bash on Windows")
def test_version_41_tools_only_ragflow_config_enables_knowledge_capability(tmp_path):
"""Tools-only legacy configs must not be disabled by the new capability gate."""
import subprocess
repo_root = Path(__file__).resolve().parents[2]
example_src = repo_root / "config.example.yaml"
expected_version = yaml.safe_load(example_src.read_text(encoding="utf-8"))["config_version"]
assert expected_version >= 46
config_path = tmp_path / "config.yaml"
legacy = {
"config_version": 41,
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
# This was the documented enablement path before knowledge_base existed.
"tools": [
{
"name": "knowledge_search",
"group": "knowledge",
"use": "deerflow.community.ragflow.tools:knowledge_search_tool",
"base_url": "http://legacy-ragflow:9380",
"api_key": "$RAGFLOW_API_KEY",
}
],
}
config_path.write_text(yaml.dump(legacy), encoding="utf-8")
env = {**os.environ, "DEER_FLOW_CONFIG_PATH": str(config_path)}
result = subprocess.run(
[SCRIPT_BASH, str(repo_root / "scripts" / "config-upgrade.sh")],
env=env,
capture_output=True,
text=True,
timeout=120,
)
assert result.returncode == 0, result.stderr
assert "knowledge_base.enabled set to true" in result.stdout
upgraded = yaml.safe_load(config_path.read_text(encoding="utf-8"))
assert upgraded["config_version"] == expected_version
assert upgraded["knowledge_base"] == {
"enabled": True,
"scope_selection_enabled": False,
}
assert upgraded["tools"][0]["base_url"] == "http://legacy-ragflow:9380"
def test_version_45_tools_only_ragflow_config_runs_knowledge_migration(tmp_path):
"""The knowledge migration must run for configs at the former base version."""
import subprocess
repo_root = Path(__file__).resolve().parents[2]
example_src = repo_root / "config.example.yaml"
expected_version = yaml.safe_load(example_src.read_text(encoding="utf-8"))["config_version"]
assert expected_version > 45
config_path = tmp_path / "config.yaml"
config_path.write_text(
yaml.dump(
{
"config_version": 45,
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
"tools": [
{
"name": "knowledge_search",
"group": "knowledge",
"use": "deerflow.community.ragflow.tools:knowledge_search_tool",
"base_url": "http://legacy-ragflow:9380",
"api_key": "$RAGFLOW_API_KEY",
}
],
}
),
encoding="utf-8",
)
env = {**os.environ, "DEER_FLOW_CONFIG_PATH": str(config_path)}
result = subprocess.run(
[SCRIPT_BASH, str(repo_root / "scripts" / "config-upgrade.sh")],
env=env,
capture_output=True,
text=True,
timeout=120,
)
assert result.returncode == 0, result.stderr
assert "knowledge_base.enabled set to true" in result.stdout
upgraded = yaml.safe_load(config_path.read_text(encoding="utf-8"))
assert upgraded["config_version"] == expected_version
assert upgraded["knowledge_base"] == {
"enabled": True,
"scope_selection_enabled": False,
}
assert upgraded["tools"][0]["base_url"] == "http://legacy-ragflow:9380"
def test_version_45_tools_only_lightrag_config_keeps_knowledge_tool_available(tmp_path):
"""Upgrading a configured LightRAG provider must enable the new knowledge gate."""
import subprocess
repo_root = Path(__file__).resolve().parents[2]
example_src = repo_root / "config.example.yaml"
expected_version = yaml.safe_load(example_src.read_text(encoding="utf-8"))["config_version"]
assert expected_version > 45
config_path = tmp_path / "config.yaml"
config_path.write_text(
yaml.dump(
{
"config_version": 45,
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
"tools": [
{
"name": "knowledge_search",
"group": "knowledge",
"use": "deerflow.community.lightrag.tools:knowledge_search_tool",
"base_url": "http://legacy-lightrag:9621",
"api_key": "$LIGHTRAG_API_KEY",
}
],
}
),
encoding="utf-8",
)
env = {**os.environ, "DEER_FLOW_CONFIG_PATH": str(config_path)}
result = subprocess.run(
[SCRIPT_BASH, str(repo_root / "scripts" / "config-upgrade.sh")],
env=env,
capture_output=True,
text=True,
timeout=120,
)
assert result.returncode == 0, result.stderr
assert "knowledge_base.enabled set to true" in result.stdout
upgraded = yaml.safe_load(config_path.read_text(encoding="utf-8"))
assert upgraded["config_version"] == expected_version
assert upgraded["knowledge_base"] == {
"enabled": True,
"scope_selection_enabled": False,
}
app_config = AppConfig.model_validate(upgraded)
tools = get_available_tools(
groups=["knowledge"],
include_mcp=False,
include_upload_tool=False,
app_config=app_config,
)
assert "knowledge_search" in {tool.name for tool in tools}
def test_version_45_lightrag_config_preserves_explicit_disabled_gate(tmp_path):
"""Migration must not override an operator's explicit knowledge gate value."""
import subprocess
repo_root = Path(__file__).resolve().parents[2]
config_path = tmp_path / "config.yaml"
config_path.write_text(
yaml.dump(
{
"config_version": 45,
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
"knowledge_base": {"enabled": False},
"tools": [
{
"name": "knowledge_search",
"group": "knowledge",
"use": "deerflow.community.lightrag.tools:knowledge_search_tool",
"base_url": "http://legacy-lightrag:9621",
}
],
}
),
encoding="utf-8",
)
env = {**os.environ, "DEER_FLOW_CONFIG_PATH": str(config_path)}
result = subprocess.run(
[SCRIPT_BASH, str(repo_root / "scripts" / "config-upgrade.sh")],
env=env,
capture_output=True,
text=True,
timeout=120,
)
assert result.returncode == 0, result.stderr
upgraded = yaml.safe_load(config_path.read_text(encoding="utf-8"))
assert upgraded["knowledge_base"]["enabled"] is False
app_config = AppConfig.model_validate(upgraded)
tools = get_available_tools(
groups=["knowledge"],
include_mcp=False,
include_upload_tool=False,
app_config=app_config,
)
assert "knowledge_search" not in {tool.name for tool in tools}
def _load_repo_example() -> dict:
"""Load the real repo config.example.yaml (first-run template)."""
example_path = Path(__file__).resolve().parents[2] / "config.example.yaml"
with open(example_path, encoding="utf-8") as f:
return yaml.safe_load(f) or {}
def _merge_missing(target: dict, source: dict) -> None:
"""Add-missing-keys-only recursive merge mirroring scripts/config-upgrade.sh."""
for key, value in source.items():
if key not in target:
import copy
target[key] = copy.deepcopy(value)
elif isinstance(value, dict) and isinstance(target[key], dict):
_merge_missing(target[key], value)
def test_security_fail_closed_bumped_config_version():
"""The example must ship security_fail_closed under a version > 26 so v26 configs upgrade."""
example = _load_repo_example()
assert example.get("config_version", 0) >= 27
assert example["skill_evolution"]["security_fail_closed"] is True
def test_version_26_config_reported_outdated_against_example(caplog):
"""A version-26 user config is flagged outdated against the real example version."""
example = _load_repo_example()
example_version = example["config_version"]
with tempfile.TemporaryDirectory() as tmpdir:
config_path = _make_config_files(
Path(tmpdir),
user_config={"config_version": 26},
example_config=example,
)
with caplog.at_level(logging.WARNING, logger="deerflow.config.app_config"):
AppConfig._check_config_version({"config_version": 26}, config_path)
assert "outdated" in caplog.text
assert "version 26" in caplog.text
assert f"version is {example_version}" in caplog.text
def test_config_upgrade_adds_security_fail_closed_preserving_user_values():
"""config-upgrade merges security_fail_closed: true without touching existing skill_evolution values."""
example = _load_repo_example()
# A version-26 user who customized skill_evolution but predates the new field.
user = {
"config_version": 26,
"skill_evolution": {
"enabled": True,
"moderation_model_name": "custom-moderation-model",
},
}
_merge_missing(user, example)
user["config_version"] = example["config_version"]
# New persisted field is merged in with the example's fail-closed default.
assert user["skill_evolution"]["security_fail_closed"] is True
# The user's existing skill_evolution values are preserved unchanged.
assert user["skill_evolution"]["enabled"] is True
assert user["skill_evolution"]["moderation_model_name"] == "custom-moderation-model"
assert user["config_version"] == example["config_version"]
def test_version_46_pii_enabled_config_reported_outdated_against_example(caplog):
"""token_secret became mandatory for enabled redaction in v47; a v46
deployment with redaction on must be flagged outdated so the upgrade
warning fires instead of a raw startup validation error with no guidance."""
example = _load_repo_example()
example_version = example["config_version"]
assert example_version >= 47, "config.example.yaml must be bumped past 46 for the mandatory token_secret"
with tempfile.TemporaryDirectory() as tmpdir:
config_path = _make_config_files(
Path(tmpdir),
user_config={"config_version": 46, "pii_redaction": {"enabled": True}},
example_config=example,
)
with caplog.at_level(logging.WARNING, logger="deerflow.config.app_config"):
AppConfig._check_config_version({"config_version": 46}, config_path)
assert "outdated" in caplog.text
assert "(version 46)" in caplog.text
assert f"version is {example_version}" in caplog.text
@pytest.mark.skipif(SCRIPT_BASH is None, reason="repo shell-script tests need Git Bash on Windows")
def test_version_46_pii_enabled_config_upgrade_generates_token_secret(tmp_path):
"""Upgrading a v46 config with redaction enabled persists a generated
token_secret, leaving the deployment startable under the v47 mandatory
validation instead of failing startup after the version bump."""
import subprocess
repo_root = Path(__file__).resolve().parents[2]
example_src = repo_root / "config.example.yaml"
expected_version = yaml.safe_load(example_src.read_text(encoding="utf-8"))["config_version"]
assert expected_version >= 47
config_path = tmp_path / "config.yaml"
(tmp_path / "config.example.yaml").write_text(example_src.read_text(encoding="utf-8"), encoding="utf-8")
config_path.write_text(
yaml.dump(
{
"config_version": 46,
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
"pii_redaction": {"enabled": True},
}
),
encoding="utf-8",
)
env = {**os.environ, "DEER_FLOW_CONFIG_PATH": str(config_path)}
result = subprocess.run(
[SCRIPT_BASH, str(repo_root / "scripts" / "config-upgrade.sh")],
env=env,
capture_output=True,
text=True,
timeout=120,
)
assert result.returncode == 0, result.stderr
assert "token_secret generated" in result.stdout
upgraded = yaml.safe_load(config_path.read_text(encoding="utf-8"))
assert upgraded["config_version"] == expected_version
assert upgraded["pii_redaction"]["enabled"] is True
secret = upgraded["pii_redaction"]["token_secret"]
assert isinstance(secret, str) and len(secret) >= 16
# The upgraded deployment passes the now-mandatory validation.
app_config = AppConfig.model_validate(upgraded)
assert app_config.pii_redaction.token_secret == secret
@pytest.mark.skipif(SCRIPT_BASH is None, reason="repo shell-script tests need Git Bash on Windows")
def test_version_46_pii_disabled_config_upgrade_skips_token_secret(tmp_path):
"""The migration must not invent a secret when redaction is off."""
import subprocess
repo_root = Path(__file__).resolve().parents[2]
example_src = repo_root / "config.example.yaml"
expected_version = yaml.safe_load(example_src.read_text(encoding="utf-8"))["config_version"]
assert expected_version >= 47
config_path = tmp_path / "config.yaml"
(tmp_path / "config.example.yaml").write_text(example_src.read_text(encoding="utf-8"), encoding="utf-8")
config_path.write_text(
yaml.dump(
{
"config_version": 46,
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
"pii_redaction": {"enabled": False},
}
),
encoding="utf-8",
)
env = {**os.environ, "DEER_FLOW_CONFIG_PATH": str(config_path)}
result = subprocess.run(
[SCRIPT_BASH, str(repo_root / "scripts" / "config-upgrade.sh")],
env=env,
capture_output=True,
text=True,
timeout=120,
)
assert result.returncode == 0, result.stderr
upgraded = yaml.safe_load(config_path.read_text(encoding="utf-8"))
assert upgraded["config_version"] == expected_version
assert "token_secret" not in upgraded["pii_redaction"]
AppConfig.model_validate(upgraded)