Skip to content

Commit 43faee0

Browse files
tangg555fridayLglin93
authored
new feat: add enhancement and env variable for scheduler (#650)
* 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 --------- Co-authored-by: fridayL <[email protected]> Co-authored-by: [email protected] <> Co-authored-by: Zehao Lin <[email protected]>
1 parent dc69cb2 commit 43faee0

File tree

11 files changed

+196
-21
lines changed

11 files changed

+196
-21
lines changed

examples/mem_scheduler/try_schedule_modules.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,14 +41,26 @@ def init_task():
4141
"role": "user",
4242
"content": "Max needs joint supplements. Actually, we're moving to Chicago next month.",
4343
},
44+
{
45+
"role": "assistant",
46+
"content": "Got it — Max is on joint supplements, and you’re relocating to Chicago soon. That’s a big move! Have you looked into how the change in climate or vet access might affect his needs?",
47+
},
4448
{
4549
"role": "user",
4650
"content": "Correction: Bella is 6, not 5. And she's allergic to chicken.",
4751
},
52+
{
53+
"role": "assistant",
54+
"content": "Thanks for the update! So Bella is 6 years old and has a chicken allergy — good to know. You’ll want to double-check her food and treats, especially during the move. Has she had any reactions recently?",
55+
},
4856
{
4957
"role": "user",
5058
"content": "My partner's cat Whiskers visits weekends. Bella chases her sometimes.",
5159
},
60+
{
61+
"role": "assistant",
62+
"content": "Ah, the classic dog-and-cat dynamic! Since Bella chases Whiskers, it might help to give them gradual supervised interactions or create safe zones for the cat—especially important as you settle into a new home in Chicago. Keeping Bella’s routine stable during the move could also reduce her urge to chase. How do they usually get along when Whiskers visits?",
63+
},
5264
]
5365

