Skip to content

Commit aba6879

Browse files
authored
Merge pull request #31 from beersoccer/feature/memory-lifecycle-cleanup
chore: release v0.2.4 with resource isolation optimization
2 parents f555dca + 46fdaa1 commit aba6879

30 files changed

Lines changed: 2630 additions & 1444 deletions

.github/workflows/ci.yml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,8 @@ jobs:
3030
env:
3131
PYTHONPATH: ${{ github.workspace }}
3232
run: |
33-
pytest -q
33+
# 运行不需要fork模式的测试(排除E2E和需要fork的工具测试)
34+
pytest tests/unit/utils/ tests/integration/ -q --tb=short
35+
36+
# 运行需要fork模式的工具测试(排除E2E)
37+
pytest tests/unit/tools/ --forked -q --tb=short

CHANGELOG.md

Lines changed: 84 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,64 @@
11
# Mem0 Dify Plugin - Changelog
22

3+
## Version 0.2.4 (2026-02-03)
4+
5+
### 🔒 Resource Isolation Optimization for Long-Term Memory Tool
6+
7+
This release introduces critical resource isolation improvements for the `extract_long_term_memory` tool, ensuring efficient connection pool management and preventing resource leaks when processing multiple memory subtypes.
8+
9+
#### Highlights
10+
11+
- **🔒 Connection Pool Sharing & Resource Isolation**:
12+
- **Problem Solved**: The long-term memory extraction tool creates multiple subtype clients (semantic/episodic/procedural) for processing different memory types. Previously, each client would create its own connection pool, leading to resource waste and potential connection exhaustion.
13+
- **Solution**: Implemented intelligent connection pool sharing mechanism where all subtype clients share the base client's connection pool
14+
- **Resource Isolation**: Each subtype client maintains its own `Memory` instance with custom prompts for isolation, but shares the underlying connection pool for efficiency
15+
- **Impact**: Reduces database connections from 3 pools (one per subtype) to 1 shared pool, significantly improving resource efficiency
16+
17+
- **🛡️ Smart Resource Cleanup**:
18+
- **Pool Ownership Detection**: Added `_is_sharing_pool` flag to track which clients are sharing connection pools
19+
- **Prevent Premature Closure**: Resource cleanup logic now detects shared pools and only allows the owner (base client) to close them
20+
- **Automatic Cleanup Order**: Subtype clients are cleaned up first, then base client closes the shared pool
21+
- **Impact**: Prevents "connection pool already closed" errors and ensures proper resource lifecycle management
22+
23+
- **🔧 Implementation Details**:
24+
- `build_subtype_sync_clients()` and `build_subtype_async_clients()` now accept `base_client` parameter to share connection pool
25+
- `SyncMem0Client.close()` and `AsyncMem0Client.aclose()` check `_is_sharing_pool` flag before closing pools
26+
- `resource_cleanup.py` enhanced with pool sharing detection logic
27+
- All cleanup operations respect pool ownership to prevent race conditions
28+
29+
#### 📊 Resource Efficiency Improvements
30+
31+
| Metric | Before | After | Improvement |
32+
|--------|--------|-------|-------------|
33+
| Connection Pools per Task | 3 (one per subtype) | 1 (shared) | **-67%** |
34+
| Database Connections | 3x pool size | 1x pool size | **-67%** |
35+
| Resource Leaks | Possible | Prevented ||
36+
| Cleanup Errors | Possible | Eliminated ||
37+
38+
#### 📝 Files Changed
39+
40+
- **Modified Files**:
41+
- `utils/mem0_extraction.py` - Added connection pool sharing logic in `build_subtype_sync_clients()` and `build_subtype_async_clients()`
42+
- `utils/mem0_client.py` - Enhanced `close()` and `aclose()` methods with pool sharing detection
43+
- `utils/resource_cleanup.py` - Added pool sharing detection in `close_vector_store()` function
44+
- `tools/extract_long_term_memory.py` - Updated to pass base_client for pool sharing, improved cleanup order
45+
46+
#### ⚠️ Migration Notes
47+
48+
- **No Breaking Changes**: All changes are internal resource management improvements
49+
- **No Configuration Changes**: No user-facing configuration changes required
50+
- **Automatic**: Resource isolation improvements are automatically applied to all extraction tasks
51+
- **Backward Compatible**: Works with existing checkpoints and task status storage
52+
53+
#### 🎯 Benefits
54+
55+
1. **Resource Efficiency**: 67% reduction in database connections per extraction task
56+
2. **Prevents Resource Leaks**: Proper cleanup order ensures no orphaned connection pools
57+
3. **Production Stability**: Eliminates connection pool exhaustion in high-concurrency scenarios
58+
4. **Cost Savings**: Fewer database connections reduce infrastructure costs for large-scale deployments
59+
60+
---
61+
362
## Version 0.2.3 (2026-01-31)
463

564
### 📚 Documentation Updates
@@ -152,40 +211,40 @@ This release introduces significant performance optimizations for the long-term
152211
### 🔥 Critical Bug Fix: Data Loss Prevention
153212

