Skip to content

Commit e9e4fb0

Browse files
tangg555fridayLglin93
authored
Scheduler: a range of bugs fixture and new features (#692)
* debug an error function name * feat: Add DynamicCache compatibility for different transformers versions - Fix build_kv_cache method in hf.py to handle both old and new DynamicCache structures - Support new 'layers' attribute with key_cache/value_cache or keys/values - Maintain backward compatibility with direct key_cache/value_cache attributes - Add comprehensive error handling and logging for unsupported structures - Update move_dynamic_cache_htod function in kv.py for cross-version compatibility - Handle layers-based structure in newer transformers versions - Support alternative attribute names (keys/values vs key_cache/value_cache) - Preserve original functionality for older transformers versions - Add comprehensive tests for DynamicCache compatibility - Test activation memory update with mock DynamicCache layers - Verify layers attribute access across different transformers versions - Fix scheduler logger mock to include memory_manager attribute This resolves AttributeError issues when using different versions of the transformers library and ensures robust handling of DynamicCache objects. debug * feat: implement APIAnalyzerForScheduler for memory operations - Add APIAnalyzerForScheduler class with search/add operations - Support requests and http.client with connection reuse - Include comprehensive error handling and dynamic configuration - Add English test suite with real-world conversation scenarios * feat: Add search_ws API endpoint and enhance API analyzer functionality - Add search_ws endpoint in server_router.py for scheduler-enabled search - Fix missing imports: time module, SearchRequest class, and get_mos_product_instance function - Implement search_ws method in api_analyzer.py with HTTP client support - Add _search_ws_with_requests and _search_ws_with_http_client private methods - Include search_ws usage example in demonstration code - Enhance scheduler and dispatcher capabilities for improved memory management - Expand test coverage to ensure functionality stability This update primarily strengthens the memory scheduling system's search capabilities, providing users with more flexible API interface options. * fix: resolve test failures and warnings in test suite - Fix Pydantic serialization warning in test_memos_chen_tang_hello_world * Add warnings filter to suppress UserWarning from Pydantic serialization - Fix KeyError: 'past_key_values' in test_build_kv_cache_and_generation * Update mock configuration to properly return forward_output with past_key_values * Add DynamicCache version compatibility handling in test mocks * Support both old and new transformers versions with layers/key_cache attributes * Improve assertion logic to check all model calls for required parameters - Update base_scheduler.py to use centralized DEFAULT_MAX_INTERNAL_MESSAGE_QUEUE_SIZE constant * Add import for DEFAULT_MAX_INTERNAL_MESSAGE_QUEUE_SIZE from general_schemas * Replace hardcoded value 100 with configurable constant (1000) All tests now pass successfully with proper version compatibility handling. * feat: add a test_robustness execution to test thread pool execution * feat: optimize scheduler configuration and API search functionality - Add DEFAULT_TOP_K and DEFAULT_CONTEXT_WINDOW_SIZE global constants in general_schemas.py - Update base_scheduler.py to use global default values instead of hardcoded numbers - Fix SchedulerConfigFactory initialization issue by using keyword argument expansion - Resolve UnboundLocalError variable conflict in search_memories_ws function - Fix indentation and parameter issues in OptimizedScheduler search_for_api method - Improve code standardization and maintainability * feat: Add Redis auto-initialization with fallback strategies - Add auto_initialize_redis() with config/env/local fallback - Move Redis logic from dispatcher_monitor to redis_service - Update base_scheduler to use auto initialization - Add proper resource cleanup and error handling * feat: add database connection management to ORM module - Add MySQL engine loading from environment variables in BaseDBManager - Add Redis connection loading from environment variables in BaseDBManager - Enhance database configuration validation and error handling - Complete database adapter infrastructure for ORM module - Provide unified database connection management interface This update provides comprehensive database connection management capabilities for the mem_scheduler module, supporting dynamic MySQL and Redis configuration loading from environment variables, establishing reliable data persistence foundation for scheduling services and API services. * remove part of test * feat: add Redis-based ORM with multiprocess synchronization - Add RedisDBManager and RedisLockableORM classes - Implement atomic locking mechanism for concurrent access - Add merge functionality for different object types - Include comprehensive test suite and examples - Fix Redis key type conflicts in lock operations * fix: resolve scheduler module import and Redis integration issues * revise naive memcube creation in server router * remove long-time tests in test_scheduler * remove redis test which needs .env * refactor all codes about mixture search with scheduler * fix: resolve Redis API synchronization issues and implement search API with reranker - Fix running_entries to running_task_ids migration across codebase - Update sync_search_data method to properly handle TaskRunningStatus - Correct variable naming and logic in API synchronization flow - Implement search API endpoint with reranker functionality - Update test files to reflect new running_task_ids convention - Ensure proper Redis state management for concurrent tasks * remove a test for api module * revise to pass the test suite * address some bugs to make mix_search normally running * modify codes according to evaluation logs * feat: Optimize mixture search and enhance API client * feat: Add conversation_turn tracking for session-based memory search - Add conversation_turn field to APIMemoryHistoryEntryItem schema with default value 0 - Implement session counter in OptimizedScheduler to track turn count per session_id - Update sync_search_data method to accept and store conversation_turn parameter - Maintain session history with LRU eviction (max 5 sessions) - Rename conversation_id to session_id for consistency with request object - Enable direct access to session_id from search requests This feature allows tracking conversation turns within the same session, providing better context for memory retrieval and search history management. * adress time bug in monitor * revise simple tree * add mode to evaluation client; rewrite print to logger.info in db files * feat: 1. add redis queue for scheduler 2. finish the code related to mix search and fine search * debug the working memory code * addressed a range of bugs to make scheduler running correctly * remove test_dispatch_parallel test * print change to logger.info * adjucted the core code related to fine and mixture apis * feat: create task queue to wrap local queue and redis queue. queue now split FIFO to multi queue from different users. addressed a range of bugs * fix bugs: debug bugs about internet trigger * debug get searcher mode * feat: add manual internet * Fix: fix code format * feat: add strategy for fine search * debug redis queue * debug redis queue * fix bugs: completely addressed bugs about redis queue * refactor: add searcher to handler_init; remove info log from task_queue * refactor: modify analyzer * refactor: revise locomo_eval to make it support llm other than gpt-4o-mini * feat: develop advanced searcher with deep search * feat: finish a complete version of deep search * refactor: refactor deep search feature, now only allowing one-round deep search * feat: implement the feature of get_tasks_status, but completed tasks are not recorded yet; waiting to be developed * debuging merged code; searching memories have bugs * change logging level * debug api evaluation * fix bugs: change top to top_k * change log * refactor: rewrite deep search to make it work better * change num_users * feat: developed and test task broker and orchestrator * Fix: Include task_id in ScheduleMessageItem serialization * Fix(Scheduler): Correct event log creation and task_id serialization * Feat(Scheduler): Add conditional detailed logging for KB updates Fix(Scheduler): Correct create_event_log indentation * Fix(Scheduler): Correct create_event_log call sites Reverts previous incorrect fix to scheduler_logger.py and correctly fixes the TypeError at the call sites in general_scheduler.py by removing the invalid 'log_content' kwarg and adding the missing memory_type kwargs. * Fix(Scheduler): Deserialize task_id in ScheduleMessageItem.from_dict This completes the fix for the task_id loss. The 'to_dict' method was previously fixed to serialize the task_id, but the corresponding 'from_dict' method was not updated to deserialize it, causing the value to be lost when messages were read from the queue. * Refactor(Config): Centralize RabbitMQ config override logic Moves all environment variable override logic into initialize_rabbitmq for a single source of truth. This ensures Nacos-provided environment variables for all RabbitMQ settings are respected over file configurations. Also removes now-redundant logging from the publish method. * Revert "Refactor(Config): Centralize RabbitMQ config override logic" This reverts commit b8cc42a. * Fix(Redis): Convert None task_id to empty string during serialization Resolves DataError in Redis Streams when task_id is None by ensuring it's serialized as an empty string instead of None, which Redis does not support. Applies to ScheduleMessageItem.to_dict method. * Feat(Log): Add diagnostic log to /product/add endpoint Adds an INFO level diagnostic log message at the beginning of the create_memory function to help verify code deployment. * Feat(Log): Add comprehensive diagnostic logs for /product/add flow Introduces detailed INFO level diagnostic logs across the entire call chain for the /product/add API endpoint. These logs include relevant context, such as full request bodies, message items before scheduler submission, and messages before RabbitMQ publication, to aid in debugging deployment discrepancies and tracing data flow, especially concerning task_id propagation. Logs added/enhanced in: - src/memos/api/routers/product_router.py - src/memos/api/handlers/add_handler.py - src/memos/multi_mem_cube/single_cube.py - src/memos/mem_os/core.py - src/memos/mem_scheduler/general_scheduler.py - src/memos/mem_scheduler/base_scheduler.py - src/memos/mem_scheduler/webservice_modules/rabbitmq_service.py * Feat(Log): Add comprehensive diagnostic logs for /product/add flow and apply ruff formatting Introduces detailed INFO level diagnostic logs across the entire call chain for the /product/add API endpoint. These logs include relevant context, such as full request bodies, message items before scheduler submission, and messages before RabbitMQ publication, to aid in debugging deployment discrepancies and tracing data flow, especially concerning task_id propagation. Also applies automatic code formatting using ruff format to all modified files. Logs added/enhanced in: - src/memos/api/routers/product_router.py - src/memos/api/handlers/add_handler.py - src/memos/multi_mem_cube/single_cube.py - src/memos/mem_os/core.py - src/memos/mem_scheduler/general_scheduler.py - src/memos/mem_scheduler/base_scheduler.py - src/memos/mem_scheduler/webservice_modules/rabbitmq_service.py * Fix(rabbitmq): Use env vars for KB updates and improve logging * Fix(rabbitmq): Explicitly use MEMSCHEDULER_RABBITMQ_EXCHANGE_NAME and empty routing key for KB updates * Fix(add_handler): Update diagnostic log timestamp * Fix(add_handler): Update diagnostic log timestamp again (auto-updated) * Update default scheduler redis stream prefix * Update diagnostic timestamp in add handler * Allow optional log_content in scheduler event log * feat: new examples to test scheduelr * feat: fair scheduler and refactor of search function * fix bugs: address bugs caused by outdated test code * feat: add task_schedule_monitor * fix: handle nil mem_cube in scheduler message consumers * fix bugs: response messaged changed in memos code * refactor: revise task queue to allow it dealing with pending tasks when no task remaining * refactor: revise mixture search and scheduler logger * Fix scheduler task tracking * fix bugs: address ai review issues * fix bugs: address rabbitmq initialization failed when doing pytest * fix(scheduler): Correct dispatcher task and future tracking * Remove dump.rdb * fix bugs: revised message ack logics; refactor add log function * fix bugs: change Chinese notation to English * fix indent error in logger * fix bugs: addressed the issues caused by multiprocessing codes obtain same pending tasks * addMemory/updateMemory log * fix bugs: modify redis queue logics to make it run as expected * feat: add a default mem cube initialization for scheduler * address scheduler init bug * feat(scheduler): Propagate trace_id across process boundaries for mem… (#592) feat(scheduler): Propagate trace_id across process boundaries for mem_scheduler logs This commit addresses the issue where 'trace_id' was missing from logs generated by the 'mem_scheduler' module, especially when tasks were executed in separate processes. The changes implement a manual propagation of 'trace_id' from the message producer to the consumer: 1. **Schema Update**: Added an optional 'trace_id' field to 'ScheduleMessageItem' in 'src/memos/mem_scheduler/schemas/message_schemas.py' to allow 'trace_id' to be carried within messages. 2. **Producer-side Capture**: Modified 'src/memos/mem_scheduler/task_schedule_modules/task_queue.py' to capture the current 'trace_id' and embed it into the 'ScheduleMessageItem' before messages are enqueued. 3. **Consumer-side Context Re-establishment**: Updated 'src/memos/mem_scheduler/task_schedule_modules/dispatcher.py' to extract the 'trace_id' from incoming messages and re-establish the logging context using 'RequestContext' for each task's execution. This ensures all logs within a task's scope correctly include its associated 'trace_id', even when crossing process boundaries. This approach ensures robust and accurate tracing of tasks within the scheduler, enhancing observability and debugging capabilities. Co-authored-by: [email protected] <> * fix bugs: redis queue allows to reget pending tasks which exceeding idle time * fix(scheduler): Correct lazy-loading logic for mem_cube property * Add MONITOR_EVENT logs for scheduler lifecycle * fix: Resolve Ruff linting and formatting issues * Handle dequeue timestamp without pydantic errors * feat: orchestrator add task priority; move task labels into task_schemas; add synchronous execuation option in dispatcher * feat: more logs for debug * fix bugs: addresss some bugs * refactor: remove logger info in pref add function * refactor: change redis queue to periodically refresh pending tasks * feat: a faster and better redis queue * refactor: remove cleanup in redis queue * feat: allow directly execute task if task priority is level 1 * refactor: refactor log_add_handler and redis queue to make the code running better * fix bugs: fix the bug in _process_chat_data * fix: use message item_id for task status updates instead of execution id * style: format dispatcher.py with ruff * chore: emit dequeue for immediate tasks * fix: resolve ruff UP038 in base_scheduler.py * feat: add scheduler queue status endpoint * fix: lazy-init redis in queue status handler * fix: unwrap queue wrapper for redis status * fix bugs: fix a bug causing no schedule memory * feat: add a new env variable to set stream_prefix in redis; make add func hallucination filter to improve qualities of added memories * fix bugs: update start_listening in redis_queue * refactor: revise polardb and scheduelr init * feat: time task_broker; add a hallucination filter for simple struct add * feat & fix bugs: redis scheduler support periodically refresh active streams and deleted inactive streams; fix bugs of xautoclaims * refactor: revise the code according to llm suggestions * address ruff * modify examples * feat: process chunks from redis streams * refactor: update add operation * feat: status_tracker support lazy init * refactor: improve scheduler * fix bugs: rewrite retriever.search and resolve the json wrong decoding issue * refactor: revise add --------- Co-authored-by: fridayL <[email protected]> Co-authored-by: [email protected] <> Co-authored-by: Zehao Lin <[email protected]> Co-authored-by: chunyu li <[email protected]>
1 parent 610ac8c commit e9e4fb0

File tree

9 files changed

+473
-106
lines changed

9 files changed

+473
-106
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import time
2+
3+
from memos.api.routers.server_router import mem_scheduler
4+
from memos.mem_scheduler.task_schedule_modules.redis_queue import SchedulerRedisQueue
5+
6+
7+
queue = mem_scheduler.memos_message_queue.memos_message_queue
8+
9+
10+
def fetch_status(queue: SchedulerRedisQueue) -> dict[str, dict[str, int]]:
11+
"""Fetch and print per-user Redis queue status using built-in API.
12+
13+
Returns a dict mapping user_id -> {"pending": int, "remaining": int}.
14+
"""
15+
# This method will also print a summary and per-user counts.
16+
return queue.show_task_status()
17+
18+
19+
def print_diff(prev: dict[str, dict[str, int]], curr: dict[str, dict[str, int]]) -> None:
20+
"""Print aggregated totals and per-user changes compared to previous snapshot."""
21+
ts = time.strftime("%Y-%m-%d %H:%M:%S")
22+
tot_p_prev = sum(v.get("pending", 0) for v in prev.values()) if prev else 0
23+
tot_r_prev = sum(v.get("remaining", 0) for v in prev.values()) if prev else 0
24+
tot_p_curr = sum(v.get("pending", 0) for v in curr.values())
25+
tot_r_curr = sum(v.get("remaining", 0) for v in curr.values())
26+
27+
dp_tot = tot_p_curr - tot_p_prev
28+
dr_tot = tot_r_curr - tot_r_prev
29+
30+
print(f"[{ts}] Total pending={tot_p_curr} ({dp_tot:+d}), remaining={tot_r_curr} ({dr_tot:+d})")
31+
32+
# Print per-user deltas (current counts are already printed by show_task_status)
33+
all_uids = sorted(set(prev.keys()) | set(curr.keys()))
34+
for uid in all_uids:
35+
p_prev = prev.get(uid, {}).get("pending", 0)
36+
r_prev = prev.get(uid, {}).get("remaining", 0)
37+
p_curr = curr.get(uid, {}).get("pending", 0)
38+
r_curr = curr.get(uid, {}).get("remaining", 0)
39+
dp = p_curr - p_prev
40+
dr = r_curr - r_prev
41+
# Only print when there is any change to reduce noise
42+
if dp != 0 or dr != 0:
43+
print(f" Δ {uid}: pending={dp:+d}, remaining={dr:+d}")
44+
45+
46+
# Note: queue.show_task_status() handles printing per-user counts internally.
47+
48+
49+
def main(interval_sec: float = 5.0) -> None:
50+
prev: dict[str, dict[str, int]] = {}
51+
while True:
52+
try:
53+
curr = fetch_status(queue)
54+
print_diff(prev, curr)
55+
print(f"stream_cache ({len(queue._stream_keys_cache)}): {queue._stream_keys_cache}")
56+
prev = curr
57+
time.sleep(interval_sec)
58+
except KeyboardInterrupt:
59+
print("Stopped.")
60+
break
61+
except Exception as e:
62+
print(f"Error while fetching status: {e}")
63+
time.sleep(interval_sec)
64+
65+
66+
if __name__ == "__main__":
67+
main()

src/memos/mem_reader/simple_struct.py

Lines changed: 30 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -453,7 +453,7 @@ def get_memory(
453453
@staticmethod
454454
def _parse_hallucination_filter_response(text: str) -> tuple[bool, dict[int, dict]]:
455455
"""Parse index-keyed JSON from hallucination filter response.
456-
Expected shape: { "0": {"delete": bool, "rewritten": str, "reason": str}, ... }
456+
Expected shape: { "0": {"need_rewrite": bool, "rewritten": str, "reason": str}, ... }
457457
Returns (success, parsed_dict) with int keys.
458458
"""
459459
try:
@@ -476,27 +476,33 @@ def _parse_hallucination_filter_response(text: str) -> tuple[bool, dict[int, dic
476476
continue
477477
if not isinstance(v, dict):
478478
continue
479-
delete_flag = v.get("delete")
479+
need_rewrite = v.get("need_rewrite")
480480
rewritten = v.get("rewritten", "")
481481
reason = v.get("reason", "")
482482
if (
483-
isinstance(delete_flag, bool)
483+
isinstance(need_rewrite, bool)
484484
and isinstance(rewritten, str)
485485
and isinstance(reason, str)
486486
):
487-
result[idx] = {"delete": delete_flag, "rewritten": rewritten, "reason": reason}
487+
result[idx] = {
488+
"need_rewrite": need_rewrite,
489+
"rewritten": rewritten,
490+
"reason": reason,
491+
}
488492

489493
return (len(result) > 0), result
490494

491495
def filter_hallucination_in_memories(
492-
self, user_messages: list[str], memory_list: list[TextualMemoryItem]
496+
self, messages: list[dict], memory_list: list[TextualMemoryItem]
493497
) -> list[TextualMemoryItem]:
494-
flat_memories = [one.memory for one in memory_list]
498+
# Build input objects with memory text and metadata (timestamps, sources, etc.)
495499
template = PROMPT_MAPPING["hallucination_filter"]
496500
prompt_args = {
497-
"user_messages_inline": "\n".join([f"- {memory}" for memory in user_messages]),
501+
"messages_inline": "\n".join(
502+
[f"- [{message['role']}]: {message['content']}" for message in messages]
503+
),
498504
"memories_inline": json.dumps(
499-
{str(i): memory for i, memory in enumerate(flat_memories)},
505+
{idx: mem.memory for idx, mem in enumerate(memory_list)},
500506
ensure_ascii=False,
501507
indent=2,
502508
),
@@ -511,40 +517,25 @@ def filter_hallucination_in_memories(
511517
f"[filter_hallucination_in_memories] Hallucination filter parsed successfully: {success}"
512518
)
513519
if success:
520+
new_mem_list = []
514521
logger.info(f"Hallucination filter result: {parsed}")
515-
total = len(memory_list)
516-
keep_flags = [True] * total
522+
assert len(parsed) == len(memory_list)
517523
for mem_idx, content in parsed.items():
518-
# Validate index bounds
519-
if not isinstance(mem_idx, int) or mem_idx < 0 or mem_idx >= total:
520-
logger.warning(
521-
f"[filter_hallucination_in_memories] Ignoring out-of-range index: {mem_idx}"
522-
)
523-
continue
524-
525-
delete_flag = content.get("delete", False)
526-
rewritten = content.get("rewritten", None)
524+
need_rewrite = content.get("need_rewrite", False)
525+
rewritten = content.get("rewritten", "")
527526
reason = content.get("reason", "")
528527

529-
logger.info(
530-
f"[filter_hallucination_in_memories] index={mem_idx}, delete={delete_flag}, rewritten='{(rewritten or '')[:100]}', reason='{reason[:120]}'"
531-
)
532-
533-
if delete_flag is True and rewritten is not None:
534-
# Mark for deletion
535-
keep_flags[mem_idx] = False
536-
else:
537-
# Apply rewrite if provided (safe-by-default: keep item when not mentioned or delete=False)
538-
try:
539-
if isinstance(rewritten, str):
540-
memory_list[mem_idx].memory = rewritten
541-
except Exception as e:
542-
logger.warning(
543-
f"[filter_hallucination_in_memories] Failed to apply rewrite for index {mem_idx}: {e}"
544-
)
545-
546-
# Build result, preserving original order; keep items not mentioned by LLM by default
547-
new_mem_list = [memory_list[i] for i in range(total) if keep_flags[i]]
528+
# Apply rewriting if requested
529+
if (
530+
need_rewrite
531+
and isinstance(rewritten, str)
532+
and len(rewritten) > len(memory_list[mem_idx].memory)
533+
):
534+
memory_list[mem_idx].memory = rewritten
535+
logger.info(
536+
f"[filter_hallucination_in_memories] index={mem_idx}, need_rewrite={need_rewrite}, rewritten='{rewritten}', reason='{reason}', original memory='{memory_list[mem_idx].memory}'"
537+
)
538+
new_mem_list.append(memory_list[mem_idx])
548539
return new_mem_list
549540
else:
550541
logger.warning("Hallucination filter parsing failed or returned empty result.")
@@ -602,11 +593,8 @@ def _read_memory(
602593
# Build inputs
603594
new_memory_list = []
604595
for unit_messages, unit_memory_list in zip(messages, memory_list, strict=False):
605-
unit_user_messages = [
606-
msg["content"] for msg in unit_messages if msg["role"] == "user"
607-
]
608596
unit_memory_list = self.filter_hallucination_in_memories(
609-
user_messages=unit_user_messages, memory_list=unit_memory_list
597+
messages=unit_messages, memory_list=unit_memory_list
610598
)
611599
new_memory_list.append(unit_memory_list)
612600
memory_list = new_memory_list

src/memos/mem_scheduler/general_scheduler.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ def long_memory_update_process(
144144
old_memory_texts = [mem.memory for mem in cur_working_memory]
145145
new_memory_texts = [mem.memory for mem in new_order_working_memory]
146146

147-
logger.debug(
147+
logger.info(
148148
f"[long_memory_update_process] For user_id='{user_id}', mem_cube_id='{mem_cube_id}': "
149149
f"Scheduler replaced working memory based on query history {queries}. "
150150
f"Old working memory ({len(old_memory_texts)} items): {old_memory_texts}. "
@@ -1413,17 +1413,16 @@ def process_session_turn(
14131413
logger.info(
14141414
f"[process_session_turn] Searching for missing evidence: '{item}' with top_k={k_per_evidence} for user_id={user_id}"
14151415
)
1416-
info = {
1417-
"user_id": user_id,
1418-
"session_id": "",
1419-
}
14201416

1417+
search_args = {}
14211418
results: list[TextualMemoryItem] = self.retriever.search(
14221419
query=item,
1420+
user_id=user_id,
1421+
mem_cube_id=mem_cube_id,
14231422
mem_cube=mem_cube,
14241423
top_k=k_per_evidence,
14251424
method=self.search_method,
1426-
info=info,
1425+
search_args=search_args,
14271426
)
14281427
logger.info(
14291428
f"[process_session_turn] Search results for missing evidence '{item}': {[one.memory for one in results]}"

src/memos/mem_scheduler/memory_manage_modules/retriever.py

Lines changed: 64 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,11 @@
2222
from memos.mem_scheduler.utils.misc_utils import extract_json_obj, extract_list_items_in_answer
2323
from memos.memories.textual.item import TextualMemoryMetadata
2424
from memos.memories.textual.tree import TextualMemoryItem, TreeTextMemory
25-
from memos.types.general_types import FINE_STRATEGY, FineStrategy
25+
from memos.types.general_types import (
26+
FINE_STRATEGY,
27+
FineStrategy,
28+
SearchMode,
29+
)
2630

2731
# Extract JSON response
2832
from .memory_filter import MemoryFilter
@@ -237,10 +241,12 @@ def recall_for_missing_memories(
237241
def search(
238242
self,
239243
query: str,
244+
user_id: str,
245+
mem_cube_id: str,
240246
mem_cube: GeneralMemCube,
241247
top_k: int,
242248
method: str = TreeTextMemory_SEARCH_METHOD,
243-
info: dict | None = None,
249+
search_args: dict | None = None,
244250
) -> list[TextualMemoryItem]:
245251
"""Search in text memory with the given query.
246252
@@ -253,22 +259,67 @@ def search(
253259
Search results or None if not implemented
254260
"""
255261
text_mem_base = mem_cube.text_mem
262+
# Normalize default for mutable argument
263+
search_args = search_args or {}
256264
try:
257265
if method in [TreeTextMemory_SEARCH_METHOD, TreeTextMemory_FINE_SEARCH_METHOD]:
258266
assert isinstance(text_mem_base, TreeTextMemory)
259-
if info is None:
260-
logger.warning(
261-
"Please input 'info' when use tree.search so that "
262-
"the database would store the consume history."
263-
)
264-
info = {"user_id": "", "session_id": ""}
267+
session_id = search_args.get("session_id", "default_session")
268+
target_session_id = session_id
269+
search_priority = (
270+
{"session_id": target_session_id} if "session_id" in search_args else None
271+
)
272+
search_filter = search_args.get("filter")
273+
search_source = search_args.get("source")
274+
plugin = bool(search_source is not None and search_source == "plugin")
275+
user_name = search_args.get("user_name", mem_cube_id)
276+
internet_search = search_args.get("internet_search", False)
277+
chat_history = search_args.get("chat_history")
278+
search_tool_memory = search_args.get("search_tool_memory", False)
279+
tool_mem_top_k = search_args.get("tool_mem_top_k", 6)
280+
playground_search_goal_parser = search_args.get(
281+
"playground_search_goal_parser", False
282+
)
265283

266-
mode = "fast" if method == TreeTextMemory_SEARCH_METHOD else "fine"
267-
results_long_term = text_mem_base.search(
268-
query=query, top_k=top_k, memory_type="LongTermMemory", mode=mode, info=info
284+
info = search_args.get(
285+
"info",
286+
{
287+
"user_id": user_id,
288+
"session_id": target_session_id,
289+
"chat_history": chat_history,
290+
},
269291
)
270-
results_user = text_mem_base.search(
271-
query=query, top_k=top_k, memory_type="UserMemory", mode=mode, info=info
292+
293+
results_long_term = mem_cube.text_mem.search(
294+
query=query,
295+
user_name=user_name,
296+
top_k=top_k,
297+
mode=SearchMode.FAST,
298+
manual_close_internet=not internet_search,
299+
memory_type="LongTermMemory",
300+
search_filter=search_filter,
301+
search_priority=search_priority,
302+
info=info,
303+
plugin=plugin,
304+
search_tool_memory=search_tool_memory,
305+
tool_mem_top_k=tool_mem_top_k,
306+
playground_search_goal_parser=playground_search_goal_parser,
307+
)
308+
309+
results_user = mem_cube.text_mem.search(
310+
query=query,
311+
user_name=user_name,
312+
top_k=top_k,
313+
mode=SearchMode.FAST,
314+
manual_close_internet=not internet_search,
315+
memory_type="UserMemory",
316+
search_filter=search_filter,
317+
search_priority=search_priority,
318+
info=info,
319+
plugin=plugin,
320+
search_tool_memory=search_tool_memory,
321+
tool_mem_top_k=tool_mem_top_k,
322+
playground_search_goal_parser=playground_search_goal_parser,
272323
)
273324
results = results_long_term + results_user
274325
else:

src/memos/mem_scheduler/schemas/task_schemas.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,6 @@ class TaskPriorityLevel(Enum):
4545
USER_INPUT_TYPE = "UserInput"
4646
NOT_APPLICABLE_TYPE = "NotApplicable"
4747

48-
# pending claim configuration
49-
# Only claim pending messages whose idle time exceeds this threshold.
50-
# Unit: milliseconds. Default: 10 minute.
51-
DEFAULT_PENDING_CLAIM_MIN_IDLE_MS = 600_000
5248

5349
# scheduler daemon defaults
5450
# Interval in seconds for periodically releasing stale pending messages
@@ -60,15 +56,22 @@ class TaskPriorityLevel(Enum):
6056
# Interval in seconds for batching and cleaning up deletions (xdel)
6157
DEFAULT_DELETE_CLEANUP_INTERVAL_SEC = 30.0
6258

63-
# Inactivity threshold for stream deletion
64-
# Delete streams whose last message ID timestamp is older than this threshold.
65-
# Unit: seconds. Default: 1 day.
66-
DEFAULT_STREAM_INACTIVITY_DELETE_SECONDS = 86_400.0
59+
# pending claim configuration
60+
# Only claim pending messages whose idle time exceeds this threshold.
61+
# Unit: milliseconds. Default: 1 hour.
62+
DEFAULT_PENDING_CLAIM_MIN_IDLE_MS = 3_600_000
63+
6764

6865
# Recency threshold for active streams
6966
# Consider a stream "active" if its last message is within this window.
70-
# Unit: seconds. Default: 30 minutes.
71-
DEFAULT_STREAM_RECENT_ACTIVE_SECONDS = 1_800.0
67+
# Unit: seconds. Default: 1 hours.
68+
DEFAULT_STREAM_RECENT_ACTIVE_SECONDS = 3_600.0
69+
70+
71+
# Inactivity threshold for stream deletion
72+
# Delete streams whose last message ID timestamp is older than this threshold.
73+
# Unit: seconds. Default: 2 hour.
74+
DEFAULT_STREAM_INACTIVITY_DELETE_SECONDS = 7_200.0
7275

7376

7477
# task queue

0 commit comments

Comments
 (0)