JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(common): 修复 CLEANUP_PERIOD_DAYS 非法值导致删除全部会话
openJiuwen-bota25e5a73c21b
diff --git a/jiuwenswarm/common/cleanup.py b/jiuwenswarm/common/cleanup.pyindex 6830cddd1d..72fa48a07c 100644--- a/jiuwenswarm/common/cleanup.py+++ b/jiuwenswarm/common/cleanup.py@@ -4,6 +4,17 @@Mirrors claude-code's ``cleanup.ts`` approach: periodically check directory mtimeand remove entries older than the configured retention period.++安全约束(清理是本仓最 destructive 的后台动作,宁可少删不可误删):++- 保留期取自 ``CLEANUP_PERIOD_DAYS``,**非法值(非整数 / ``0`` / 负数)一律回落默认+ 30 天并告警**;缺失或空串属"未配置",静默回落。``0`` / 负数若直接参与+ ``cutoff = now - days*86400``,cutoff 会落在现在或未来,使所有会话目录都判定为过期+ 而被全量删除(不可恢复的数据丢失)。非法值回落的约定与本包+ ``common/workspace/quota.py`` 一致。+- 超大值(> ``MAX_CLEANUP_PERIOD_DAYS``)夹紧到上界并告警。上界的存在同时挡掉+ ``days*86400`` 的 float 溢出:极大值会让 cutoff 计算抛 OverflowError,被+ ``run_cleanup`` 吞掉后整轮会话清理静默不执行(孤儿 file_ops 清理照跑)。"""from __future__ import annotations@@ -24,29 +35,122 @@ from jiuwenswarm.common.utils import (logger = logging.getLogger(__name__)DEFAULT_CLEANUP_PERIOD_DAYS = 30+# 保留期上界,取 100 年——再长没有业务意义。+# 上界本身是硬要求:days*86400 超出 float 可表示范围(约 2e304 天)后+# `time.time() - days*86400` 会抛 OverflowError,让整轮会话清理被 run_cleanup 吞掉。+# 命中上界时取"夹紧"而非"回落默认值":极大值语义是"什么都别删",夹紧能保住该意图,+# 回落 30 天反而会突然开始删掉运维本来想保留的数据。+MAX_CLEANUP_PERIOD_DAYS = 36500RECURRING_CLEANUP_INTERVAL_S = 24 * 60 * 60FIRST_CLEANUP_DELAY_S = 10 * 60AGENT_ID = "jiuwenswarm"+CLEANUP_PERIOD_ENV = "CLEANUP_PERIOD_DAYS"++_LOG_VALUE_MAX_CHARS = 32+++def _short(raw: str) -> str:+ """截断超长环境变量值,避免畸形配置(如 400 位数字)刷屏日志。++ 只负责截断,**渲染时仍必须配 ``%r``**:repr 负责转义换行等控制字符,+ 否则 ``CLEANUP_PERIOD_DAYS="0\\nFAKE-LOG-LINE"`` 这类值会把日志拆行、+ 伪造出一条无前缀的假日志(``common/workspace/quota.py`` 也是 ``%r``)。+ """+ if len(raw) <= _LOG_VALUE_MAX_CHARS:+ return raw+ return raw[:_LOG_VALUE_MAX_CHARS] + "..."+++def _parse_period_days(raw: str) -> int | None:+ """把配置值解析成天数;不是整数时返回 ``None``。++ CPython ≥3.11 给 int-str 转换设了位数上限(默认 4300),超长数字串会抛+ ``ValueError``。这类值语义明确是"极大",返回 ``MAX_CLEANUP_PERIOD_DAYS + 1``+ 让它走夹紧分支——当成"不是数字"回落默认值会恰好走到本函数想避免的那条路+ (30 天,开始真删数据)。用 ``isdecimal()`` 而不是 ``isdigit()``:后者对+ ``'²'`` 这类字符也为真,但 ``int()`` 解析不了,会误判成"数字过大"。+ """+ try:+ return int(raw)+ except (TypeError, ValueError):+ return MAX_CLEANUP_PERIOD_DAYS + 1 if raw.isdecimal() else None+def _get_cleanup_period_days() -> int:- env_val = os.getenv("CLEANUP_PERIOD_DAYS")- if env_val:- try:- return int(env_val)- except (ValueError, TypeError):- pass- return DEFAULT_CLEANUP_PERIOD_DAYS+ """保留期天数;非整数 / 非正值回落默认值并告警,超大值夹紧到上界。++ 缺失或空串属"未配置",静默回落(不告警);``days <= 0`` 会让+ ``_get_cutoff_timestamp()`` 的 cutoff 落在现在或未来,从而删除**全部**会话目录,+ 因此必须挡在入口而不是靠调用方自觉。+ """+ raw = os.getenv(CLEANUP_PERIOD_ENV, "").strip()+ if not raw:+ return DEFAULT_CLEANUP_PERIOD_DAYS+ days = _parse_period_days(raw)+ if days is None:+ logger.warning(+ "background_cleanup: invalid %s=%r; using default %dd",+ CLEANUP_PERIOD_ENV,+ _short(raw),+ DEFAULT_CLEANUP_PERIOD_DAYS,+ )+ return DEFAULT_CLEANUP_PERIOD_DAYS+ if days <= 0:+ logger.warning(+ "background_cleanup: non-positive %s=%r; using default %dd "+ "(0 / negative is invalid)",+ CLEANUP_PERIOD_ENV,+ _short(raw),+ DEFAULT_CLEANUP_PERIOD_DAYS,+ )+ return DEFAULT_CLEANUP_PERIOD_DAYS+ if days > MAX_CLEANUP_PERIOD_DAYS:+ logger.warning(+ "background_cleanup: %s=%r exceeds max; clamped to %dd",+ CLEANUP_PERIOD_ENV,+ _short(raw),+ MAX_CLEANUP_PERIOD_DAYS,+ )+ return MAX_CLEANUP_PERIOD_DAYS+ return days-def _get_cutoff_timestamp() -> float:- days = _get_cleanup_period_days()+def _get_cutoff_timestamp(days: int) -> float:+ """保留期对应的过期时间戳;早于该 mtime 的目录视为过期。++ ``days`` 必须是 ``_get_cleanup_period_days()`` 夹紧后的值——超大整数在这里+ 会因 ``time.time() - days * 86400`` 的 float 转换抛 OverflowError。+ """return time.time() - days * 24 * 60 * 60-def _rmtree(path: Path) -> None:+def _rmtree(path: Path) -> bool:+ """删除目录树,返回路径是否**确认**已不存在。++ ``rmtree`` 用 ``ignore_errors=True``(保证幂等、不因单个文件失败中断整轮),+ 代价是失败被完全吞掉,所以这里用 ``os.lstat`` 回查一次:只有 ``FileNotFoundError``+ 才算删干净;仍存在、或无法判定(父目录不可访问等)一律返回 False 交给调用方计+ error。不用 ``Path.exists()`` / ``os.path.lexists``——两者都把 OSError 吞成+ False,会把"没删掉 / 查不了"误报成删除成功。lstat 不跟随符号链接,故残留的+ 软链目录也会如实判为"仍存在"。++ 告警前缀沿用调用方 ``cleanup_old_sessions:``(本模块日志前缀按所属流程统一,+ 不用匿名的 ``cleanup:``),便于按函数名过滤。+ """import shutil+shutil.rmtree(path, ignore_errors=True)+ try:+ os.lstat(path)+ except FileNotFoundError:+ return True+ except OSError:+ logger.warning(+ "cleanup_old_sessions: cannot verify removal of %s", path, exc_info=True+ )+ return False+ return Falsedef cleanup_old_sessions() -> dict[str, int]:@@ -55,7 +159,8 @@ def cleanup_old_sessions() -> dict[str, int]:Returns:{ "removed": N, "errors": N }"""- cutoff = _get_cutoff_timestamp()+ retention_days = _get_cleanup_period_days()+ cutoff = _get_cutoff_timestamp(retention_days)sessions_dir = get_agent_sessions_dir()if not sessions_dir.is_dir():return {"removed": 0, "errors": 0}@@ -69,16 +174,20 @@ def cleanup_old_sessions() -> dict[str, int]:try:if entry.stat().st_mtime >= cutoff:continue- _rmtree(entry)+ except OSError:+ errors += 1+ continue+ if _rmtree(entry):removed += 1logger.info("cleanup_old_sessions: removed %s", entry.name)- except OSError:+ else:errors += 1+ logger.warning("cleanup_old_sessions: failed to remove %s", entry)if removed or errors:logger.info(- "cleanup_old_sessions: removed=%d errors=%d cutoff_ts=%.0f",- removed, errors, cutoff,+ "cleanup_old_sessions: removed=%d errors=%d cutoff_ts=%.0f retention=%dd",+ removed, errors, cutoff, retention_days,)return {"removed": removed, "errors": errors}@@ -143,12 +252,12 @@ async def run_cleanup() -> None:try:await loop.run_in_executor(None, cleanup_old_sessions)except Exception:- logger.warning("cleanup_old_sessions failed", exc_info=True)+ logger.warning("background_cleanup: cleanup_old_sessions failed", exc_info=True)try:await loop.run_in_executor(None, cleanup_orphan_file_ops)except Exception:- logger.warning("cleanup_orphan_file_ops failed", exc_info=True)+ logger.warning("background_cleanup: cleanup_orphan_file_ops failed", exc_info=True)async def cleanup_loop(diff --git a/jiuwenswarm/common/docs/specs/S_14_session-lifecycle-and-upgrade.md b/jiuwenswarm/common/docs/specs/S_14_session-lifecycle-and-upgrade.mdindex 16b5355958..733f62bf34 100644--- a/jiuwenswarm/common/docs/specs/S_14_session-lifecycle-and-upgrade.md+++ b/jiuwenswarm/common/docs/specs/S_14_session-lifecycle-and-upgrade.md@@ -7,7 +7,7 @@| 类型 | spec || 编号 / slug | S_14 / session-lifecycle-and-upgrade || 关联模块 | jiuwenswarm/common/{todo_generation, todo_snapshot, cleanup, cron_team_completion, git_safe_directory, updater, updater_restart_helper, upgrade_executor, version, version_source}.py |-| 最近一次修订日期 | 2026-10-13 |+| 最近一次修订日期 | 2026-10-21 || 关联 feature | 暂无 |## 范围 / 边界@@ -44,6 +44,15 @@ version.__version__(唯一版本真源)- **N3 后台清理尽力而为**:保留期默认 30 天(`CLEANUP_PERIOD_DAYS`);首次延迟 10min、之后每 24h 一轮;按目录 mtime 判过期;阻塞操作丢线程池且单步失败不中断循环;rmtree `ignore_errors=True`(可重复执行幂等)。装配点:`app_gateway` 启动。+ 安全约束:`CLEANUP_PERIOD_DAYS` **非正整数(0 / 负数 / 非数字)一律回落默认 30 天并+ warning**——`days <= 0` 会让 cutoff 落在现在或未来而删除全部会话(与+ `workspace/quota.py` 的非法值回落约定一致);**超大值夹紧到 `MAX_CLEANUP_PERIOD_DAYS`+ (36500 天 = 100 年)并 warning**——上界本身挡掉 `days*86400` 的 float 溢出(极大值+ 会让 cutoff 计算抛 OverflowError,被 `run_cleanup` 吞掉后整轮清理静默不执行),取夹紧+ 而非回落默认值是为保住"极大保留期 = 什么都别删"的原意;超过 int-str 位数上限+ (CPython ≥3.11 默认 4300 位)的数字串同样按夹紧处理,不得退化成"非法 → 回落 30 天";+ 告警里的配置值一律 `%r` 渲染 + 截断 32 字符(转义换行等控制字符,防日志被拆行伪造);+ rmtree 后回查目录是否真的消失,失败计 `errors` 并 warning(不再静默)。- **N4 cron 收轮三信号路径**:只有 **leader 的非占位 `chat.final`** 才算完成信号(三个结束路径:workflow 完成后 final / team.completed + 有文本 / 纯 harness 收尾);**leader 提前 final 后若出现 `task.created` 会清除 final 锁存继续等待**;占位文案diff --git a/tests/unit_tests/common/test_cleanup.py b/tests/unit_tests/common/test_cleanup.pyindex ecca7f2b1e..e37835a958 100644--- a/tests/unit_tests/common/test_cleanup.py+++ b/tests/unit_tests/common/test_cleanup.py@@ -2,16 +2,46 @@from __future__ import annotations+import loggingimport os+import sysimport time+from pathlib import Path+from types import SimpleNamespaceimport pytestfrom jiuwenswarm.common.cleanup import (+ CLEANUP_PERIOD_ENV,+ DEFAULT_CLEANUP_PERIOD_DAYS,+ MAX_CLEANUP_PERIOD_DAYS,+ _get_cleanup_period_days,+ _parse_period_days,+ _rmtree,cleanup_old_sessions,cleanup_orphan_file_ops,)+CLEANUP_MODULE = "jiuwenswarm.common.cleanup"+LOGGER_NAME = "jiuwenswarm.common.cleanup"+++def _patch_sessions_dir(monkeypatch, sessions_dir: Path) -> None:+ monkeypatch.setattr(f"{CLEANUP_MODULE}.get_agent_sessions_dir", lambda: sessions_dir)+++def _make_session_dirs(sessions_dir: Path, ages_seconds: list[float]) -> list[Path]:+ """按给定"存在时长(秒)"批量创建会话目录并设置其 mtime。"""+ now = time.time()+ created: list[Path] = []+ for idx, age in enumerate(ages_seconds):+ entry = sessions_dir / f"session-{idx:03d}"+ entry.mkdir(parents=True)+ stamp = now - age+ os.utime(entry, (stamp, stamp))+ created.append(entry)+ return created+class TestCleanup:@@ -26,8 +56,8 @@ class TestCleanup:old_time = time.time() - 999 * 86400os.utime(stale, (old_time, old_time))- monkeypatch.setattr("jiuwenswarm.common.cleanup.get_agent_sessions_dir", lambda: sessions_dir)- monkeypatch.setattr("jiuwenswarm.common.cleanup._get_cleanup_period_days", lambda: 30)+ _patch_sessions_dir(monkeypatch, sessions_dir)+ monkeypatch.setattr(f"{CLEANUP_MODULE}._get_cleanup_period_days", lambda: 30)result = cleanup_old_sessions()assert result["removed"] >= 1@@ -44,10 +74,256 @@ class TestCleanup:fop = hist_dir / "file_ops_jiuwenswarm_dead_session.json"fop.write_text("{}", encoding="utf-8")- monkeypatch.setattr("jiuwenswarm.common.cleanup.get_agent_workspace_dir", lambda: tmp_path / "agent-ws")- monkeypatch.setattr("jiuwenswarm.common.cleanup.get_user_workspace_dir", lambda: tmp_path / "user-ws")- monkeypatch.setattr("jiuwenswarm.common.cleanup.get_agent_sessions_dir", lambda: sessions_dir)+ monkeypatch.setattr(f"{CLEANUP_MODULE}.get_agent_workspace_dir", lambda: tmp_path / "agent-ws")+ monkeypatch.setattr(f"{CLEANUP_MODULE}.get_user_workspace_dir", lambda: tmp_path / "user-ws")+ _patch_sessions_dir(monkeypatch, sessions_dir)result = cleanup_orphan_file_ops()assert result["removed"] >= 1assert not fop.exists()+++class TestCleanupPeriodDays:+ """P01:``CLEANUP_PERIOD_DAYS`` 非法值必须回落默认值,不能变成"全删"。"""++ @staticmethod+ @pytest.mark.parametrize("raw", ["0", "-1", "-30", "abc", "1.5", "30d", "", " "])+ def test_invalid_value_falls_back_to_default(monkeypatch, raw):+ monkeypatch.setenv(CLEANUP_PERIOD_ENV, raw)+ assert _get_cleanup_period_days() == DEFAULT_CLEANUP_PERIOD_DAYS++ @staticmethod+ def test_missing_env_falls_back_to_default(monkeypatch):+ monkeypatch.delenv(CLEANUP_PERIOD_ENV, raising=False)+ assert _get_cleanup_period_days() == DEFAULT_CLEANUP_PERIOD_DAYS++ @staticmethod+ @pytest.mark.parametrize(+ "raw,expected",+ [+ ("7", 7),+ (" 15 ", 15),+ ("+3", 3),+ (str(MAX_CLEANUP_PERIOD_DAYS), MAX_CLEANUP_PERIOD_DAYS),+ ],+ ids=["plain", "spaces", "plus-sign", "at-max"],+ )+ def test_valid_value_is_kept(monkeypatch, raw, expected):+ monkeypatch.setenv(CLEANUP_PERIOD_ENV, raw)+ assert _get_cleanup_period_days() == expected++ @staticmethod+ @pytest.mark.parametrize(+ "raw",+ [+ str(MAX_CLEANUP_PERIOD_DAYS + 1),+ "1" + "0" * 399,+ "1" * 5000,+ ],+ ids=["max-plus-one", "huge-400-digits", "over-int-str-limit"],+ )+ def test_too_large_value_is_clamped(monkeypatch, caplog, raw):+ """合法但过大的值夹紧到上界,而不是回落默认值。++ 包括超过 CPython int-str 位数上限(默认 4300)的串:``int()`` 解析失败,+ 但语义仍是"极大",不能退化成"非法 → 回落 30 天"(那会开始真删数据)。+ """+ monkeypatch.setenv(CLEANUP_PERIOD_ENV, raw)+ with caplog.at_level(logging.WARNING, logger=LOGGER_NAME):+ assert _get_cleanup_period_days() == MAX_CLEANUP_PERIOD_DAYS++ messages = [rec.getMessage() for rec in caplog.records]+ assert any("clamped" in msg for msg in messages), caplog.text+ assert not any("using default" in msg for msg in messages), caplog.text+ # 畸形长值不能在日志里整串展开+ assert all(len(msg) < 200 for msg in messages), caplog.text++ @staticmethod+ @pytest.mark.parametrize(+ "raw",+ ["0\nFAKE-LOG-LINE injected", "abc\r\nfake", "0\tfake"],+ ids=["newline", "crlf", "tab"],+ )+ def test_warning_escapes_control_chars(monkeypatch, caplog, raw):+ """回归:配置值里的换行/制表符必须被转义,否则日志会被拆行伪造假日志。"""+ monkeypatch.setenv(CLEANUP_PERIOD_ENV, raw)+ with caplog.at_level(logging.WARNING, logger=LOGGER_NAME):+ _get_cleanup_period_days()++ assert caplog.records, caplog.text+ for rec in caplog.records:+ msg = rec.getMessage()+ assert "\n" not in msg and "\r" not in msg and "\t" not in msg, msg++ @staticmethod+ @pytest.mark.parametrize("raw", ["0", "-1", "abc"])+ def test_invalid_value_logs_warning(monkeypatch, caplog, raw):+ monkeypatch.setenv(CLEANUP_PERIOD_ENV, raw)+ with caplog.at_level(logging.WARNING, logger=LOGGER_NAME):+ _get_cleanup_period_days()+ assert any(+ CLEANUP_PERIOD_ENV in rec.getMessage() and rec.levelno == logging.WARNING+ for rec in caplog.records+ ), caplog.text++ @staticmethod+ @pytest.mark.parametrize(+ "raw",+ ["0", "-1", "-30", "0.5", "abc"],+ ids=["zero", "negative", "negative-large", "non-integer", "garbage"],+ )+ def test_invalid_period_keeps_all_sessions(tmp_path, monkeypatch, raw):+ """issue 复现场景:非法保留期不再删除任何会话目录(含几分钟前的)。"""+ sessions_dir = tmp_path / "sessions"+ dirs = _make_session_dirs(sessions_dir, [86400, 60])+ _patch_sessions_dir(monkeypatch, sessions_dir)+ monkeypatch.setenv(CLEANUP_PERIOD_ENV, raw)++ result = cleanup_old_sessions()++ assert result == {"removed": 0, "errors": 0}+ assert sorted(p.name for p in sessions_dir.iterdir()) == sorted(p.name for p in dirs)++ @staticmethod+ def test_huge_period_does_not_abort_cleanup(tmp_path, monkeypatch):+ """回归:超大保留期不得让整轮清理抛 OverflowError 而整体失效。++ 原先 days*86400 溢出 → cleanup_old_sessions 抛错 → 被 run_cleanup 吞掉,+ 会话清理整轮不执行;夹紧到上界后应正常跑完且不删除任何目录。+ """+ sessions_dir = tmp_path / "sessions"+ dirs = _make_session_dirs(sessions_dir, [400 * 86400, 60])+ _patch_sessions_dir(monkeypatch, sessions_dir)+ monkeypatch.setenv(CLEANUP_PERIOD_ENV, "1" + "0" * 399)++ result = cleanup_old_sessions() # 修复前这里直接抛 OverflowError++ assert result == {"removed": 0, "errors": 0}+ assert sorted(p.name for p in sessions_dir.iterdir()) == sorted(p.name for p in dirs)+++class TestParsePeriodDays:+ """``int()`` 解析失败时的分叉:数字过长 → 夹紧;不是数字 → None(回落默认)。"""++ @staticmethod+ def test_huge_digit_string_is_treated_as_too_large():+ """超长数字串必须落在"过大"一侧,不能变成 None(None 会回落默认值)。++ 这里只断言"结果 > 上界",不断言具体哨兵值:CPython 的 int-str 位数上限+ 可由 ``PYTHONINTMAXSTRDIGITS`` 调高或关闭,届时 ``int()`` 直接解析成功、+ 返回那个巨型整数;上限生效时才返回 ``MAX + 1`` 哨兵。两种情况的共同契约+ 是"结果超过上界",把测试钉在哨兵上会在上限被关闭的机器上误报失败。+ """+ days = _parse_period_days("1" * 5000)++ assert days is not None+ assert days > MAX_CLEANUP_PERIOD_DAYS++ @staticmethod+ def test_huge_digit_string_hits_sentinel_when_int_limit_bites():+ """位数上限真正生效时走哨兵分支——固定上限,不依赖宿主环境配置。"""+ original_limit = sys.get_int_max_str_digits()+ sys.set_int_max_str_digits(640)+ try:+ assert _parse_period_days("1" * 700) == MAX_CLEANUP_PERIOD_DAYS + 1+ finally:+ sys.set_int_max_str_digits(original_limit)++ @staticmethod+ @pytest.mark.parametrize("raw", ["abc", "1.5", "30d", "²"])+ def test_non_numeric_returns_none(raw):+ assert _parse_period_days(raw) is None++ @staticmethod+ def test_plain_integer_is_returned_as_is():+ assert _parse_period_days("36500") == MAX_CLEANUP_PERIOD_DAYS+++class TestRemovalVerification:+ """回归:删除失败/无法确认时必须计 errors + warning,不能伪造成 removed。"""++ @staticmethod+ def test_rmtree_reports_true_when_path_gone(tmp_path):+ target = tmp_path / "session-old"+ target.mkdir()++ assert _rmtree(target) is True+ assert not target.exists()++ @staticmethod+ def test_rmtree_reports_false_when_still_present(tmp_path, monkeypatch):+ """rmtree 被吞掉(未真正删除)时不能算成功。"""+ target = tmp_path / "session-old"+ target.mkdir()+ monkeypatch.setattr("shutil.rmtree", lambda *args, **kwargs: None)++ assert _rmtree(target) is False+ assert target.exists()++ @staticmethod+ def test_rmtree_reports_false_when_verification_fails(tmp_path, monkeypatch, caplog):+ """lstat 抛 OSError(父目录不可访问等)时按"未确认删除"处理,不能算成功。"""++ def _denied(_path):+ raise PermissionError(13, "Permission denied")++ target = tmp_path / "session-old"+ target.mkdir()+ monkeypatch.setattr(f"{CLEANUP_MODULE}.os", SimpleNamespace(lstat=_denied))++ with caplog.at_level(logging.WARNING, logger=LOGGER_NAME):+ assert _rmtree(target) is False++ assert any(+ "cleanup_old_sessions:" in rec.getMessage() and rec.levelno == logging.WARNING+ for rec in caplog.records+ ), caplog.text++ @staticmethod+ def test_cleanup_counts_removal_failure_as_error(tmp_path, monkeypatch, caplog):+ """rmtree 没删掉目录时,cleanup_old_sessions 计 errors 并打 warning。"""+ sessions_dir = tmp_path / "sessions"+ _make_session_dirs(sessions_dir, [40 * 86400])+ _patch_sessions_dir(monkeypatch, sessions_dir)+ monkeypatch.setenv(CLEANUP_PERIOD_ENV, "30")+ monkeypatch.setattr("shutil.rmtree", lambda *args, **kwargs: None)++ with caplog.at_level(logging.WARNING, logger=LOGGER_NAME):+ result = cleanup_old_sessions()++ assert result == {"removed": 0, "errors": 1}+ assert len(list(sessions_dir.iterdir())) == 1+ assert any(+ "failed to remove" in rec.getMessage() and rec.levelno == logging.WARNING+ for rec in caplog.records+ ), caplog.text+++class TestAllExpiredSessions:+ """全部会话都过期时照常全量回收。"""++ @staticmethod+ def test_all_expired_sessions_are_removed(tmp_path, monkeypatch):+ sessions_dir = tmp_path / "sessions"+ total = 12+ _make_session_dirs(sessions_dir, [40 * 86400] * total)+ _patch_sessions_dir(monkeypatch, sessions_dir)+ monkeypatch.setenv(CLEANUP_PERIOD_ENV, "30")++ result = cleanup_old_sessions()++ assert result == {"removed": total, "errors": 0}+ assert list(sessions_dir.iterdir()) == []++ @staticmethod+ def test_fresh_sessions_are_kept(tmp_path, monkeypatch):+ """同一轮里新旧混排:过期的删、未过期的留。"""+ sessions_dir = tmp_path / "sessions"+ _make_session_dirs(sessions_dir, [40 * 86400, 1 * 86400, 60])+ _patch_sessions_dir(monkeypatch, sessions_dir)+ monkeypatch.setenv(CLEANUP_PERIOD_ENV, "30")++ result = cleanup_old_sessions()++ assert result == {"removed": 1, "errors": 0}+ assert sorted(p.name for p in sessions_dir.iterdir()) == ["session-001", "session-002"]