5466
questions = [
@@ -145,18 +157,25 @@ def start_conversation(self, user_id="test_user", mem_cube_id="test_cube", sessi
145157
print(f" User ID: {self.current_user_id}")
146158
print(f" Mem Cube ID: {self.current_mem_cube_id}")
147159

148-
def add_msgs(self, messages: list[dict]):
160+
def add_msgs(
161+
self,
162+
messages: list[dict],
163+
extract_mode: str = "fine",
164+
async_mode: str = "sync",
165+
):
149166
# Create add request
150167
add_req = self.create_test_add_request(
151168
user_id=self.current_user_id,
152169
mem_cube_id=self.current_mem_cube_id,
153170
messages=messages,
154171
session_id=self.current_session_id,
172+
extract_mode=extract_mode,
173+
async_mode=async_mode,
155174
)
156175

157176
# Add to memory
158177
result = self.add_memories(add_req)
159-
print(f" ✅ Added to memory successfully: \n{messages}")
178+
print(f" ✅ Added to memory successfully: \n{result}")
160179

161180
return result
162181

src/memos/mem_reader/simple_struct.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import concurrent.futures
22
import copy
33
import json
4+
import os
45
import re
56
import traceback
67

@@ -25,6 +26,7 @@
2526
from memos.templates.mem_reader_prompts import (
2627
CUSTOM_TAGS_INSTRUCTION,
2728
CUSTOM_TAGS_INSTRUCTION_ZH,
29+
PROMPT_MAPPING,
2830
SIMPLE_STRUCT_DOC_READER_PROMPT,
2931
SIMPLE_STRUCT_DOC_READER_PROMPT_ZH,
3032
SIMPLE_STRUCT_MEM_READER_EXAMPLE,
@@ -80,6 +82,7 @@ def from_config(_config):
8082
"custom_tags": {"en": CUSTOM_TAGS_INSTRUCTION, "zh": CUSTOM_TAGS_INSTRUCTION_ZH},
8183
}
8284

85+
8386
try:
8487
import tiktoken
8588

@@ -448,6 +451,81 @@ def get_memory(
448451
standard_scene_data = coerce_scene_data(scene_data, type)
449452
return self._read_memory(standard_scene_data, type, info, mode)
450453

454+
@staticmethod
455+
def _parse_hallucination_filter_response(text: str) -> tuple[bool, dict[int, dict]]:
456+
"""Parse index-keyed JSON from hallucination filter response.
457+
Expected shape: { "0": {"if_delete": bool, "rewritten memory content": str}, ... }
458+
Returns (success, parsed_dict) with int keys.
459+
"""
460+
try:
461+
data = json.loads(text)
462+
except Exception:
463+
return False, {}
464+
465+
if not isinstance(data, dict):
466+
return False, {}
467+
468+
result: dict[int, dict] = {}
469+
for k, v in data.items():
470+
try:
471+
idx = int(k)
472+
except Exception:
473+
# allow integer keys as-is
474+
if isinstance(k, int):
475+
idx = k
476+
else:
477+
continue
478+
if not isinstance(v, dict):
479+
continue
480+
delete_flag = v.get("delete_flag")
481+
rewritten = v.get("rewritten memory content", "")
482+
if isinstance(delete_flag, bool) and isinstance(rewritten, str):
483+
result[idx] = {"delete_flag": delete_flag, "rewritten memory content": rewritten}
484+
485+
return (len(result) > 0), result
486+
487+
def filter_hallucination_in_memories(
488+
self, user_messages: list[str], memory_list: list[list[TextualMemoryItem]]
489+
):
490+
filtered_memory_list = []
491+
for group in memory_list:
492+
try:
493+
flat_memories = [one.memory for one in group]
494+
template = PROMPT_MAPPING["hallucination_filter"]
495+
prompt_args = {
496+
"user_messages_inline": "\n".join(user_messages),
497+
"memories_inline": json.dumps(flat_memories, ensure_ascii=False, indent=2),
498+
}
499+
prompt = template.format(**prompt_args)
500+
501+
# Optionally run filter and parse the output
502+
try:
503+
raw = self.llm.generate(prompt)
504+
success, parsed = self._parse_hallucination_filter_response(raw)
505+
logger.info(f"Hallucination filter parsed successfully: {success}")
506+
new_mem_list = []
507+
if success:
508+
logger.info(f"Hallucination filter result: {parsed}")
509+
for mem_idx, (delete_flag, rewritten_mem_content) in parsed.items():
510+
if not delete_flag:
511+
group[mem_idx].memory = rewritten_mem_content
512+
new_mem_list.append(group[mem_idx])
513+
filtered_memory_list.append(new_mem_list)
514+
logger.info(
515+
f"Successfully transform origianl memories from {group} to {new_mem_list}."
516+
)
517+
else:
518+
logger.warning(
519+
"Hallucination filter parsing failed or returned empty result."
520+
)
521+
except Exception as e:
522+
logger.error(f"Hallucination filter execution error: {e}", stack_info=True)
523+
filtered_memory_list.append(group)
524+
except Exception:
525+
logger.error("Fail to filter memories", stack_info=True)
526+
filtered_memory_list.append(group)
527+
return filtered_memory_list
528+
451529
def _read_memory(
452530
self, messages: list[MessagesType], type: str, info: dict[str, Any], mode: str = "fine"
453531
) -> list[list[TextualMemoryItem]]:
@@ -492,6 +570,14 @@ def _read_memory(
492570
except Exception as e:
493571
logger.error(f"Task failed with exception: {e}")
494572
logger.error(traceback.format_exc())
573+
574+
if os.getenv("SIMPLE_STRUCT_ADD_FILTER", "false") == "true":
575+
# Build inputs
576+
user_messages = [msg.content for msg in messages if msg.role == "user"]
577+
memory_list = self.filter_hallucination_in_memories(
578+
user_messages=user_messages, memory_list=memory_list
579+
)
580+
495581
return memory_list
496582

497583
def fine_transfer_simple_mem(

src/memos/mem_scheduler/analyzer/api_analyzer.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -599,6 +599,8 @@ def create_test_add_request(
599599
messages=None,
600600
memory_content=None,
601601
session_id=None,
602+
extract_mode=None,
603+
async_mode="sync",
602604
):
603605
"""
604606
Create a test APIADDRequest object with the given parameters.
@@ -637,6 +639,8 @@ def create_test_add_request(
637639
source="api_analyzer_test",
638640
chat_history=None,
639641
operation=None,
642+
mode=extract_mode,
643+
async_mode=async_mode,
640644
)
641645

642646
def run_all_tests(self, mode=SearchMode.MIXTURE):

src/memos/mem_scheduler/base_scheduler.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -140,12 +140,7 @@ def __init__(self, config: BaseSchedulerConfig):
140140
"max_internal_message_queue_size", DEFAULT_MAX_INTERNAL_MESSAGE_QUEUE_SIZE
141141
)
142142
self.orchestrator = SchedulerOrchestrator()
143-
self.memos_message_queue = ScheduleTaskQueue(
144-
use_redis_queue=self.use_redis_queue,
145-
maxsize=self.max_internal_message_queue_size,
146-
disabled_handlers=self.disabled_handlers,
147-
orchestrator=self.orchestrator,
148-
)
143+
149144
self.searcher: Searcher | None = None
150145
self.retriever: SchedulerRetriever | None = None
151146
self.db_engine: Engine | None = None
@@ -155,6 +150,13 @@ def __init__(self, config: BaseSchedulerConfig):
155150
self.status_tracker: TaskStatusTracker | None = None
156151
self.metrics = metrics
157152
self._monitor_thread = None
153+
self.memos_message_queue = ScheduleTaskQueue(
154+
use_redis_queue=self.use_redis_queue,
155+
maxsize=self.max_internal_message_queue_size,
156+
disabled_handlers=self.disabled_handlers,
157+
orchestrator=self.orchestrator,
158+
status_tracker=self.status_tracker,
159+
)
158160
self.dispatcher = SchedulerDispatcher(
159161
config=self.config,
160162
memos_message_queue=self.memos_message_queue,
@@ -228,6 +230,8 @@ def initialize_modules(
228230
self.status_tracker = TaskStatusTracker(redis_client)
229231
if self.dispatcher:
230232
self.dispatcher.status_tracker = self.status_tracker
233+
if self.memos_message_queue:
234+
self.memos_message_queue.status_tracker = self.status_tracker
231235
# initialize submodules
232236
self.chat_llm = chat_llm
233237
self.process_llm = process_llm

src/memos/mem_scheduler/general_modules/misc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ def put(self, item: T, block: bool = False, timeout: float | None = None) -> Non
233233

234234
def get(
235235
self, block: bool = True, timeout: float | None = None, batch_size: int | None = None
236-
) -> list[T] | T:
236+
) -> list[T]:
237237
"""Get items from the queue.
238238
239239
Args:

src/memos/mem_scheduler/schemas/task_schemas.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,9 @@ class TaskPriorityLevel(Enum):
6262

6363

6464
# task queue
65-
DEFAULT_STREAM_KEY_PREFIX = "scheduler:messages:stream:v1.7"
66-
exchange_name = os.getenv("MEMSCHEDULER_RABBITMQ_EXCHANGE_NAME", None)
67-
if exchange_name is not None:
68-
DEFAULT_STREAM_KEY_PREFIX += f":{exchange_name}"
65+
DEFAULT_STREAM_KEY_PREFIX = os.getenv(
66+
"MEMSCHEDULER_STREAM_KEY_PREFIX", "scheduler:messages:stream:v2.0"
67+
)
6968

7069

7170
# ============== Running Tasks ==============

src/memos/mem_scheduler/task_schedule_modules/dispatcher.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,7 @@ def wrapped_handler(messages: list[ScheduleMessageItem]):
273273
mem_cube_id=msg.mem_cube_id,
274274
task_label=msg.label,
275275
redis_message_id=redis_message_id,
276+
message=msg,
276277
)
277278
except Exception as ack_err:
278279
logger.warning(f"Ack in finally failed: {ack_err}")

src/memos/mem_scheduler/task_schedule_modules/redis_queue.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,12 @@ def put(
328328
raise
329329

330330
def ack_message(
331-
self, user_id: str, mem_cube_id: str, task_label: str, redis_message_id
331+
self,
332+
user_id: str,
333+
mem_cube_id: str,
334+
task_label: str,
335+
redis_message_id,
336+
message: ScheduleMessageItem | None,
332337
) -> None:
333338
stream_key = self.get_stream_key(
334339
user_id=user_id, mem_cube_id=mem_cube_id, task_label=task_label
@@ -347,6 +352,12 @@ def ack_message(
347352

348353
try:
349354
self._redis_conn.xack(stream_key, self.consumer_group, redis_message_id)
355+
356+
if message:
357+
self.status_tracker.task_completed(task_id=message.item_id, user_id=message.user_id)
358+
logger.info(
359+
f"Message {message.item_id} | {message.label} | {message.content} has been acknowledged."
360+
)
350361
except Exception as e:
351362
logger.warning(
352363
f"xack failed for stream '{stream_key}', msg_id='{redis_message_id}': {e}"
@@ -364,7 +375,7 @@ def get(
364375
stream_key: str,
365376
block: bool = True,
366377
timeout: float | None = None,
367-
batch_size: int | None = None,
378+
batch_size: int | None = 1,
368379
) -> list[ScheduleMessageItem]:
369380
if not self._redis_conn:
370381
raise ConnectionError("Not connected to Redis. Redis connection not available.")
@@ -385,7 +396,7 @@ def get(
385396
self.consumer_group,
386397
self.consumer_name,
387398
{stream_key: ">"},
388-
count=(batch_size if batch_size is not None else None),
399+
count=batch_size,
389400
block=redis_timeout,
390401
)
391402
except Exception as read_err:
@@ -400,7 +411,7 @@ def get(
400411
self.consumer_group,
401412
self.consumer_name,
402413
{stream_key: ">"},
403-
count=(batch_size if batch_size is not None else None),
414+
count=batch_size,
404415
block=redis_timeout,
405416
)
406417
else:
@@ -492,7 +503,7 @@ def get(
492503

493504
raise Empty("No messages available in Redis queue")
494505

495-
return result_messages if batch_size is not None else result_messages[0]
506+
return result_messages
496507

497508
except Exception as e:
498509
if "Empty" in str(type(e).__name__):
@@ -630,7 +641,7 @@ def start_listening(
630641

631642
try:
632643
while self._is_listening:
633-
messages = self.get(timeout=poll_interval, count=batch_size)
644+
messages = self.get_messages(batch_size=1)
634645

635646
for message in messages:
636647
try:

src/memos/mem_scheduler/task_schedule_modules/task_queue.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from memos.mem_scheduler.utils.db_utils import get_utc_now
1515
from memos.mem_scheduler.utils.misc_utils import group_messages_by_user_and_mem_cube
1616
from memos.mem_scheduler.utils.monitor_event_utils import emit_monitor_event, to_iso
17+
from memos.mem_scheduler.utils.status_tracker import TaskStatusTracker
1718

1819

1920
logger = get_logger(__name__)
@@ -26,10 +27,12 @@ def __init__(
2627
maxsize: int,
2728
disabled_handlers: list | None = None,
2829
orchestrator: SchedulerOrchestrator | None = None,
30+
status_tracker: TaskStatusTracker | None = None,
2931
):
3032
self.use_redis_queue = use_redis_queue
3133
self.maxsize = maxsize
3234
self.orchestrator = SchedulerOrchestrator() if orchestrator is None else orchestrator
35+
self.status_tracker = status_tracker
3336

3437
if self.use_redis_queue:
3538
if maxsize is None or not isinstance(maxsize, int) or maxsize <= 0:
@@ -51,6 +54,7 @@ def ack_message(
5154
mem_cube_id: str,
5255
task_label: str,
5356
redis_message_id,
57+
message: ScheduleMessageItem | None,
5458
) -> None:
5559
if not isinstance(self.memos_message_queue, SchedulerRedisQueue):
5660
logger.warning("ack_message is only supported for Redis queues")
@@ -61,6 +65,7 @@ def ack_message(
6165
mem_cube_id=mem_cube_id,
6266
task_label=task_label,
6367
redis_message_id=redis_message_id,
68+
message=message,
6469
)
6570

6671
def get_stream_keys(self) -> list[str]:

src/memos/multi_mem_cube/single_cube.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,11 @@ def add_memories(self, add_req: APIADDRequest) -> list[dict[str, Any]]:
9393
for item in pref_results:
9494
item["cube_id"] = self.cube_id
9595

96-
return text_results + pref_results
96+
all_memories = text_results + pref_results
97+
98+
# TODO: search existing memories and compare
99+
100+
return all_memories
97101

98102
def search_memories(self, search_req: APISearchRequest) -> dict[str, Any]:
99103
# Create UserContext object
@@ -692,11 +696,13 @@ def _process_text_mem(
692696
sync_mode=sync_mode,
693697
)
694698

695-
return [
699+
text_memories = [
696700
{
697701
"memory": memory.memory,
698702
"memory_id": memory_id,
699703
"memory_type": memory.metadata.memory_type,
700704
}
701705
for memory_id, memory in zip(mem_ids_local, flattened_local, strict=False)
702706
]
707+
708+
return text_memories

0 commit comments

Comments
 (0)