Skip to content

Commit 5679474

Browse files
tangg555fridayLglin93
authored
feat: a range of new feats to make a better redis scheduler (#630)
* 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 --------- Co-authored-by: fridayL <[email protected]> Co-authored-by: [email protected] <> Co-authored-by: Zehao Lin <[email protected]>
1 parent 4746f2a commit 5679474

File tree

12 files changed

+499
-147
lines changed

12 files changed

+499
-147
lines changed

examples/mem_scheduler/task_stop_rerun.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ def my_test_handler(messages: list[ScheduleMessageItem]):
2828
try:
2929
print(f"writing {file_path}...")
3030
file_path.write_text(f"Task {task_id} processed.\n")
31+
sleep(5)
3132
except Exception as e:
3233
print(f"Failed to write {file_path}: {e}")
3334

@@ -57,6 +58,8 @@ def submit_tasks():
5758
TEST_HANDLER_LABEL = "test_handler"
5859
mem_scheduler.register_handlers({TEST_HANDLER_LABEL: my_test_handler})
5960

61+
# 10s to restart
62+
mem_scheduler.orchestrator.tasks_min_idle_ms[TEST_HANDLER_LABEL] = 10_000
6063

6164
tmp_dir = Path("./tmp")
6265
tmp_dir.mkdir(exist_ok=True)
@@ -69,10 +72,15 @@ def submit_tasks():
6972
submit_tasks()
7073

7174
# 6. Wait until tmp has 100 files or timeout
72-
poll_interval = 0.01
75+
poll_interval = 1
7376
expected = 100
7477
tmp_dir = Path("tmp")
75-
while mem_scheduler.get_tasks_status()["remaining"] != 0:
78+
tasks_status = mem_scheduler.get_tasks_status()
79+
mem_scheduler.print_tasks_status(tasks_status=tasks_status)
80+
while (
81+
mem_scheduler.get_tasks_status()["remaining"] != 0
82+
or mem_scheduler.get_tasks_status()["running"] != 0
83+
):
7684
count = len(list(tmp_dir.glob("*.txt"))) if tmp_dir.exists() else 0
7785
tasks_status = mem_scheduler.get_tasks_status()
7886
mem_scheduler.print_tasks_status(tasks_status=tasks_status)

src/memos/api/handlers/scheduler_handler.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,13 @@
2222
AllStatusResponseData,
2323
StatusResponse,
2424
StatusResponseItem,
25+
TaskQueueData,
26+
TaskQueueResponse,
2527
TaskSummary,
2628
)
2729
from memos.log import get_logger
2830
from memos.mem_scheduler.base_scheduler import BaseScheduler
31+
from memos.mem_scheduler.optimized_scheduler import OptimizedScheduler
2932
from memos.mem_scheduler.utils.status_tracker import TaskStatusTracker
3033

3134