154213
#### Fixed
155-
- **严重Bug修复**: 修复了时间范围向前扩展时导致的数据丢失问题
156-
- **问题**: 当新的`start_time`早于上次处理的时间时,checkpoint会导致早期消息被永久跳过
157-
- **示例**: 第1次处理 T2-T4,第2次处理 T1-T5,结果 T1-T2 的消息丢失
158-
- **根本原因**: 倒序扫描 + ID-based checkpoint停止逻辑无法处理时间范围回溯
159-
- **影响范围**: 补处理历史数据、时间范围调整等场景
160-
- **修复方案**: 时间范围感知的Checkpoint机制
214+
- **Critical Bug Fix**: Fixed data loss issue when time range expands forward
215+
- **Issue**: When new `start_time` is earlier than last processed time, checkpoint causes early messages to be permanently skipped
216+
- **Example**: First run processes T2-T4, second run processes T1-T5, resulting in messages T1-T2 being lost
217+
- **Root Cause**: Reverse-order scanning + ID-based checkpoint stop logic cannot handle time range rollback
218+
- **Impact Scope**: Scenarios like backfilling historical data, time range adjustments, etc.
219+
- **Fix Solution**: Time range-aware Checkpoint mechanism
161220

162221
#### Enhanced
163-
- **ConversationCheckpoint 增强**:
164-
- 新增 `processed_range_start`: 记录已处理的最早消息时间
165-
- 新增 `processed_range_end`: 记录已处理的最晚消息时间
166-
- 冗余度影响: 每个会话增加 ~40 字节(仍然很低)
222+
- **ConversationCheckpoint Enhancement**:
223+
- Added `processed_range_start`: Records the earliest processed message time
224+
- Added `processed_range_end`: Records the latest processed message time
225+
- Redundancy Impact: Each session increases by ~40 bytes (still very low)
167226

