# Conflicts: # apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts # apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts # apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts # apps/desktop/e2e/bot-mode-roster-localized.spec.ts # apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts # apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts # apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts # apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts # apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts # apps/desktop/e2e/bot-roster-user-sections.spec.ts # apps/desktop/e2e/bot-routines-pane-narrow.spec.ts # apps/desktop/e2e/bot-row-open-recent-session.spec.ts # apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts # apps/desktop/e2e/group-composer-auto-grow.spec.ts # apps/desktop/e2e/group-create-gate-remote-roster.spec.ts # apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts # apps/desktop/e2e/hosted-room-backend-continuity.spec.ts # apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts # apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts # apps/desktop/e2e/worktree-branch-status.spec.ts # apps/desktop/electron/backend-probes.test.ts # apps/desktop/electron/connection-apply.test.ts # apps/desktop/electron/desktop-electron-pin.test.ts # apps/desktop/electron/desktop-uninstall.test.ts # apps/desktop/electron/gateway-file-download-transport.test.ts # apps/desktop/electron/gateway-stop-before-update.test.ts # apps/desktop/electron/github-api-auth.test.ts # apps/desktop/electron/registry-primary-profile-scope.test.ts # apps/desktop/electron/update-api-check.test.ts # apps/desktop/electron/update-handoff-marker.test.ts # apps/desktop/electron/venv-blocker-scan.test.ts # apps/desktop/scripts/after-extract.test.mjs # apps/desktop/scripts/local-pack-publish.test.mjs # apps/desktop/scripts/tasks-scroll.test.mjs # apps/desktop/src/app/settings/model-settings.test.tsx # apps/desktop/src/app/updates-overlay.blockers.test.tsx # apps/desktop/src/components/desktop-install-overlay.test.tsx # apps/desktop/src/lib/update-copy.test.ts # scripts/ci/check_os_marker_fakes.py # tests-js/desktop-mac-usage-descriptions.test.ts # tests-js/node-engine-alignment.test.ts # tests/agent/lsp/test_install_and_lint_fixes.py # tests/agent/test_command_token_source.py # tests/agent/test_compression_boundary_hook.py # tests/agent/test_create_openai_client_ssl_verify.py # tests/agent/test_custom_provider_ca_probes.py # tests/agent/test_endpoint_blackhole.py # tests/agent/test_estimator_parity.py # tests/agent/test_in_place_compaction.py # tests/agent/test_moa_loop_mode.py # tests/agent/test_model_metadata.py # tests/agent/test_skill_session_platform_gate.py # tests/agent/test_skill_utils.py # tests/agent/test_ssl_ca_guard.py # tests/computer_use/test_doctor.py # tests/cron/test_codex_execution_paths.py # tests/cron/test_cron_bot_chat_delivery.py # tests/cron/test_cron_script.py # tests/cron/test_media_delivery_parity.py # tests/cron/test_misfire_catchup.py # tests/cron/test_parallel_pool.py # tests/cron/test_recurring_eagain_redispatch.py # tests/gateway/test_choice_picker.py # tests/gateway/test_control_socket_windows_live.py # tests/gateway/test_dingtalk.py # tests/gateway/test_feishu.py # tests/gateway/test_feishu_onboard.py # tests/gateway/test_gateway_shutdown.py # tests/gateway/test_matrix.py # tests/gateway/test_model_command_custom_providers.py # tests/gateway/test_reasoning_command.py # tests/gateway/test_runtime_footer.py # tests/gateway/test_session.py # tests/gateway/test_session_hygiene.py # tests/gateway/test_status.py # tests/gateway/test_teams.py # tests/gateway/test_turn_lease.py # tests/gateway/test_whatsapp_connect.py # tests/hermes_cli/test_approvals_command.py # tests/hermes_cli/test_auth_store_lock_concurrent.py # tests/hermes_cli/test_backup.py # tests/hermes_cli/test_banner_git_state.py # tests/hermes_cli/test_certifi_repair.py # tests/hermes_cli/test_cmd_update.py # tests/hermes_cli/test_compat_manifest_targets.py # tests/hermes_cli/test_computer_use_cli.py # tests/hermes_cli/test_cpr_local_leak.py # tests/hermes_cli/test_dashboard_auth_gate.py # tests/hermes_cli/test_dashboard_procs_kill_grace.py # tests/hermes_cli/test_desktop_lifecycle_windows_live.py # tests/hermes_cli/test_doctor.py # tests/hermes_cli/test_doctor_command_install.py # tests/hermes_cli/test_fleet_config_migration_windows_live.py # tests/hermes_cli/test_gateway.py # tests/hermes_cli/test_gateway_platform_gating.py # tests/hermes_cli/test_gateway_restart_loop.py # tests/hermes_cli/test_gateway_task_probe.py # tests/hermes_cli/test_gateway_wsl.py # tests/hermes_cli/test_gui_command.py # tests/hermes_cli/test_install_cua_driver.py # tests/hermes_cli/test_kanban_db.py # tests/hermes_cli/test_lazy_command_exports.py # tests/hermes_cli/test_lazy_refresh_venv_repair.py # tests/hermes_cli/test_linux_desktop_entry.py # tests/hermes_cli/test_local_runtime.py # tests/hermes_cli/test_local_runtime_updates.py # tests/hermes_cli/test_managed_uv.py # tests/hermes_cli/test_mcp_reload_confirm_gate.py # tests/hermes_cli/test_nous_subscription.py # tests/hermes_cli/test_npm_engine.py # tests/hermes_cli/test_personality_none.py # tests/hermes_cli/test_pet_toggle.py # tests/hermes_cli/test_plan_reconciliation_windows_live.py # tests/hermes_cli/test_plugin_event_bus.py # tests/hermes_cli/test_plugin_manifest_v2.py # tests/hermes_cli/test_plugin_packs.py # tests/hermes_cli/test_plugins_cmd.py # tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py # tests/hermes_cli/test_process_identity.py # tests/hermes_cli/test_profiles.py # tests/hermes_cli/test_profiles_sidebar_cache.py # tests/hermes_cli/test_pty_bridge.py # tests/hermes_cli/test_resolve_turn_limit.py # tests/hermes_cli/test_serve_runtime_inventory.py # tests/hermes_cli/test_session_vacuum_config.py # tests/hermes_cli/test_set_config_value.py # tests/hermes_cli/test_signal_handler_kanban_worker.py # tests/hermes_cli/test_slash_confirm_windows.py # tests/hermes_cli/test_stale_pid_guard.py # tests/hermes_cli/test_startup_fast_guards.py # tests/hermes_cli/test_status.py # tests/hermes_cli/test_telegram_managed_bot.py # tests/hermes_cli/test_tools_config.py # tests/hermes_cli/test_update_apply_shallow_count.py # tests/hermes_cli/test_update_autostash.py # tests/hermes_cli/test_update_concurrent_quarantine.py # tests/hermes_cli/test_update_fetch_failure_classifier.py # tests/hermes_cli/test_update_fleet_probe_resume_token.py # tests/hermes_cli/test_update_handoff_backend_reap.py # tests/hermes_cli/test_update_handoff_desktop_rebuild.py # tests/hermes_cli/test_update_head_moved_gate.py # tests/hermes_cli/test_update_host_obligation.py # tests/hermes_cli/test_update_import_guard.py # tests/hermes_cli/test_update_interrupted_recovery.py # tests/hermes_cli/test_update_inventory.py # tests/hermes_cli/test_update_launchd_unloaded_gateway.py # tests/hermes_cli/test_update_missing_configured_deps.py # tests/hermes_cli/test_update_modified_notice.py # tests/hermes_cli/test_update_multiplex_migration_hook.py # tests/hermes_cli/test_update_no_gateway_restart.py # tests/hermes_cli/test_update_orphan_backend_reap.py # tests/hermes_cli/test_update_parked_branch_guard.py # tests/hermes_cli/test_update_post_pull_syntax_guard.py # tests/hermes_cli/test_update_receipt.py # tests/hermes_cli/test_update_self_lock.py # tests/hermes_cli/test_update_shim_fail_closed.py # tests/hermes_cli/test_update_shim_self_lock.py # tests/hermes_cli/test_update_sqlite_remediation.py # tests/hermes_cli/test_update_stale_dashboard.py # tests/hermes_cli/test_update_stale_virtualenv.py # tests/hermes_cli/test_update_venv_health.py # tests/hermes_cli/test_update_venv_ownership_preflight.py # tests/hermes_cli/test_update_wedged_gateway.py # tests/hermes_cli/test_update_yes_flag.py # tests/hermes_cli/test_update_zip_two_phase.py # tests/hermes_cli/test_urllib_security.py # tests/hermes_cli/test_ux_messages_auth_config.py # tests/hermes_cli/test_ux_messages_startup.py # tests/hermes_cli/test_venv_holder_classifier.py # tests/hermes_cli/test_verify_console_scripts.py # tests/hermes_cli/test_verify_core_dependencies.py # tests/hermes_cli/test_web_server.py # tests/hermes_cli/test_web_server_console_ws.py # tests/hermes_cli/test_web_server_ws_ping.py # tests/hermes_cli/test_web_ui_build.py # tests/hermes_state/test_fts_rebuild_admission.py # tests/hermes_state/test_hermes_state.py # tests/plugins/memory/test_memory_lazy_install.py # tests/plugins/test_google_meet_plugin.py # tests/plugins/test_langfuse_plugin.py # tests/plugins/test_security_guidance_plugin.py # tests/plugins/test_transform_llm_output_hook.py # tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py # tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py # tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py # tests/scripts/install/test_install_clone_throttle_fallback.py # tests/scripts/install/test_install_lockfile_churn.py # tests/scripts/install/test_install_no_initial_commit.py # tests/scripts/install/test_install_sh_browser_install.py # tests/scripts/install/test_install_sh_node_prerelease.py # tests/scripts/install/test_install_sh_symlink_stomp.py # tests/scripts/install/test_install_sh_uv_lock_config.py # tests/scripts/install/test_install_unmerged_index.py # tests/scripts/test_contributor_map.py # tests/scripts/test_run_tests_parallel.py # tests/skills/test_competitor_news_monitor_skill.py # tests/skills/test_document_to_action_items_skill.py # tests/skills/test_google_workspace_setup.py # tests/skills/test_google_workspace_setup_deps.py # tests/skills/test_grounded_citations_skill.py # tests/skills/test_ip_as_logo_skill.py # tests/skills/test_live_dashboard_skill.py # tests/skills/test_mcp_oauth_remote_gateway_skill.py # tests/skills/test_office_document_skills.py # tests/skills/test_openclaw_migration.py # tests/skills/test_product_price_monitor_skill.py # tests/skills/test_scrollcraft_skill.py # tests/skills/test_setup_wizard_generator_skill.py # tests/skills/test_weekly_review_planning_skill.py # tests/test_engines_satisfiable.py # tests/test_fast_safe_load.py # tests/test_hermes_bootstrap.py # tests/test_hermes_constants.py # tests/test_hermes_logging.py # tests/test_managed_runtime_resolution.py # tests/test_model_tools_async_bridge.py # tests/test_packaging_build_guard.py # tests/test_packaging_metadata.py # tests/test_yaml_indent_consistency.py # tests/tools/test_approval_timeout_overflow.py # tests/tools/test_base_environment.py # tests/tools/test_bot_mode_dm.py # tests/tools/test_browser_chromium_check.py # tests/tools/test_browser_hardening.py # tests/tools/test_browser_homebrew_paths.py # tests/tools/test_browser_npx_warmup.py # tests/tools/test_browser_orphan_reaper.py # tests/tools/test_browser_real_profile.py # tests/tools/test_browser_use_cli.py # tests/tools/test_clipboard.py # tests/tools/test_code_execution.py # tests/tools/test_code_execution_modes.py # tests/tools/test_code_execution_windows_env.py # tests/tools/test_computer_use.py # tests/tools/test_delegate_liveness_timeout.py # tests/tools/test_execute_code_approval_cluster.py # tests/tools/test_execution_flag_detection.py # tests/tools/test_fal_common.py # tests/tools/test_file_operations.py # tests/tools/test_file_tools.py # tests/tools/test_file_tools_cwd_resolution.py # tests/tools/test_file_tools_live.py # tests/tools/test_lazy_deps.py # tests/tools/test_lazy_deps_durable_target.py # tests/tools/test_lazy_deps_managed.py # tests/tools/test_local_env_blocklist.py # tests/tools/test_local_tempdir.py # tests/tools/test_macos_protected_search.py # tests/tools/test_mcp_npx_cached_bin.py # tests/tools/test_oneshot_completion_linger.py # tests/tools/test_process_registry.py # tests/tools/test_read_file_schema_gating.py # tests/tools/test_skill_improvements.py # tests/tools/test_skills_sync.py # tests/tools/test_termux_api_detection.py # tests/tools/test_tirith_security.py # tests/tools/test_transcription_tools.py # tests/tools/test_tts_streaming.py # tests/tools/test_wake_word.py # tests/tui_gateway/test_compute_host_borrowed_lease.py # tests/tui_gateway/test_compute_host_turn_protocol.py # tests/tui_gateway/test_isolated_orphan_activity.py # tests/tui_gateway/test_protocol.py # tests/tui_gateway/test_slash_worker_profile_home.py # tests/tui_gateway/test_subprocess_encoding.py # tests/tui_gateway/test_tui_gateway_server.py # ui-tui/src/__tests__/terminalParity.test.ts # ui-tui/src/__tests__/termuxComposerLayout.test.ts # ui-tui/src/__tests__/textInputFastEcho.test.ts
493 lines
21 KiB
Python
493 lines
21 KiB
Python
"""Tests for Mem0 v3 API — new tool names, paginated responses, update/delete tools."""
|
||
|
||
import json
|
||
import threading
|
||
import pytest
|
||
|
||
from agent import secret_scope
|
||
import plugins.memory.mem0 as mem0_plugin
|
||
from plugins.memory.mem0 import Mem0MemoryProvider
|
||
|
||
|
||
class FakeBackend:
|
||
"""Fake Mem0Backend for provider-level tests."""
|
||
|
||
def __init__(self, search_results=None, all_results=None):
|
||
self._search_results = search_results or []
|
||
self._all_results = all_results or {"results": [], "count": 0}
|
||
self.captured = []
|
||
|
||
def search(self, query, *, filters, top_k=10, rerank=True):
|
||
self.captured.append(("search", query, {"filters": filters, "top_k": top_k, "rerank": rerank}))
|
||
return self._search_results
|
||
|
||
def get_all(self, *, filters, page=1, page_size=100):
|
||
self.captured.append(("get_all", {"filters": filters, "page": page, "page_size": page_size}))
|
||
return self._all_results
|
||
|
||
def add(self, messages, *, user_id, agent_id, infer=False, metadata=None):
|
||
self.captured.append((
|
||
"add",
|
||
messages,
|
||
{"user_id": user_id, "agent_id": agent_id, "infer": infer, "metadata": metadata},
|
||
))
|
||
return {"status": "PENDING", "event_id": "evt-test-123"}
|
||
|
||
def update(self, memory_id, text):
|
||
self.captured.append(("update", memory_id, text))
|
||
return {"result": "Memory updated.", "memory_id": memory_id}
|
||
|
||
def delete(self, memory_id):
|
||
self.captured.append(("delete", memory_id))
|
||
return {"result": "Memory deleted.", "memory_id": memory_id}
|
||
|
||
|
||
class TestMem0V3Tools:
|
||
"""Test v3 tool names and response handling."""
|
||
|
||
def _make_provider(self, monkeypatch, backend):
|
||
provider = Mem0MemoryProvider()
|
||
provider.initialize("test-session")
|
||
provider._user_id = "u123"
|
||
provider._agent_id = "hermes"
|
||
provider._backend = backend
|
||
return provider
|
||
|
||
|
||
|
||
def test_add_uses_content_param(self, monkeypatch):
|
||
backend = FakeBackend()
|
||
provider = self._make_provider(monkeypatch, backend)
|
||
result = json.loads(provider.handle_tool_call("mem0_add", {"content": "user likes dark mode"}))
|
||
assert len(backend.captured) == 1
|
||
call = backend.captured[0]
|
||
assert call[2]["infer"] is False
|
||
assert call[2]["user_id"] == "u123"
|
||
assert call[2]["agent_id"] == "hermes"
|
||
assert "event_id" in result
|
||
|
||
|
||
|
||
|
||
class TestMem0UpdateDelete:
|
||
|
||
def _make_provider(self, monkeypatch, backend):
|
||
provider = Mem0MemoryProvider()
|
||
provider.initialize("test-session")
|
||
provider._user_id = "u123"
|
||
provider._agent_id = "hermes"
|
||
provider._backend = backend
|
||
return provider
|
||
|
||
def test_update_calls_sdk(self, monkeypatch):
|
||
backend = FakeBackend()
|
||
provider = self._make_provider(monkeypatch, backend)
|
||
result = json.loads(provider.handle_tool_call(
|
||
"mem0_update", {"memory_id": "mem-1", "text": "updated fact"}
|
||
))
|
||
assert backend.captured[0][1] == "mem-1"
|
||
assert backend.captured[0][2] == "updated fact"
|
||
assert result["result"] == "Memory updated."
|
||
assert result["memory_id"] == "mem-1"
|
||
|
||
|
||
def test_delete_calls_sdk(self, monkeypatch):
|
||
backend = FakeBackend()
|
||
provider = self._make_provider(monkeypatch, backend)
|
||
result = json.loads(provider.handle_tool_call(
|
||
"mem0_delete", {"memory_id": "mem-1"}
|
||
))
|
||
assert backend.captured[0][1] == "mem-1"
|
||
assert result["result"] == "Memory deleted."
|
||
|
||
|
||
class TestMem0V3Internal:
|
||
|
||
def _make_provider(self, monkeypatch, backend):
|
||
provider = Mem0MemoryProvider()
|
||
provider.initialize("test-session")
|
||
provider._user_id = "u123"
|
||
provider._agent_id = "hermes"
|
||
provider._backend = backend
|
||
return provider
|
||
|
||
def test_sync_turn_explicit_kwargs(self, monkeypatch):
|
||
backend = FakeBackend()
|
||
provider = self._make_provider(monkeypatch, backend)
|
||
provider.sync_turn("user said", "assistant replied", session_id="s1")
|
||
provider._sync_thread.join(timeout=2)
|
||
assert len(backend.captured) == 1
|
||
call = backend.captured[0]
|
||
assert call[2]["user_id"] == "u123"
|
||
assert call[2]["agent_id"] == "hermes"
|
||
assert call[2]["infer"] is True
|
||
|
||
|
||
class TestSyncTurnTruncation:
|
||
"""sync_turn must cap messages before ingestion so small-context embedding
|
||
backends (OSS Ollama bge-small-zh-v1.5: 512 tokens; jina-embeddings-v3 token
|
||
limits) don't fail the whole extraction — a failure _try only logs."""
|
||
|
||
def _make_provider(self, monkeypatch, backend):
|
||
provider = Mem0MemoryProvider()
|
||
provider.initialize("test-session")
|
||
provider._user_id = "u123"
|
||
provider._agent_id = "hermes"
|
||
provider._backend = backend
|
||
return provider
|
||
|
||
def test_small_context_backend_never_sees_oversized_input(self, monkeypatch):
|
||
"""Regression for #106235/#37421: an OSS embedding backend with a small
|
||
context window raises on oversized input; truncation up front keeps the
|
||
extraction from being silently dropped (no breaker failures)."""
|
||
|
||
class SmallContextBackend(FakeBackend):
|
||
def add(self, messages, **kwargs):
|
||
if any(len(m["content"]) > mem0_plugin._SYNC_MSG_MAX_CHARS for m in messages):
|
||
raise RuntimeError("HTTP 500: embedding input exceeds model context")
|
||
return super().add(messages, **kwargs)
|
||
|
||
backend = SmallContextBackend()
|
||
provider = self._make_provider(monkeypatch, backend)
|
||
provider.sync_turn("Short question?", "".join(f"Fact {i}. " for i in range(200)), session_id="s1")
|
||
provider._sync_thread.join(timeout=2)
|
||
assert len(backend.captured) == 1
|
||
sent = backend.captured[0][1]
|
||
assert sent[0]["content"] == "Short question?" # under the cap: untouched
|
||
assert len(sent[1]["content"]) <= mem0_plugin._SYNC_MSG_MAX_CHARS and sent[1]["content"].endswith(".")
|
||
assert provider._consecutive_failures == 0
|
||
|
||
def test_the_boundary_kept_is_the_last_one_in_the_window_whatever_its_script(self):
|
||
"""A mixed-script turn must not be cut back to an early CJK stop.
|
||
|
||
The trim exists to keep as much of the turn as the embedder can take; picking the
|
||
first separator KIND that qualifies instead of the last boundary threw away most of
|
||
the allowed window whenever two kinds appeared — an early ``。`` (or ``.``, which
|
||
outranks ``!``/``?``) beat a boundary 240 characters later, so the facts stated in
|
||
the rest of the message never reached extraction.
|
||
"""
|
||
cap = mem0_plugin._SYNC_MSG_MAX_CHARS
|
||
early, late = cap // 2, cap - 9
|
||
|
||
for early_sep, late_sep in (("。", "."), (".", "!"), ("?", "?"), ("!", ".")):
|
||
text = "a" * early + early_sep + "b" * (late - early - 1) + late_sep + "c" * cap
|
||
assert text[late] == late_sep and len(text) > cap # both boundaries inside the window
|
||
kept = mem0_plugin._truncate_for_sync(text)
|
||
assert kept == text[:late + 1], f"{early_sep!r} before {late_sep!r} cut back to {len(kept)} chars"
|
||
assert kept.endswith(late_sep)
|
||
|
||
def test_a_boundary_only_in_the_first_third_still_falls_back_to_a_hard_cut(self):
|
||
"""Unsegmented input keeps the whole window rather than a sliver of a sentence."""
|
||
cap = mem0_plugin._SYNC_MSG_MAX_CHARS
|
||
text = "a" * 10 + "." + "b" * (cap * 2)
|
||
assert mem0_plugin._truncate_for_sync(text) == text[:cap]
|
||
|
||
def test_sync_max_chars_config_raises_cap(self, monkeypatch, tmp_path):
|
||
"""8k-token embedders should not be stuck at the 512-token default (#106235)."""
|
||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||
monkeypatch.setenv("MEM0_API_KEY", "test-key")
|
||
(tmp_path / "mem0.json").write_text('{"sync_max_chars": 3000}')
|
||
backend = FakeBackend()
|
||
provider = self._make_provider(monkeypatch, backend)
|
||
provider.sync_turn("hi", "Long answer. " * 200, session_id="s1") # 2600 chars
|
||
provider._sync_thread.join(timeout=2)
|
||
assert backend.captured[0][1][1]["content"] == "Long answer. " * 200
|
||
|
||
|
||
class TestMem0Prefetch:
|
||
"""prefetch() must recall on the CURRENT question, synchronously.
|
||
|
||
The old implementation ignored its ``query`` and returned whatever a
|
||
background ``queue_prefetch`` had warmed from the PREVIOUS turn — so the
|
||
first turn injected nothing and later turns injected stale, off-topic
|
||
memories. These lock the corrected behaviour.
|
||
"""
|
||
|
||
def _make_provider(self, backend):
|
||
provider = Mem0MemoryProvider()
|
||
provider.initialize("test-session")
|
||
provider._user_id = "u123"
|
||
provider._agent_id = "hermes"
|
||
provider._backend = backend
|
||
return provider
|
||
|
||
def test_prefetch_searches_current_query(self):
|
||
backend = FakeBackend(search_results=[{"id": "m1", "memory": "user prefers dark mode"}])
|
||
provider = self._make_provider(backend)
|
||
result = provider.prefetch("what theme do I like?")
|
||
kind, query, opts = backend.captured[0]
|
||
assert kind == "search"
|
||
assert query == "what theme do I like?"
|
||
assert opts["filters"] == {"user_id": "u123"}
|
||
assert opts["top_k"] == 10
|
||
assert opts["rerank"] is False
|
||
assert "## Mem0 Memory" in result
|
||
assert "user prefers dark mode" in result
|
||
|
||
|
||
def test_on_turn_start_queues_current_query(self):
|
||
backend = FakeBackend(search_results=[{"id": "m1", "memory": "lives in Berlin"}])
|
||
provider = self._make_provider(backend)
|
||
provider.on_turn_start(1, "where do I live?")
|
||
provider._prefetch_thread.join(timeout=1)
|
||
result = provider.prefetch("where do I live?")
|
||
assert "lives in Berlin" in result
|
||
assert len([c for c in backend.captured if c[0] == "search"]) == 1
|
||
|
||
def test_slow_prefetch_returns_quickly(self, monkeypatch):
|
||
entered = threading.Event()
|
||
release = threading.Event()
|
||
search_returned = threading.Event()
|
||
|
||
class SlowBackend(FakeBackend):
|
||
def search(self, query, *, filters, top_k=10, rerank=True):
|
||
entered.set()
|
||
try:
|
||
release.wait(30)
|
||
return super().search(
|
||
query, filters=filters, top_k=top_k, rerank=rerank
|
||
)
|
||
finally:
|
||
search_returned.set()
|
||
|
||
monkeypatch.setattr(mem0_plugin, "_PREFETCH_WAIT_SECS", 0.01)
|
||
provider = self._make_provider(
|
||
SlowBackend(search_results=[{"id": "m1", "memory": "lives in Berlin"}])
|
||
)
|
||
# DETERMINISTIC non-blocking witness — replaces `assert elapsed < 0.1`.
|
||
#
|
||
# The old form slept 0.2s in the backend and asserted prefetch returned
|
||
# in under 0.1s. That makes the OS scheduler part of the assertion: on
|
||
# a loaded box thread startup alone can eat the 100ms budget, so the
|
||
# inequality flips with nothing wrong in the code under test. Observed
|
||
# failing in a full-directory run of tests/plugins/memory.
|
||
#
|
||
# The real contract is that prefetch gives up on the slow backend
|
||
# instead of waiting for it. Assert it directly: the backend search is
|
||
# STILL PARKED (release unset, so `search_returned` cannot be set). If
|
||
# prefetch ever waited for the backend, the search would have returned
|
||
# first and this fails. No wall-clock constant.
|
||
assert provider.prefetch("where do I live?") == ""
|
||
assert entered.wait(30), "prefetch never reached the backend"
|
||
assert not search_returned.is_set(), (
|
||
"prefetch blocked on the slow backend: the backend search had "
|
||
"already returned by the time prefetch did"
|
||
)
|
||
|
||
release.set()
|
||
provider._prefetch_thread.join(timeout=30)
|
||
assert "lives in Berlin" in provider.prefetch("where do I live?")
|
||
|
||
|
||
def test_queue_prefetch_fires_no_search(self):
|
||
# prefetch is synchronous now, so the post-turn warm is redundant and
|
||
# must not fire a wasted backend search.
|
||
backend = FakeBackend(search_results=[{"id": "m1", "memory": "x"}])
|
||
provider = self._make_provider(backend)
|
||
provider.queue_prefetch("previous turn text")
|
||
assert backend.captured == []
|
||
|
||
|
||
|
||
|
||
class TestMem0ModeSwitch:
|
||
|
||
def test_oss_mode_initializes_without_platform_key_in_scope(
|
||
self, monkeypatch, tmp_path
|
||
):
|
||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||
monkeypatch.delenv("MEM0_API_KEY", raising=False)
|
||
(tmp_path / "mem0.json").write_text(
|
||
json.dumps(
|
||
{
|
||
"mode": "oss",
|
||
"oss": {"vector_store": {"provider": "qdrant"}},
|
||
}
|
||
)
|
||
)
|
||
|
||
# Contract (#99121, restated for fail-loud reads): every production caller is scoped
|
||
# (turn/cron/kanban scope installers); an OSS profile whose scope simply lacks MEM0_API_KEY
|
||
# must initialize. A scope-LESS multiplex caller is a spawn-site bug and raises instead —
|
||
# see test_load_config_fails_closed_without_scope_even_for_identity_settings.
|
||
token = secret_scope.set_secret_scope({})
|
||
secret_scope.set_multiplex_active(True)
|
||
try:
|
||
provider = Mem0MemoryProvider()
|
||
provider._create_backend = lambda: None # type: ignore[method-assign]
|
||
provider.initialize("test")
|
||
available = provider.is_available()
|
||
finally:
|
||
secret_scope.set_multiplex_active(False)
|
||
secret_scope.reset_secret_scope(token)
|
||
|
||
assert provider._mode == "oss"
|
||
assert provider._api_key == ""
|
||
assert available is True
|
||
|
||
def test_platform_config_still_fails_closed_without_profile_scope(
|
||
self, monkeypatch, tmp_path
|
||
):
|
||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||
monkeypatch.delenv("MEM0_API_KEY", raising=False)
|
||
|
||
token = secret_scope.set_secret_scope(None)
|
||
secret_scope.set_multiplex_active(True)
|
||
try:
|
||
with pytest.raises(secret_scope.UnscopedSecretError):
|
||
Mem0MemoryProvider().is_available()
|
||
finally:
|
||
secret_scope.set_multiplex_active(False)
|
||
secret_scope.reset_secret_scope(token)
|
||
|
||
def test_load_config_fails_closed_without_scope_even_for_identity_settings(
|
||
self, monkeypatch, tmp_path
|
||
):
|
||
"""A scope-less multiplex caller is a spawn-site bug: identity/mode reads must surface it,
|
||
not degrade to '' and route the turn's memories into the default profile's account."""
|
||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||
(tmp_path / "mem0.json").write_text(json.dumps({"mode": "oss", "oss": {"vector_store": {"provider": "qdrant"}}}))
|
||
|
||
token = secret_scope.set_secret_scope(None)
|
||
secret_scope.set_multiplex_active(True)
|
||
try:
|
||
with pytest.raises(secret_scope.UnscopedSecretError):
|
||
mem0_plugin._load_config()
|
||
finally:
|
||
secret_scope.set_multiplex_active(False)
|
||
secret_scope.reset_secret_scope(token)
|
||
|
||
def test_file_api_key_still_overrides_environment(self, monkeypatch, tmp_path):
|
||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||
monkeypatch.setenv("MEM0_API_KEY", "env-key")
|
||
(tmp_path / "mem0.json").write_text(
|
||
json.dumps({"api_key": "file-key"})
|
||
)
|
||
|
||
assert mem0_plugin._load_config()["api_key"] == "file-key"
|
||
|
||
|
||
def test_missing_mode_key_defaults_platform(self, monkeypatch, tmp_path):
|
||
"""Backward compat: old mem0.json without mode key works."""
|
||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||
config_path = tmp_path / "mem0.json"
|
||
config_path.write_text('{"user_id": "old-user"}')
|
||
monkeypatch.setenv("MEM0_API_KEY", "test-key")
|
||
provider = Mem0MemoryProvider()
|
||
provider.initialize("test")
|
||
assert provider._mode == "platform"
|
||
assert provider._user_id == "old-user"
|
||
|
||
def test_is_available_platform_needs_key(self, monkeypatch, tmp_path):
|
||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||
monkeypatch.delenv("MEM0_API_KEY", raising=False)
|
||
provider = Mem0MemoryProvider()
|
||
assert provider.is_available() is False
|
||
|
||
|
||
class TestMem0UserIdResolution:
|
||
"""user_id resolution: configured override > gateway-native id > placeholder.
|
||
|
||
Same human across CLI / Telegram / Discord / Slack / etc. should map to
|
||
the same memory store when MEM0_USER_ID is set, and only fall back to the
|
||
gateway-native id when it isn't.
|
||
"""
|
||
|
||
def _provider(self, monkeypatch, tmp_path):
|
||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||
monkeypatch.setenv("MEM0_API_KEY", "test-key")
|
||
provider = Mem0MemoryProvider()
|
||
# Skip backend instantiation — we only care about identity resolution.
|
||
provider._create_backend = lambda: None # type: ignore[method-assign]
|
||
return provider
|
||
|
||
def test_env_override_beats_gateway_native_id(self, monkeypatch, tmp_path):
|
||
monkeypatch.setenv("MEM0_USER_ID", "ryan@example.com")
|
||
provider = self._provider(monkeypatch, tmp_path)
|
||
provider.initialize("test", user_id="123456789", platform="telegram")
|
||
assert provider._user_id == "ryan@example.com"
|
||
|
||
def test_file_override_beats_gateway_native_id(self, monkeypatch, tmp_path):
|
||
monkeypatch.delenv("MEM0_USER_ID", raising=False)
|
||
(tmp_path / "mem0.json").write_text('{"user_id": "ryan@example.com"}')
|
||
provider = self._provider(monkeypatch, tmp_path)
|
||
provider.initialize("test", user_id="123456789", platform="telegram")
|
||
assert provider._user_id == "ryan@example.com"
|
||
|
||
def test_unset_falls_back_to_gateway_native_id(self, monkeypatch, tmp_path):
|
||
monkeypatch.delenv("MEM0_USER_ID", raising=False)
|
||
provider = self._provider(monkeypatch, tmp_path)
|
||
provider.initialize("test", user_id="123456789", platform="telegram")
|
||
assert provider._user_id == "123456789"
|
||
|
||
|
||
def test_legacy_placeholder_in_config_does_not_override_kwargs(self, monkeypatch, tmp_path):
|
||
# Setup wizard historically wrote {"user_id": "hermes-user"} as the
|
||
# suggested default. Treat that placeholder as unset so users on
|
||
# gateways still get gateway-native ids — not silent collisions.
|
||
monkeypatch.delenv("MEM0_USER_ID", raising=False)
|
||
(tmp_path / "mem0.json").write_text('{"user_id": "hermes-user"}')
|
||
provider = self._provider(monkeypatch, tmp_path)
|
||
provider.initialize("test", user_id="123456789", platform="telegram")
|
||
assert provider._user_id == "123456789"
|
||
|
||
|
||
class _SentinelBackend:
|
||
def __init__(self, *args):
|
||
self.args = args
|
||
|
||
|
||
class TestCreateBackendRouting:
|
||
"""_create_backend() must pick the backend matching the configured mode/host."""
|
||
|
||
def _provider(self, monkeypatch, *, mode="platform", api_key="k", host=""):
|
||
# Neutralize lazy-install so the routing decision is all we exercise.
|
||
monkeypatch.setattr("pm.ensure_import", lambda *a, **k: None, raising=False)
|
||
provider = Mem0MemoryProvider()
|
||
provider._mode = mode
|
||
provider._api_key = api_key
|
||
provider._host = host
|
||
provider._config = {"oss": {"vector_store": {"provider": "qdrant"}}}
|
||
return provider
|
||
|
||
def test_routes_to_selfhosted_when_host_set(self, monkeypatch):
|
||
captured = {}
|
||
|
||
class SH(_SentinelBackend):
|
||
def __init__(self, api_key, host):
|
||
captured["args"] = (api_key, host)
|
||
|
||
monkeypatch.setattr("plugins.memory.mem0._backend.SelfHostedBackend", SH)
|
||
provider = self._provider(monkeypatch, host="http://sh:8888", api_key="adminkey")
|
||
backend = provider._create_backend()
|
||
assert isinstance(backend, SH)
|
||
assert captured["args"] == ("adminkey", "http://sh:8888")
|
||
|
||
|
||
def test_oss_mode_takes_precedence_over_host(self, monkeypatch):
|
||
class OB(_SentinelBackend):
|
||
def __init__(self, cfg):
|
||
pass
|
||
|
||
monkeypatch.setattr("plugins.memory.mem0._backend.OSSBackend", OB)
|
||
provider = self._provider(monkeypatch, mode="oss", host="http://sh:8888")
|
||
assert isinstance(provider._create_backend(), OB)
|
||
|
||
def test_prompt_label_matches_routing_when_oss_and_host_both_set(self, monkeypatch):
|
||
# system_prompt_block must mirror _create_backend precedence: with both
|
||
# mode=oss and host set, OSS wins the routing, so the prompt must label
|
||
# OSS — not "self-hosted (HTTP API)". Guards the prompt-vs-routing lie.
|
||
provider = self._provider(monkeypatch, mode="oss", host="http://sh:8888")
|
||
provider._user_id = "test"
|
||
block = provider.system_prompt_block()
|
||
assert "OSS" in block
|
||
assert "HTTP API" not in block
|
||
|
||
|
||
class TestSelfHostedConfig:
|
||
"""Config plumbing for self-hosted (MEM0_HOST env + is_available)."""
|
||
|
||
def test_load_config_reads_mem0_host_env(self, monkeypatch):
|
||
monkeypatch.setenv("MEM0_HOST", "http://localhost:8888")
|
||
assert mem0_plugin._load_config()["host"] == "http://localhost:8888"
|