@@ -243,6 +246,96 @@ def handle_scheduler_status(
243246
raise HTTPException(status_code=500, detail="Failed to get scheduler status") from err
244247

245248

249+
def handle_task_queue_status(
250+
user_id: str, mem_scheduler: OptimizedScheduler, task_id: str | None = None
251+
) -> TaskQueueResponse:
252+
try:
253+
queue = getattr(mem_scheduler, "memos_message_queue", None)
254+
if queue is None:
255+
raise HTTPException(status_code=503, detail="Scheduler queue is not available")
256+
257+
# Only support Redis-backed queue for now; try lazy init if not connected
258+
redis_conn = getattr(queue, "_redis_conn", None)
259+
if redis_conn is None:
260+
try:
261+
if hasattr(queue, "auto_initialize_redis"):
262+
queue.auto_initialize_redis()
263+
redis_conn = getattr(queue, "_redis_conn", None)
264+
if redis_conn and hasattr(queue, "connect"):
265+
queue.connect()
266+
except Exception:
267+
redis_conn = None
268+
269+
if redis_conn is None:
270+
raise HTTPException(status_code=503, detail="Scheduler queue not connected to Redis")
271+
272+
stream_keys = queue.get_stream_keys()
273+
# Filter by user_id; stream key format: {prefix}:{user_id}:{mem_cube_id}:{task_label}
274+
user_stream_keys = [sk for sk in stream_keys if f":{user_id}:" in sk]
275+
276+
if not user_stream_keys:
277+
raise HTTPException(
278+
status_code=404, detail=f"No scheduler streams found for user {user_id}"
279+
)
280+
281+
def _parse_user_id_from_stream(stream_key: str) -> str | None:
282+
try:
283+
parts = stream_key.split(":")
284+
if len(parts) < 3:
285+
return None
286+
# prefix may contain multiple segments; user_id is the 2nd segment from the end - 1
287+
return parts[-3]
288+
except Exception:
289+
return None
290+
291+
user_ids_present = {
292+
uid for uid in (_parse_user_id_from_stream(sk) for sk in stream_keys) if uid
293+
}
294+
295+
pending_total = 0
296+
pending_detail: list[str] = []
297+
remaining_total = 0
298+
remaining_detail: list[str] = []
299+
300+
consumer_group = getattr(queue, "consumer_group", None) or "scheduler_group"
301+
for sk in user_stream_keys:
302+
try:
303+
pending_info = redis_conn.xpending(sk, consumer_group)
304+
pending_count = pending_info[0] if pending_info else 0
305+
except Exception:
306+
pending_count = 0
307+
pending_total += pending_count
308+
pending_detail.append(f"{sk}:{pending_count}")
309+
310+
try:
311+
remaining_count = redis_conn.xlen(sk)
312+
except Exception:
313+
remaining_count = 0
314+
remaining_total += remaining_count
315+
remaining_detail.append(f"{sk}:{remaining_count}")
316+
317+
data = TaskQueueData(
318+
user_id=user_id,
319+
user_name=None,
320+
mem_cube_id=None,
321+
stream_keys=user_stream_keys,
322+
users_count=len(user_ids_present),
323+
pending_tasks_count=pending_total,
324+
remaining_tasks_count=remaining_total,
325+
pending_tasks_detail=pending_detail,
326+
remaining_tasks_detail=remaining_detail,
327+
)
328+
return TaskQueueResponse(data=data)
329+
except HTTPException:
330+
# Re-raise HTTPException directly to preserve its status code (e.g., 404)
331+
raise
332+
except Exception as err:
333+
logger.error(
334+
f"Failed to get task queue status for user {user_id}: {traceback.format_exc()}"
335+
)
336+
raise HTTPException(status_code=500, detail="Failed to get scheduler status") from err
337+
338+
246339
def handle_scheduler_wait(
247340
user_name: str,
248341
status_tracker: TaskStatusTracker,

src/memos/api/product_models.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -884,6 +884,34 @@ class StatusResponse(BaseResponse[list[StatusResponseItem]]):
884884
message: str = "Memory get status successfully"
885885

886886

887+
class TaskQueueData(BaseModel):
888+
"""Queue-level metrics for scheduler tasks."""
889+
890+
user_id: str = Field(..., description="User ID the query is scoped to")
891+
user_name: str | None = Field(None, description="User name if available")
892+
mem_cube_id: str | None = Field(
893+
None, description="MemCube ID if a single cube is targeted; otherwise None"
894+
)
895+
stream_keys: list[str] = Field(..., description="Matched Redis stream keys for this user")
896+
users_count: int = Field(..., description="Distinct users currently present in queue streams")
897+
pending_tasks_count: int = Field(
898+
..., description="Count of pending (delivered, not acked) tasks"
899+
)
900+
remaining_tasks_count: int = Field(..., description="Count of enqueued tasks (xlen)")
901+
pending_tasks_detail: list[str] = Field(
902+
..., description="Per-stream pending counts, formatted as '{stream_key}:{count}'"
903+
)
904+
remaining_tasks_detail: list[str] = Field(
905+
..., description="Per-stream remaining counts, formatted as '{stream_key}:{count}'"
906+
)
907+
908+
909+
class TaskQueueResponse(BaseResponse[TaskQueueData]):
910+
"""Response model for scheduler task queue status."""
911+
912+
message: str = "Scheduler task queue status retrieved successfully"
913+
914+
887915
class TaskSummary(BaseModel):
888916
"""Aggregated counts of tasks by status."""
889917

src/memos/api/routers/server_router.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
StatusResponse,
4242
SuggestionRequest,
4343
SuggestionResponse,
44+
TaskQueueResponse,
4445
)
4546
from memos.log import get_logger
4647
from memos.mem_scheduler.base_scheduler import BaseScheduler
@@ -143,6 +144,20 @@ def scheduler_status(
143144
)
144145

145146

147+
@router.get( # Changed from post to get
148+
"/scheduler/task_queue_status",
149+
summary="Get scheduler task queue status",
150+
response_model=TaskQueueResponse,
151+
)
152+
def scheduler_task_queue_status(
153+
user_id: str = Query(..., description="User ID whose queue status is requested"),
154+
):
155+
"""Get scheduler task queue backlog/pending status for a user."""
156+
return handlers.scheduler_handler.handle_task_queue_status(
157+
user_id=user_id, mem_scheduler=mem_scheduler
158+
)
159+
160+
146161
@router.post("/scheduler/wait", summary="Wait until scheduler is idle for a specific user")
147162
def scheduler_wait(
148163
user_name: str,

src/memos/configs/mem_reader.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ def parse_datetime(cls, value):
4444
class SimpleStructMemReaderConfig(BaseMemReaderConfig):
4545
"""SimpleStruct MemReader configuration class."""
4646

47+
# Allow passing additional fields without raising validation errors
4748
model_config = ConfigDict(extra="allow", strict=True)
4849

4950

src/memos/mem_scheduler/base_scheduler.py

Lines changed: 116 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import time
55

66
from collections.abc import Callable
7+
from contextlib import suppress
78
from datetime import datetime, timezone
89
from pathlib import Path
910
from typing import TYPE_CHECKING, Union
@@ -47,6 +48,15 @@
4748
ScheduleMessageItem,
4849
)
4950
from memos.mem_scheduler.schemas.monitor_schemas import MemoryMonitorItem
51+
from memos.mem_scheduler.schemas.task_schemas import (
52+
ADD_TASK_LABEL,
53+
ANSWER_TASK_LABEL,
54+
MEM_ARCHIVE_TASK_LABEL,
55+
MEM_ORGANIZE_TASK_LABEL,
56+
MEM_UPDATE_TASK_LABEL,
57+
QUERY_TASK_LABEL,
58+
TaskPriorityLevel,
59+
)
5060
from memos.mem_scheduler.task_schedule_modules.dispatcher import SchedulerDispatcher
5161
from memos.mem_scheduler.task_schedule_modules.orchestrator import SchedulerOrchestrator
5262
from memos.mem_scheduler.task_schedule_modules.task_queue import ScheduleTaskQueue
@@ -55,6 +65,7 @@
5565
from memos.mem_scheduler.utils.filter_utils import (
5666
transform_name_to_key,
5767
)
68+
from memos.mem_scheduler.utils.misc_utils import group_messages_by_user_and_mem_cube
5869
from memos.mem_scheduler.utils.monitor_event_utils import emit_monitor_event, to_iso
5970
from memos.mem_scheduler.utils.status_tracker import TaskStatusTracker
6071
from memos.mem_scheduler.webservice_modules.rabbitmq_service import RabbitMQSchedulerModule
@@ -642,19 +653,115 @@ def update_activation_memory_periodically(
642653
logger.error(f"Error in update_activation_memory_periodically: {e}", exc_info=True)
643654

644655
def submit_messages(self, messages: ScheduleMessageItem | list[ScheduleMessageItem]):
656+
"""Submit messages for processing, with priority-aware dispatch.
657+
658+
- LEVEL_1 tasks dispatch immediately to the appropriate handler.
659+
- Lower-priority tasks are enqueued via the configured message queue.
660+
"""
645661
if isinstance(messages, ScheduleMessageItem):
646662
messages = [messages]
647-
for message in messages:
648-
self.metrics.task_enqueued(user_id=message.user_id, task_type=message.label)
663+
664+
if not messages:
665+
return
666+
667+
immediate_msgs: list[ScheduleMessageItem] = []
668+
queued_msgs: list[ScheduleMessageItem] = []
669+
670+
for msg in messages:
671+
# basic metrics and status tracking
672+
with suppress(Exception):
673+
self.metrics.task_enqueued(user_id=msg.user_id, task_type=msg.label)
674+
675+
# ensure timestamp exists for monitoring
676+
if getattr(msg, "timestamp", None) is None:
677+
msg.timestamp = get_utc_now()
678+
649679
if self.status_tracker:
650-
self.status_tracker.task_submitted(
651-
task_id=message.item_id,
652-
user_id=message.user_id,
653-
task_type=message.label,
654-
mem_cube_id=message.mem_cube_id,
655-
business_task_id=message.task_id, # Pass business task_id if provided
680+
try:
681+
self.status_tracker.task_submitted(
682+
task_id=msg.item_id,
683+
user_id=msg.user_id,
684+
task_type=msg.label,
685+
mem_cube_id=msg.mem_cube_id,
686+
business_task_id=msg.task_id,
687+
)
688+
except Exception:
689+
logger.warning("status_tracker.task_submitted failed", exc_info=True)
690+
691+
# honor disabled handlers
692+
if self.disabled_handlers and msg.label in self.disabled_handlers:
693+
logger.info(f"Skipping disabled handler: {msg.label} - {msg.content}")
694+
continue
695+
696+
# decide priority path
697+
task_priority = self.orchestrator.get_task_priority(task_label=msg.label)
698+
if task_priority == TaskPriorityLevel.LEVEL_1:
699+
immediate_msgs.append(msg)
700+
else:
701+
queued_msgs.append(msg)
702+
703+
# Dispatch high-priority tasks immediately
704+
if immediate_msgs:
705+
# emit enqueue events for consistency
706+
for m in immediate_msgs:
707+
emit_monitor_event(
708+
"enqueue", m, {"enqueue_ts": to_iso(getattr(m, "timestamp", None))}
656709
)
657-
self.memos_message_queue.submit_messages(messages=messages)
710+
711+
# simulate dequeue for immediately dispatched messages so monitor logs stay complete
712+
for m in immediate_msgs:
713+
try:
714+
now = time.time()
715+
enqueue_ts_obj = getattr(m, "timestamp", None)
716+
enqueue_epoch = None
717+
if isinstance(enqueue_ts_obj, int | float):
718+
enqueue_epoch = float(enqueue_ts_obj)
719+
elif hasattr(enqueue_ts_obj, "timestamp"):
720+
dt = enqueue_ts_obj
721+
if dt.tzinfo is None:
722+
dt = dt.replace(tzinfo=timezone.utc)
723+
enqueue_epoch = dt.timestamp()
724+
725+
queue_wait_ms = None
726+
if enqueue_epoch is not None:
727+
queue_wait_ms = max(0.0, now - enqueue_epoch) * 1000
728+
729+
object.__setattr__(m, "_dequeue_ts", now)
730+
emit_monitor_event(
731+
"dequeue",
732+
m,
733+
{
734+
"enqueue_ts": to_iso(enqueue_ts_obj),
735+
"dequeue_ts": datetime.fromtimestamp(now, tz=timezone.utc).isoformat(),
736+
"queue_wait_ms": queue_wait_ms,
737+
},
738+
)
739+
self.metrics.task_dequeued(user_id=m.user_id, task_type=m.label)
740+
except Exception:
741+
logger.debug("Failed to emit dequeue for immediate task", exc_info=True)
742+
743+
user_cube_groups = group_messages_by_user_and_mem_cube(immediate_msgs)
744+
for user_id, cube_groups in user_cube_groups.items():
745+
for mem_cube_id, user_cube_msgs in cube_groups.items():
746+
label_groups: dict[str, list[ScheduleMessageItem]] = {}
747+
for m in user_cube_msgs:
748+
label_groups.setdefault(m.label, []).append(m)
749+
750+
for label, msgs_by_label in label_groups.items():
751+
handler = self.dispatcher.handlers.get(
752+
label, self.dispatcher._default_message_handler
753+
)
754+
self.dispatcher.execute_task(
755+
user_id=user_id,
756+
mem_cube_id=mem_cube_id,
757+
task_label=label,
758+
msgs=msgs_by_label,
759+
handler_call_back=handler,
760+
)
761+
762+
# Enqueue lower-priority tasks
763+
if queued_msgs:
764+
self.memos_message_queue.submit_messages(messages=queued_msgs)
658765

659766
def _submit_web_logs(
660767
self,
@@ -706,15 +813,6 @@ def get_web_log_messages(self) -> list[dict]:
706813
break
707814

708815
def _map_label(label: str) -> str:
709-
from memos.mem_scheduler.schemas.task_schemas import (
710-
ADD_TASK_LABEL,
711-
ANSWER_TASK_LABEL,
712-
MEM_ARCHIVE_TASK_LABEL,
713-
MEM_ORGANIZE_TASK_LABEL,
714-
MEM_UPDATE_TASK_LABEL,
715-
QUERY_TASK_LABEL,
716-
)
717-
718816
mapping = {
719817
QUERY_TASK_LABEL: "addMessage",
720818
ANSWER_TASK_LABEL: "addMessage",

0 commit comments

Comments
 (0)