168-
- **扫描逻辑优化**:
169-
- 自动检测时间范围向前扩展(`range_is_expanding`
170-
- 扩展时不在checkpoint处停止,继续扫描更早的消息
171-
- 时间戳优先的停止逻辑(更可靠),ID-based作为备份
172-
- 完全向后兼容旧checkpoint(无range字段)
227+
- **Scanning Logic Optimization**:
228+
- Automatically detects time range forward expansion (`range_is_expanding`)
229+
- When expanding, does not stop at checkpoint, continues scanning earlier messages
230+
- Timestamp-priority stop logic (more reliable), ID-based as fallback
231+
- Fully backward compatible with old checkpoints (no range fields)
173232

174233
#### Testing
175-
- 新增测试文件: `tests/test_time_range_expansion.py`
176-
- 验证时间范围向前扩展不丢失数据
177-
- 验证无范围扩展时checkpoint正常停止
178-
- 验证旧checkpoint向后兼容性
234+
- Added test file: `tests/test_time_range_expansion.py`
235+
- Verifies time range forward expansion does not lose data
236+
- Verifies checkpoint stops normally when no range expansion
237+
- Verifies old checkpoint backward compatibility
179238

180239
#### Documentation
181-
- 新增详细文档: `.cursor/plans/checkpoint_data_integrity_fix.md`
182-
- 问题分析、修复方案、测试覆盖、使用建议
240+
- Added detailed documentation: `.cursor/plans/checkpoint_data_integrity_fix.md`
241+
- Issue analysis, fix solution, test coverage, usage recommendations
183242

184243
#### Impact
185-
-**消息不丢失**: 完全修复时间范围回溯的数据丢失问题
186-
-**消息不重复**: checkpoint仍然有效阻止重复处理
187-
-**向后兼容**: 旧checkpoint自动迁移,无需手动操作
188-
-**强烈建议升级**: 修复了严重的数据完整性问题
244+
-**No Message Loss**: Completely fixes data loss issue from time range rollback
245+
-**No Message Duplication**: Checkpoint still effectively prevents duplicate processing
246+
-**Backward Compatible**: Old checkpoints automatically migrate, no manual operation required
247+
-**Strongly Recommended Upgrade**: Fixes critical data integrity issue
189248

190249
---
191250

PR_TEMPLATE.md

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,13 @@ Please provide the following metadata of your plugin to make it easier for the r
2929

3030
<!-- Please briefly describe the purpose of the new plugin or the updates made to the existing plugin -->
3131

32-
This version update (v0.2.3) focuses on comprehensive documentation updates to ensure all markdown documentation matches the current code implementation. The plugin integrates [Mem0 AI](https://mem0.ai)'s intelligent memory layer into Dify, providing comprehensive memory management capabilities for AI applications. The plugin operates exclusively in **self-hosted mode**, allowing users to configure and manage their own LLM, embedding models, vector databases, graph databases, and rerankers.
32+
This version update (v0.2.4) focuses on critical resource isolation optimization for the long-term memory extraction tool. The plugin integrates [Mem0 AI](https://mem0.ai)'s intelligent memory layer into Dify, providing comprehensive memory management capabilities for AI applications. The plugin operates exclusively in **self-hosted mode**, allowing users to configure and manage their own LLM, embedding models, vector databases, graph databases, and rerankers.
3333

34-
### What's New in v0.2.3:
34+
### What's New in v0.2.4:
35+
36+
- **🔒 Connection Pool Sharing & Resource Isolation (2026-02-03)**: Implemented intelligent connection pool sharing mechanism for long-term memory extraction tool. All subtype clients (semantic/episodic/procedural) now share the base client's connection pool while maintaining independent Memory instances. **67% reduction** in database connections per extraction task, prevents connection pool exhaustion, eliminates resource leaks
37+
38+
### Previous Updates in v0.2.3:
3539

3640
- **📝 Comprehensive Documentation Update (2026-01-31)**: Updated all markdown documentation to match current code implementation, merged scattered design documents into unified design history, ensured consistency across all documentation files
3741

@@ -313,6 +317,12 @@ Please confirm that your plugin README includes all necessary information:
313317
- **PRIVACY.md**: Complete privacy policy explaining self-hosted mode operation and data handling
314318
- **CHANGELOG.md**: Detailed version history and changes for all versions
315319

320+
**Documentation Improvements in v0.2.4:**
321+
- Added comprehensive documentation for resource isolation optimization
322+
- Updated version references to v0.2.4
323+
- Documented connection pool sharing mechanism and resource efficiency improvements
324+
- Updated resource management and cleanup enhancements with pool sharing details
325+
316326
**Documentation Improvements in v0.2.3:**
317327
- Added comprehensive documentation for performance optimizations (smart memory classification, token-aware processing)
318328
- Updated version references to v0.2.3

README.md

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Mem0 Dify Plugin v0.2.3
1+
# Mem0 Dify Plugin v0.2.4
22

33
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
44
[![Dify Plugin](https://img.shields.io/badge/Dify-Plugin-blue)](https://dify.ai)
@@ -31,7 +31,16 @@ A comprehensive Dify plugin that integrates [Mem0 AI](https://mem0.ai)'s intelli
3131
- 🌍 **Internationalized** - 中英双语 (Chinese/English)
3232
- ⚙️ **Async Mode Switch** - `async_mode` is enabled by default; Write ops (Add/Update/Delete) are non-blocking in async mode, Read ops (Search/Get/History) always wait; in sync mode all operations block until completion.
3333

34-
### What's New (v0.2.3) - Documentation Updates! 📚
34+
### What's New (v0.2.4) - Resource Isolation Optimization! 🔒
35+
- **🔒 Connection Pool Sharing & Resource Isolation (2026-02-03)**
36+
- **Critical Optimization**: Long-term memory extraction tool now uses intelligent connection pool sharing
37+
- **Problem Solved**: Previously, each memory subtype client (semantic/episodic/procedural) created its own connection pool, wasting resources
38+
- **Solution**: All subtype clients now share the base client's connection pool while maintaining independent Memory instances
39+
- **Resource Efficiency**: **67% reduction** in database connections (from 3 pools to 1 shared pool per extraction task)
40+
- **Smart Cleanup**: Automatic detection of shared pools prevents premature closure and resource leaks
41+
- **Impact**: Significantly improved resource efficiency, prevents connection pool exhaustion, reduces infrastructure costs
42+
43+
### Previous Updates (v0.2.3) - Documentation Updates! 📚
3544
- **📝 Comprehensive Documentation Update (2026-01-31)**
3645
- Updated all markdown documentation to match current code implementation
3746
- Merged scattered design documents into unified design history
@@ -365,6 +374,7 @@ done
365374

366375
| Version | Date | Changes |
367376
|---------|------|---------|
377+
| v0.2.4 | 2026-02-03 | Resource isolation optimization: Connection pool sharing for long-term memory tool (67% reduction in database connections) |
368378
| v0.2.3 | 2026-01-31 | Documentation updates: Comprehensive documentation synchronization, merged design documents, improved consistency |
369379
| v0.2.2 | 2026-01-30 | Performance optimizations: Smart memory classification (33% LLM call reduction), token-aware processing with tiktoken, code quality improvements |
370380
| v0.2.1 | 2026-01-29 | Critical bug fix: Data loss prevention when time range expands backward, enhanced checkpoint with time range awareness |

manifest.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
version: 0.2.3
1+
version: 0.2.4
22
type: plugin
33
author: beersoccer
44
name: mem0ai

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "mem0-dify-plugin"
3-
version = "0.2.3"
3+
version = "0.2.4"
44
description = "Mem0 Dify plugin"
55
requires-python = ">=3.12"
66
dependencies = [

requirements-dev.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
pytest>=8.0.0
22
pytest-asyncio>=0.21.0
3+
pytest-forked>=1.6.0
34
ruff>=0.8.0
45
locust>=2.0.0
56
python-dotenv>=1.0.0

0 commit comments

Comments
 (0)