diff --git a/backend/packages/harness/deerflow/agents/memory/backends/README.md b/backend/packages/harness/deerflow/agents/memory/backends/README.md index 4d7b210488..78448e2f06 100644 --- a/backend/packages/harness/deerflow/agents/memory/backends/README.md +++ b/backend/packages/harness/deerflow/agents/memory/backends/README.md @@ -5,7 +5,10 @@ Each subfolder under `agents/memory/backends/` is a pluggable memory backend. Sw - `deermem/` - the default backend (deer-flow's own: structured facts + JSON storage). - `noop/` - an empty backend and the **template** to copy when adding a new one. - `openviking/` - optional remote backend using the official - `langchain-openviking` package (single-user middleware mode). + `langchain-openviking` package (`memory.mode: middleware` only; supports + single-user `owner_user_id` + `api_key_env` and fail-closed multi-user / + multi-tenant isolation via `user_credentials` or `credential_provider` with + optional `tenant_id` and `client_pool`). - `honcho/` - optional remote Honcho backend over HTTP: user-model memory (representations built by Honcho's server-side deriver; no local LLM calls). Workspace-per-user isolation with per-user overrides. This guide tells you **which files to touch** when you change, swap, or add a memory system. Paths are relative to `backend/` unless noted. diff --git a/backend/packages/harness/deerflow/agents/memory/backends/openviking/__init__.py b/backend/packages/harness/deerflow/agents/memory/backends/openviking/__init__.py index 26a3c8040b..b944e480da 100644 --- a/backend/packages/harness/deerflow/agents/memory/backends/openviking/__init__.py +++ b/backend/packages/harness/deerflow/agents/memory/backends/openviking/__init__.py @@ -1,7 +1,13 @@ """OpenViking memory backend using the official LangChain integration.""" +from .credentials import OpenVikingCredential, OpenVikingCredentialProvider from .openviking_manager import OpenVikingMemoryManager MANAGER_CLASS = OpenVikingMemoryManager -__all__ = ["OpenVikingMemoryManager"] +__all__ = [ + "MANAGER_CLASS", + "OpenVikingCredential", + "OpenVikingCredentialProvider", + "OpenVikingMemoryManager", +] diff --git a/backend/packages/harness/deerflow/agents/memory/backends/openviking/config.py b/backend/packages/harness/deerflow/agents/memory/backends/openviking/config.py index 5a4364269f..d906f3bc8c 100644 --- a/backend/packages/harness/deerflow/agents/memory/backends/openviking/config.py +++ b/backend/packages/harness/deerflow/agents/memory/backends/openviking/config.py @@ -4,14 +4,27 @@ from __future__ import annotations import os import re -from collections.abc import Callable +from collections.abc import Callable, Mapping from dataclasses import dataclass, field from math import isfinite +from types import MappingProxyType from typing import Any, Literal from urllib.parse import urlparse +from .credentials import ( + OpenVikingCredential, + has_control_chars, + validate_api_key, + validate_provider_path, + validate_user_key, +) + _SAFE_PEER_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$") GENERATED_PEER_PREFIX = "df-agent-" +_DEFAULT_POOL_MAX_CLIENTS = 64 +_MAX_POOL_CLIENTS = 4096 +_DEFAULT_POOL_IDLE_TTL_SECONDS = 900.0 +_ALLOWED_USER_CREDENTIAL_KEYS = frozenset({"api_key", "api_key_env", "tenant_id"}) _REMOVED_CUSTOM_HTTP_FIELDS = frozenset( { "connect_timeout_seconds", @@ -31,9 +44,15 @@ class OpenVikingConfig: base_url: str storage_path: str - owner_user_id: str + owner_user_id: str | None api_key: str = field(repr=False) - api_key_env: str + api_key_env: str | None + isolation_mode: Literal["single_user", "multi_user"] + user_credentials: Mapping[str, OpenVikingCredential] = field(repr=False) + credential_provider: str | None + credential_provider_config: Mapping[str, Any] = field(repr=False) + pool_max_clients: int + pool_idle_ttl_seconds: float | None default_peer_id: str timeout_seconds: float search_top_k: int @@ -51,60 +70,132 @@ class OpenVikingConfig: def from_backend_config( cls, backend_config: dict[str, Any] | None, + *, + has_injected_credential_provider: bool = False, ) -> OpenVikingConfig: + """Parse and validate ``backend_config`` without imports or network I/O.""" + cfg = dict(backend_config or {}) if "auth_mode" in cfg or "account" in cfg: - raise ValueError("OpenViking trusted mode is no longer supported by this backend; use a USER API key and configure owner_user_id") + raise ValueError("OpenViking trusted mode is no longer supported by this backend; use a USER API key and configure owner_user_id, user_credentials, or credential_provider") removed_fields = sorted(_REMOVED_CUSTOM_HTTP_FIELDS.intersection(cfg)) if removed_fields: raise ValueError("OpenViking custom HTTP client fields are no longer supported: " + ", ".join(removed_fields)) retrieval = _mapping(cfg.pop("retrieval", {}), "retrieval") - failure_policy = _mapping( - cfg.pop("failure_policy", {}), - "failure_policy", - ) - api_key_env = str(cfg.pop("api_key_env", "OPENVIKING_API_KEY")).strip() - if not api_key_env: - raise ValueError("OpenViking api_key_env must not be empty") + failure_policy = _mapping(cfg.pop("failure_policy", {}), "failure_policy") + client_pool = _mapping(cfg.pop("client_pool", {}), "client_pool") - result = cls( - base_url=str(cfg.pop("base_url", "http://127.0.0.1:1933")).rstrip("/"), - storage_path=str(cfg.pop("storage_path", "")), - owner_user_id=str(cfg.pop("owner_user_id", "")).strip(), - api_key=os.environ.get(api_key_env, "").strip(), - api_key_env=api_key_env, - default_peer_id=str(cfg.pop("default_peer_id", "deerflow")).strip(), - timeout_seconds=_number(cfg, "timeout_seconds", 30.0, float), - search_top_k=_number(retrieval, "top_k", 8, int), - score_threshold=_optional_float(retrieval.pop("score_threshold", None), "score_threshold"), - max_injection_chars=_number(retrieval, "max_injection_chars", 12_000, int), - content_mode=str(retrieval.pop("content_mode", "overview")).lower(), # type: ignore[arg-type] - injection_query=str( - retrieval.pop( - "injection_query", - "user profile preferences important entities events ongoing goals constraints and prior decisions", - ) - ).strip(), - startup_policy=str(cfg.pop("startup_policy", "fail_fast")).lower(), # type: ignore[arg-type] - read_failure_policy=str(failure_policy.pop("read", "fail_open")).lower(), # type: ignore[arg-type] - write_failure_policy=str(failure_policy.pop("write", "log_and_drop")).lower(), # type: ignore[arg-type] - allow_insecure_http=_boolean( - cfg.pop("allow_insecure_http", False), - "allow_insecure_http", - ), - max_seen_message_ids=_number(cfg, "max_seen_message_ids", 512, int), - ) + credential_provider = _parse_credential_provider(cfg.pop("credential_provider", None)) + provider_config = _mapping(cfg.pop("credential_provider_config", {}), "credential_provider_config") + + has_explicit_owner_user_id = "owner_user_id" in cfg + has_explicit_api_key_env = "api_key_env" in cfg + raw_owner_user_id = cfg.pop("owner_user_id", None) + raw_api_key_env = cfg.pop("api_key_env", None) + raw_user_credentials = cfg.pop("user_credentials", None) + + is_multi_user = raw_user_credentials is not None or credential_provider is not None or has_injected_credential_provider + + if provider_config and credential_provider is None: + raise ValueError("OpenViking credential_provider_config requires credential_provider in backend_config") + if client_pool and not is_multi_user: + raise ValueError("OpenViking client_pool is only supported in multi-user mode with user_credentials or credential_provider") + + user_credential_unknowns: list[str] = [] + if is_multi_user: + if has_explicit_owner_user_id or has_explicit_api_key_env: + raise ValueError("OpenViking owner_user_id and api_key_env cannot be used in multi-user mode with user_credentials or credential_provider") + if raw_user_credentials is not None: + user_credential_unknowns = _validate_user_credentials_structure(raw_user_credentials) + isolation_mode: Literal["single_user", "multi_user"] = "multi_user" + owner_user_id: str | None = None + api_key_env: str | None = None + api_key = "" + else: + isolation_mode = "single_user" + if raw_owner_user_id is None: + owner_user_id = "" + elif not isinstance(raw_owner_user_id, str) or has_control_chars(raw_owner_user_id): + raise ValueError("OpenViking owner_user_id must be a string without control characters") + else: + owner_user_id = raw_owner_user_id.strip() + if raw_api_key_env is None: + api_key_env = "OPENVIKING_API_KEY" + elif not isinstance(raw_api_key_env, str) or has_control_chars(raw_api_key_env): + raise ValueError("OpenViking api_key_env must be a string without control characters") + else: + api_key_env = raw_api_key_env.strip() + if not api_key_env: + raise ValueError("OpenViking api_key_env must not be empty") + api_key = os.environ.get(api_key_env, "").strip() + + pool_max_clients = _pool_int(client_pool, "max_clients", _DEFAULT_POOL_MAX_CLIENTS) + pool_idle_ttl_seconds = _pool_idle_ttl(client_pool) + + base_url = str(cfg.pop("base_url", "http://127.0.0.1:1933")).rstrip("/") + storage_path = str(cfg.pop("storage_path", "")) + default_peer_id = str(cfg.pop("default_peer_id", "deerflow")).strip() + timeout_seconds = _number(cfg, "timeout_seconds", 30.0, float) + search_top_k = _number(retrieval, "top_k", 8, int) + score_threshold = _optional_float(retrieval.pop("score_threshold", None), "score_threshold") + max_injection_chars = _number(retrieval, "max_injection_chars", 12_000, int) + content_mode = str(retrieval.pop("content_mode", "overview")).lower() + injection_query = str( + retrieval.pop( + "injection_query", + "user profile preferences important entities events ongoing goals constraints and prior decisions", + ) + ).strip() + startup_policy = str(cfg.pop("startup_policy", "fail_fast")).lower() + read_failure_policy = str(failure_policy.pop("read", "fail_open")).lower() + write_failure_policy = str(failure_policy.pop("write", "log_and_drop")).lower() + allow_insecure_http = _boolean(cfg.pop("allow_insecure_http", False), "allow_insecure_http") + max_seen_message_ids = _number(cfg, "max_seen_message_ids", 512, int) unknown = sorted( [ *cfg, *(f"retrieval.{key}" for key in retrieval), *(f"failure_policy.{key}" for key in failure_policy), + *(f"client_pool.{key}" for key in client_pool), + *user_credential_unknowns, ] ) if unknown: raise ValueError("Unknown OpenViking backend_config fields: " + ", ".join(unknown)) + + parsed_user_credentials: dict[str, OpenVikingCredential] = {} + if is_multi_user and raw_user_credentials is not None: + if not raw_user_credentials and credential_provider is None and not has_injected_credential_provider: + raise ValueError("OpenViking user_credentials must not be empty when no credential_provider is configured") + parsed_user_credentials = _resolve_user_credentials(raw_user_credentials) + + result = cls( + base_url=base_url, + storage_path=storage_path, + owner_user_id=owner_user_id, + api_key=api_key, + api_key_env=api_key_env, + isolation_mode=isolation_mode, + user_credentials=MappingProxyType(parsed_user_credentials), + credential_provider=credential_provider, + credential_provider_config=MappingProxyType(provider_config), + pool_max_clients=pool_max_clients, + pool_idle_ttl_seconds=pool_idle_ttl_seconds, + default_peer_id=default_peer_id, + timeout_seconds=timeout_seconds, + search_top_k=search_top_k, + score_threshold=score_threshold, + max_injection_chars=max_injection_chars, + content_mode=content_mode, # type: ignore[arg-type] + injection_query=injection_query, + startup_policy=startup_policy, # type: ignore[arg-type] + read_failure_policy=read_failure_policy, # type: ignore[arg-type] + write_failure_policy=write_failure_policy, # type: ignore[arg-type] + allow_insecure_http=allow_insecure_http, + max_seen_message_ids=max_seen_message_ids, + ) result._validate() return result @@ -112,12 +203,20 @@ class OpenVikingConfig: parsed = urlparse(self.base_url) if parsed.scheme not in {"http", "https"} or not parsed.netloc: raise ValueError("OpenViking base_url must be an absolute http(s) URL") + if parsed.username is not None or parsed.password is not None: + raise ValueError("OpenViking base_url must not embed credentials; configure api_key_env, user_credentials, or credential_provider instead") if parsed.scheme == "http" and not self.allow_insecure_http and parsed.hostname not in {"127.0.0.1", "localhost", "openviking"}: raise ValueError("OpenViking plain HTTP is allowed only for localhost/openviking; set allow_insecure_http=true only for a trusted internal network") - if not self.owner_user_id: - raise ValueError("OpenViking owner_user_id must not be empty") - if not self.api_key: - raise ValueError(f"OpenViking USER API key is missing; set {self.api_key_env}") + if self.isolation_mode == "single_user": + if not self.owner_user_id: + raise ValueError("OpenViking owner_user_id must not be empty") + if not self.api_key: + raise ValueError(f"OpenViking USER API key is missing; set {self.api_key_env}") + validate_api_key(self.api_key) + if not 1 <= self.pool_max_clients <= _MAX_POOL_CLIENTS: + raise ValueError(f"OpenViking client_pool.max_clients must be between 1 and {_MAX_POOL_CLIENTS}") + if self.pool_idle_ttl_seconds is not None and (not isfinite(self.pool_idle_ttl_seconds) or self.pool_idle_ttl_seconds <= 0): + raise ValueError("OpenViking client_pool.idle_ttl_seconds must be a finite value > 0 or null") if not is_safe_peer_id(self.default_peer_id): raise ValueError("OpenViking default_peer_id must start with a lowercase letter or digit and contain at most 64 lowercase letters, digits, '_' or '-'") if self.default_peer_id.startswith(GENERATED_PEER_PREFIX): @@ -150,6 +249,72 @@ def is_safe_peer_id(value: str) -> bool: return _SAFE_PEER_RE.fullmatch(value) is not None +def _parse_credential_provider(value: Any) -> str | None: + if value is None: + return None + if not isinstance(value, str): + raise ValueError("OpenViking credential_provider must be a non-empty string") + if not value.strip(): + raise ValueError("OpenViking credential_provider must not be empty") + validate_provider_path(value) + return value + + +def _validate_user_credentials_structure(raw_user_credentials: Any) -> list[str]: + if not isinstance(raw_user_credentials, dict): + raise ValueError("OpenViking user_credentials must be a mapping") + unknown: list[str] = [] + for raw_uid, raw_spec in raw_user_credentials.items(): + uid = validate_user_key(raw_uid) + if not isinstance(raw_spec, dict): + raise ValueError(f"OpenViking user_credentials.{uid} must be a mapping") + for key in raw_spec: + if not isinstance(key, str): + raise ValueError(f"OpenViking user_credentials.{uid} keys must be strings, got {type(key).__name__}") + if key not in _ALLOWED_USER_CREDENTIAL_KEYS: + unknown.append(f"user_credentials.{uid}.{key}") + return unknown + + +def _resolve_user_credentials(raw_user_credentials: dict[str, dict[str, Any]]) -> dict[str, OpenVikingCredential]: + resolved: dict[str, OpenVikingCredential] = {} + seen_fingerprints: dict[str, str] = {} + for uid, spec in raw_user_credentials.items(): + has_inline = spec.get("api_key") is not None + has_env = spec.get("api_key_env") is not None + if has_inline == has_env: + raise ValueError(f"OpenViking user_credentials.{uid} must specify exactly one of 'api_key' or 'api_key_env'") + + raw_tenant = spec.get("tenant_id") + env_name: str | None = None + if has_env: + raw_env = spec["api_key_env"] + if not isinstance(raw_env, str) or not raw_env.strip() or has_control_chars(raw_env): + raise ValueError(f"OpenViking user_credentials.{uid}.api_key_env must be a non-empty string without control characters") + env_name = raw_env.strip() + api_key_value = os.environ.get(env_name, "").strip() + if not api_key_value: + raise ValueError(f"OpenViking USER API key is missing for user {uid!r}; set {env_name}") + else: + api_key_value = spec["api_key"] + + try: + cred = OpenVikingCredential( + api_key=api_key_value, + tenant_id=raw_tenant, + api_key_env=env_name, + ) + except ValueError as exc: + raise ValueError(f"Invalid OpenViking user_credentials.{uid}: {exc}") from exc + + existing_uid = seen_fingerprints.get(cred.key_fingerprint) + if existing_uid is not None: + raise ValueError(f"OpenViking user_credentials must not share the same API key across users ({existing_uid!r} and {uid!r})") + seen_fingerprints[cred.key_fingerprint] = uid + resolved[uid] = cred + return resolved + + def _mapping(value: Any, name: str) -> dict[str, Any]: if value is None: return {} @@ -171,6 +336,8 @@ def _number[T](cfg: dict[str, Any], key: str, default: T, cast: Callable[[Any], value = cfg.pop(key, default) if value is None or (isinstance(value, str) and not value.strip()): return default + if isinstance(value, bool): + raise ValueError(f"OpenViking {key} must be a number, got {type(value).__name__}") try: return cast(value) except (TypeError, ValueError): @@ -183,12 +350,42 @@ def _optional_float(value: Any, name: str) -> float | None: falling back to a default.""" if value is None or (isinstance(value, str) and not value.strip()): return None + if isinstance(value, bool): + raise ValueError(f"OpenViking {name} must be a number, got {type(value).__name__}") try: return float(value) except (TypeError, ValueError): raise ValueError(f"OpenViking {name} must be a number, got {type(value).__name__}") from None +def _pool_int(pool: dict[str, Any], key: str, default: int) -> int: + value = pool.pop(key, default) + if value is None or (isinstance(value, str) and not value.strip()): + return default + if isinstance(value, (bool, float)): + raise ValueError(f"OpenViking client_pool.{key} must be an integer, got {type(value).__name__}") + try: + return int(value) + except (TypeError, ValueError): + raise ValueError(f"OpenViking client_pool.{key} must be an integer, got {type(value).__name__}") from None + + +def _pool_idle_ttl(pool: dict[str, Any]) -> float | None: + if "idle_ttl_seconds" not in pool: + return _DEFAULT_POOL_IDLE_TTL_SECONDS + value = pool.pop("idle_ttl_seconds") + if value is None: + return None + if isinstance(value, bool): + raise ValueError(f"OpenViking client_pool.idle_ttl_seconds must be a number, got {type(value).__name__}") + if isinstance(value, str) and not value.strip(): + raise ValueError("OpenViking client_pool.idle_ttl_seconds must be a number or null, got empty str") + try: + return float(value) + except (TypeError, ValueError): + raise ValueError(f"OpenViking client_pool.idle_ttl_seconds must be a number, got {type(value).__name__}") from None + + def _boolean(value: Any, name: str) -> bool: if isinstance(value, bool): return value diff --git a/backend/packages/harness/deerflow/agents/memory/backends/openviking/credentials.py b/backend/packages/harness/deerflow/agents/memory/backends/openviking/credentials.py new file mode 100644 index 0000000000..52eda62561 --- /dev/null +++ b/backend/packages/harness/deerflow/agents/memory/backends/openviking/credentials.py @@ -0,0 +1,200 @@ +"""Credential types, validation, and dynamic provider loading for OpenViking.""" + +from __future__ import annotations + +import hashlib +import importlib +import keyword +import unicodedata +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import Any, Protocol, runtime_checkable + +_MAX_TENANT_ID_LENGTH = 128 +_ALLOWED_PROVIDER_RESULT_KEYS = frozenset({"api_key", "tenant_id"}) + + +def has_control_chars(value: str) -> bool: + """Return whether *value* contains NUL or any Unicode control character.""" + + return any(ord(ch) < 0x20 or ord(ch) == 0x7F or 0x80 <= ord(ch) <= 0x9F or unicodedata.category(ch) == "Cc" for ch in value) + + +def validate_api_key(api_key: Any) -> str: + """Validate an OpenViking USER API key without ever echoing its value.""" + + if not isinstance(api_key, str): + raise ValueError(f"OpenViking API key must be a non-empty string, got {type(api_key).__name__}") + if not api_key: + raise ValueError("OpenViking API key must not be empty") + if any(ord(ch) < 0x21 or ord(ch) > 0x7E for ch in api_key): + raise ValueError("OpenViking API key must contain printable ASCII characters only (0x21..0x7E)") + return api_key + + +def validate_tenant_id(tenant_id: Any) -> str | None: + """Validate an optional DeerFlow tenant identifier.""" + + if tenant_id is None: + return None + if not isinstance(tenant_id, str): + raise ValueError(f"OpenViking tenant_id must be a string, got {type(tenant_id).__name__}") + if not tenant_id: + raise ValueError("OpenViking tenant_id must not be empty") + if tenant_id != tenant_id.strip(): + raise ValueError("OpenViking tenant_id must not have leading or trailing whitespace") + if len(tenant_id) > _MAX_TENANT_ID_LENGTH: + raise ValueError(f"OpenViking tenant_id must be at most {_MAX_TENANT_ID_LENGTH} characters") + if has_control_chars(tenant_id): + raise ValueError("OpenViking tenant_id must not contain control characters") + return tenant_id + + +def validate_user_key(user_id: Any) -> str: + """Validate a static ``user_credentials`` map key.""" + + if not isinstance(user_id, str): + raise ValueError(f"OpenViking user_credentials keys must be strings, got {type(user_id).__name__}") + if not user_id or user_id != user_id.strip() or has_control_chars(user_id): + raise ValueError(f"OpenViking user_credentials key {user_id!r} must be a non-empty stripped string without control characters") + return user_id + + +@dataclass(frozen=True, slots=True) +class OpenVikingCredential: + """Validated OpenViking USER API credential for one DeerFlow identity.""" + + api_key: str = field(repr=False) + tenant_id: str | None = None + api_key_env: str | None = None + key_fingerprint: str = field(init=False, repr=False) + + def __post_init__(self) -> None: + validated_key = validate_api_key(self.api_key) + validated_tenant = validate_tenant_id(self.tenant_id) + object.__setattr__(self, "api_key", validated_key) + object.__setattr__(self, "tenant_id", validated_tenant) + if self.api_key_env is not None: + if not isinstance(self.api_key_env, str) or not self.api_key_env.strip() or has_control_chars(self.api_key_env): + raise ValueError("OpenViking api_key_env must be a non-empty string without control characters when provided") + object.__setattr__(self, "api_key_env", self.api_key_env.strip()) + digest = hashlib.sha256(validated_key.encode("utf-8")).hexdigest() + object.__setattr__(self, "key_fingerprint", digest) + + +@runtime_checkable +class OpenVikingCredentialProvider(Protocol): + """Dynamic per-user credential resolver for multi-user OpenViking deployments.""" + + def resolve(self, user_id: str) -> OpenVikingCredential | Mapping[str, Any] | str | None: + """Resolve an OpenViking USER credential for *user_id*, or ``None`` if unauthorized.""" + ... + + +def _is_valid_identifier(part: str) -> bool: + return bool(part) and part.isidentifier() and not keyword.iskeyword(part) + + +def _parse_provider_path(path: str) -> tuple[str, list[str]]: + if not isinstance(path, str) or not path or path != path.strip(): + raise ValueError("OpenViking credential_provider must be a non-empty 'module:attr' or 'module.attr' path") + if ":" in path: + if path.count(":") != 1: + raise ValueError("OpenViking credential_provider must contain at most one ':' separator") + module_path, attr_path = path.split(":", 1) + module_parts = module_path.split(".") + attr_parts = attr_path.split(".") + if not module_parts or not attr_parts or not all(_is_valid_identifier(p) for p in (*module_parts, *attr_parts)): + raise ValueError(f"Invalid OpenViking credential_provider path {path!r}: expected valid Python identifiers") + return module_path, attr_parts + + parts = path.split(".") + if len(parts) < 2 or not all(_is_valid_identifier(p) for p in parts): + raise ValueError(f"Invalid OpenViking credential_provider path {path!r}: expected 'pkg.mod:Attr' or 'pkg.mod.Attr'") + return ".".join(parts[:-1]), [parts[-1]] + + +def validate_provider_path(path: str) -> None: + """Validate ``credential_provider`` dotted/colon path syntax without importing or doing I/O.""" + + _parse_provider_path(path) + + +def _is_usable_provider(provider: Any) -> bool: + return callable(getattr(provider, "resolve", None)) or callable(provider) + + +def load_credential_provider(path: str, config: Mapping[str, Any]) -> Any: + """Import and instantiate/validate a configured OpenViking credential provider.""" + + module_path, attr_parts = _parse_provider_path(path) + if not isinstance(config, Mapping): + raise ValueError("OpenViking credential_provider_config must be a mapping") + kwargs = dict(config) + + module = importlib.import_module(module_path) + target: Any = module + for attr in attr_parts: + target = getattr(target, attr) + + if isinstance(target, type): + try: + provider = target(**kwargs) + except Exception as exc: + raise ValueError(f"OpenViking credential_provider {path!r} initialization failed ({type(exc).__name__})") from None + if not _is_usable_provider(provider): + raise ValueError(f"OpenViking credential_provider {path!r} instance must define a callable 'resolve(user_id)' method or be callable") + return provider + + if callable(target): + if kwargs: + try: + provider = target(**kwargs) + except Exception as exc: + raise ValueError(f"OpenViking credential_provider {path!r} initialization failed ({type(exc).__name__})") from None + if not _is_usable_provider(provider): + raise ValueError(f"OpenViking credential_provider factory {path!r} must return a callable or an object with a callable 'resolve(user_id)' method") + return provider + return target + + raise ValueError(f"OpenViking credential_provider {path!r} must resolve to a class or callable, got {type(target).__name__}") + + +def normalize_resolved_credential(raw: Any, *, user_id: str) -> OpenVikingCredential | None: + """Normalize a provider return value into ``OpenVikingCredential`` without echoing secrets.""" + + if raw is None: + return None + if isinstance(raw, OpenVikingCredential): + return raw + if isinstance(raw, str): + return OpenVikingCredential(api_key=raw) + if isinstance(raw, Mapping): + if not all(isinstance(k, str) for k in raw): + raise ValueError(f"OpenViking credential provider returned non-string keys for user {user_id!r}") + unknown = sorted(k for k in raw if k not in _ALLOWED_PROVIDER_RESULT_KEYS) + if unknown: + raise ValueError(f"OpenViking credential provider returned unsupported keys for user {user_id!r}: {', '.join(unknown)}") + if "api_key" not in raw: + raise ValueError(f"OpenViking credential provider response for user {user_id!r} is missing 'api_key'") + api_key = raw["api_key"] + if not isinstance(api_key, str) or not api_key: + raise ValueError(f"OpenViking credential provider returned invalid 'api_key' for user {user_id!r}") + tenant_id = raw.get("tenant_id") + if tenant_id is not None and not isinstance(tenant_id, str): + raise ValueError(f"OpenViking credential provider returned invalid 'tenant_id' for user {user_id!r}") + return OpenVikingCredential(api_key=api_key, tenant_id=tenant_id) + raise ValueError(f"OpenViking credential provider returned unsupported credential type {type(raw).__name__} for user {user_id!r}") + + +__all__ = [ + "OpenVikingCredential", + "OpenVikingCredentialProvider", + "has_control_chars", + "load_credential_provider", + "normalize_resolved_credential", + "validate_api_key", + "validate_provider_path", + "validate_tenant_id", + "validate_user_key", +] diff --git a/backend/packages/harness/deerflow/agents/memory/backends/openviking/openviking_manager.py b/backend/packages/harness/deerflow/agents/memory/backends/openviking/openviking_manager.py index 1d235c5730..30873df44d 100644 --- a/backend/packages/harness/deerflow/agents/memory/backends/openviking/openviking_manager.py +++ b/backend/packages/harness/deerflow/agents/memory/backends/openviking/openviking_manager.py @@ -10,15 +10,25 @@ import os import threading import time import weakref +from collections import OrderedDict +from collections.abc import Callable, Mapping from contextlib import AbstractContextManager +from dataclasses import dataclass from pathlib import Path from typing import Any, ClassVar, Literal +import httpx from pydantic import PrivateAttr from deerflow.agents.memory.manager import MemoryManager, MemoryManagerError, MemoryReadError from .config import OpenVikingConfig +from .credentials import ( + OpenVikingCredential, + load_credential_provider, + normalize_resolved_credential, + validate_user_key, +) from .session import ( _advanced_cursor, _canonical_peer_id, @@ -32,9 +42,25 @@ from .session import ( logger = logging.getLogger(__name__) +_ClientPoolKey = tuple[str | None, str, str] # (tenant_id, user_id, key_fingerprint) + + +@dataclass(slots=True, eq=False) +class _ScopedClientEntry: + """Pooled OpenViking SDK handles bound to one resolved credential scope.""" + + key: _ClientPoolKey + recorder: Any + retriever: Any + client: Any + active_ops: int = 0 + last_used: float = 0.0 + retired: bool = False + closed: bool = False + class OpenVikingMemoryManager(MemoryManager): - """Single-user OpenViking backend using the official integration package. + """OpenViking memory backend supporting single-user and multi-user isolation. DeerFlow continues to choose when capture and recall occur. The official adapter owns SDK transport, message conversion, batching, commit retries, @@ -44,10 +70,18 @@ class OpenVikingMemoryManager(MemoryManager): supports_search: ClassVar[bool] = True _config: OpenVikingConfig = PrivateAttr() - _client: Any = PrivateAttr() - _recorder: Any = PrivateAttr() - _retriever: Any = PrivateAttr() + _integration: dict[str, Any] = PrivateAttr() + _credential_provider: Any = PrivateAttr(default=None) + _single_user_credential: OpenVikingCredential | None = PrivateAttr(default=None) + _pool: OrderedDict[_ClientPoolKey, _ScopedClientEntry] = PrivateAttr(default_factory=OrderedDict) + _pool_lock: threading.Lock = PrivateAttr(default_factory=threading.Lock) + _inflight_entries: set[_ScopedClientEntry] = PrivateAttr(default_factory=set) + _clock: Callable[[], float] = PrivateAttr(default=time.monotonic) + _client: Any = PrivateAttr(default=None) + _recorder: Any = PrivateAttr(default=None) + _retriever: Any = PrivateAttr(default=None) _use_actor_peer: Any = PrivateAttr() + _use_home_alias_uris: bool = PrivateAttr(default=False) _partial_write_error: type[Exception] = PrivateAttr() _should_keep_hidden_message: Any = PrivateAttr(default=None) _session_locks: weakref.WeakValueDictionary[str, threading.RLock] = PrivateAttr(default_factory=weakref.WeakValueDictionary) @@ -57,34 +91,69 @@ class OpenVikingMemoryManager(MemoryManager): _closed: bool = PrivateAttr(default=False) _close_requested: bool = PrivateAttr(default=False) _resources_closed: bool = PrivateAttr(default=False) + _cleanup_started: bool = PrivateAttr(default=False) + _cleanup_done: threading.Event = PrivateAttr(default_factory=threading.Event) + _cleanup_failed: bool = PrivateAttr(default=False) + _flush_timed_out: bool = PrivateAttr(default=False) _resource_lock: threading.Lock = PrivateAttr(default_factory=threading.Lock) def model_post_init(self, __context: Any) -> None: - self._config = OpenVikingConfig.from_backend_config(self.backend_config) - integration = _load_official_integration() - commit_policy = integration["OpenVikingCommitPolicy"](mode="always") - self._recorder = integration["OpenVikingSessionRecorder"]( - url=self._config.base_url, - api_key=self._config.api_key, - timeout=self._config.timeout_seconds, - # An explicit mapping disables the SDK's ovcli.conf header fallback. - extra_headers={}, - commit_policy=commit_policy, + if self.mode != "middleware": + raise ValueError("The OpenViking automatic-memory backend supports memory.mode='middleware' only; use OpenViking MCP for explicit model tools") + + injected_provider = __context.get("credential_provider") if isinstance(__context, Mapping) else None + if injected_provider is not None and (isinstance(injected_provider, type) or not (callable(getattr(injected_provider, "resolve", None)) or callable(injected_provider))): + raise ValueError("OpenViking injected credential_provider must expose a callable 'resolve(user_id)' method or be callable") + + self._config = OpenVikingConfig.from_backend_config( + self.backend_config, + has_injected_credential_provider=injected_provider is not None, ) - # The recorder owns one recovery-aware SDK client. Retrieval borrows the - # same handle, so this backend has one connection pool and one owner. - self._client = self._recorder.client - self._retriever = integration["OpenVikingRetriever"]( - client=self._client, - search_mode="find", - limit=self._config.search_top_k, - score_threshold=self._config.score_threshold, - context_types=("memory",), - content_mode=self._config.content_mode, - max_content_chars=self._config.max_injection_chars, - ) - self._use_actor_peer = integration["use_actor_peer"] - self._partial_write_error = integration["OpenVikingPartialWriteError"] + if injected_provider is not None and self._config.credential_provider is not None: + raise ValueError("OpenViking cannot configure both backend_config.credential_provider and an injected credential_provider") + + loaded_provider = False + if injected_provider is not None: + self._credential_provider = injected_provider + elif self._config.credential_provider is not None: + self._credential_provider = load_credential_provider( + self._config.credential_provider, + self._config.credential_provider_config, + ) + loaded_provider = True + + try: + self._integration = _load_official_integration() + self._use_actor_peer = self._integration["use_actor_peer"] + self._partial_write_error = self._integration["OpenVikingPartialWriteError"] + + if self._config.isolation_mode == "single_user": + assert self._config.owner_user_id is not None + credential = OpenVikingCredential( + api_key=self._config.api_key, + tenant_id=None, + api_key_env=self._config.api_key_env, + ) + self._single_user_credential = credential + key: _ClientPoolKey = (None, self._config.owner_user_id, credential.key_fingerprint) + try: + entry = self._build_scoped_entry( + key=key, + api_key=credential.api_key, + now=self._clock(), + ) + except (MemoryManagerError, ValueError): + raise + except Exception as exc: + raise MemoryManagerError(f"Failed to initialize OpenViking client ({type(exc).__name__})") from None + self._pool[key] = entry + self._recorder = entry.recorder + self._client = entry.client + self._retriever = entry.retriever + except BaseException: + if loaded_provider: + self._close_credential_provider() + raise @classmethod def from_config( @@ -96,7 +165,11 @@ class OpenVikingMemoryManager(MemoryManager): ) -> OpenVikingMemoryManager: if mode != "middleware": raise ValueError("The OpenViking automatic-memory backend supports memory.mode='middleware' only; use OpenViking MCP for explicit model tools") - instance = cls(backend_config=backend_config or {}, mode=mode) + injected_provider = host_hooks.get("credential_provider") + instance = cls.model_validate( + {"backend_config": backend_config or {}, "mode": mode}, + context={"credential_provider": injected_provider}, + ) hidden_filter = host_hooks.get("should_keep_hidden_message") instance._should_keep_hidden_message = hidden_filter if callable(hidden_filter) else None return instance @@ -125,6 +198,18 @@ class OpenVikingMemoryManager(MemoryManager): ) -> bool: return OpenVikingConfig.from_backend_config(backend_config).read_failure_policy == "raise" + @property + def read_failures_are_fatal(self) -> bool: + """Whether read failures or timeouts abort for this manager instance. + + ``DynamicContextMiddleware`` consults the classmethod + :meth:`read_failures_are_fatal_for_config` over ``backend_config`` (which + requires ``user_credentials`` or ``credential_provider``), whereas this + instance property also covers direct programmatic callers injecting + ``host_hooks["credential_provider"]``. + """ + return self._config.read_failure_policy == "raise" + def add_nowait( self, thread_id: str, @@ -168,22 +253,33 @@ class OpenVikingMemoryManager(MemoryManager): thread_id: str | None = None, query: str | None = None, ) -> str: + del query if not self._begin_operation(): return "" + entry: _ScopedClientEntry | None = None try: - peer_id = self._resolve_read_scope(user_id, agent_name) - retriever = copy.copy(self._retriever) - retriever.target_uri = _memory_target_uris(peer_id) + resolved_user, credential, peer_id = self._resolve_read_scope(user_id, agent_name) + try: + entry = self._acquire_client(resolved_user, credential) + except MemoryManagerError as exc: + if self._config.read_failure_policy == "raise": + raise MemoryReadError(str(exc)) from exc + raise + retriever = copy.copy(entry.retriever) if thread_id: retriever.search_mode = "search" retriever.session_id = _session_id( - self._config.owner_user_id, + resolved_user, peer_id, thread_id, + tenant_id=credential.tenant_id, ) try: - with self._actor_peer_scope(peer_id): - documents = retriever.invoke(self._config.injection_query) + documents = self._invoke_retriever( + retriever, + self._config.injection_query, + peer_id=peer_id, + ) except Exception as exc: if self._config.read_failure_policy == "raise": raise MemoryReadError("OpenViking context retrieval failed") from exc @@ -197,6 +293,8 @@ class OpenVikingMemoryManager(MemoryManager): max_chars=self._config.max_injection_chars, ) finally: + if entry is not None: + self._release_client(entry) self._end_operation() async def aget_context( @@ -226,10 +324,16 @@ class OpenVikingMemoryManager(MemoryManager): ) -> list[dict[str, Any]]: if not query.strip() or not self._begin_operation(): return [] + entry: _ScopedClientEntry | None = None try: - peer_id = self._resolve_read_scope(user_id, agent_name) - retriever = copy.copy(self._retriever) - retriever.target_uri = _memory_target_uris(peer_id) + resolved_user, credential, peer_id = self._resolve_read_scope(user_id, agent_name) + try: + entry = self._acquire_client(resolved_user, credential) + except MemoryManagerError as exc: + if self._config.read_failure_policy == "raise": + raise MemoryReadError(str(exc)) from exc + raise + retriever = copy.copy(entry.retriever) retriever.search_mode = "find" retriever.session_id = None retriever.limit = max(1, min(int(top_k), 100)) @@ -240,8 +344,11 @@ class OpenVikingMemoryManager(MemoryManager): "conds": [category], } try: - with self._actor_peer_scope(peer_id): - documents = retriever.invoke(query.strip()) + documents = self._invoke_retriever( + retriever, + query.strip(), + peer_id=peer_id, + ) except Exception as exc: if self._config.read_failure_policy == "raise": raise MemoryReadError("OpenViking memory search failed") from exc @@ -252,6 +359,8 @@ class OpenVikingMemoryManager(MemoryManager): return [] return [_document_to_fact(document) for document in documents] finally: + if entry is not None: + self._release_client(entry) self._end_operation() async def asearch( @@ -277,11 +386,16 @@ class OpenVikingMemoryManager(MemoryManager): return False try: try: - health = getattr(self._client, "health", None) - healthy = bool(health()) if callable(health) else True - except Exception: + if self._config.isolation_mode == "single_user": + health = getattr(self._client, "health", None) + healthy = bool(health()) if callable(health) else True + else: + healthy = self._probe_health_unauthenticated() + except Exception as exc: if self._config.startup_policy == "fail_fast": - raise + if isinstance(exc, MemoryManagerError): + raise + raise MemoryManagerError("OpenViking startup validation failed") from exc logger.warning( "OpenViking startup validation failed; memory will run in degraded mode", exc_info=True, @@ -295,6 +409,18 @@ class OpenVikingMemoryManager(MemoryManager): finally: self._end_operation() + def _probe_health_unauthenticated(self) -> bool: + url = f"{self._config.base_url}/health" + with httpx.Client(timeout=self._config.timeout_seconds) as client: + response = client.get(url) + if response.status_code != 200: + return False + try: + payload = response.json() + except ValueError: + return False + return isinstance(payload, dict) and payload.get("status") == "ok" + def shutdown_flush(self, timeout: float) -> bool: """Stop new work, drain accepted calls, and close owned resources.""" @@ -305,10 +431,18 @@ class OpenVikingMemoryManager(MemoryManager): while self._active_operations: remaining = deadline - time.monotonic() if remaining <= 0: + self._flush_timed_out = True return False self._lifecycle.wait(remaining) - self._close_resources() - return True + done = self._start_resource_cleanup() + if done.is_set(): + return not self._cleanup_failed + finished = done.wait(timeout=max(0.0, deadline - time.monotonic())) + if not finished: + with self._lifecycle: + self._flush_timed_out = True + return False + return not self._cleanup_failed def close(self) -> None: """Request idempotent closure after any active operation finishes.""" @@ -317,8 +451,12 @@ class OpenVikingMemoryManager(MemoryManager): self._closed = True self._close_requested = True can_close = self._active_operations == 0 - if can_close: - self._close_resources() + already_timed_out = self._flush_timed_out + if not can_close: + return + done = self._start_resource_cleanup() + if not done.is_set() and not already_timed_out: + done.wait(timeout=self._config.timeout_seconds) def _write_conversation( self, @@ -331,26 +469,30 @@ class OpenVikingMemoryManager(MemoryManager): if not self._begin_operation(): logger.warning("OpenViking write ignored after backend shutdown") return + entry: _ScopedClientEntry | None = None try: if not thread_id: raise ValueError("OpenViking memory write requires thread_id") try: - peer_id = self._resolve_scope(user_id, agent_name) + resolved_user, credential, peer_id = self._resolve_scope(user_id, agent_name) + entry = self._acquire_client(resolved_user, credential) except MemoryManagerError as exc: - # The owner check has already refused the write before any - # remote call; the write policy decides whether that refusal + # Scope/credential checks have already refused the write before + # any remote call; the write policy decides whether that refusal # also fails a turn whose answer was already generated. if self._config.write_failure_policy == "raise": raise logger.error("%s Dropping the memory write (thread=%s).", exc, thread_id) return session_id = _session_id( - self._config.owner_user_id, + resolved_user, peer_id, thread_id, + tenant_id=credential.tenant_id, ) with self._session_lock(session_id): self._capture_locked( + entry.recorder, session_id, peer_id, _captureable_messages( @@ -359,10 +501,13 @@ class OpenVikingMemoryManager(MemoryManager): ), ) finally: + if entry is not None: + self._release_client(entry) self._end_operation() def _capture_locked( self, + recorder: Any, session_id: str, peer_id: str, messages: list[Any], @@ -373,7 +518,7 @@ class OpenVikingMemoryManager(MemoryManager): if state.get("commit_pending"): try: with self._actor_peer_scope(peer_id): - self._recorder.flush(session_id) + recorder.flush(session_id) except Exception as exc: self._handle_write_error( exc, @@ -382,7 +527,8 @@ class OpenVikingMemoryManager(MemoryManager): ) return state = {**state, "commit_pending": False} - self._save_cursor(session_id, state) + if not self._save_cursor_with_policy(session_id, state): + return start = _matching_prefix_count(state, signatures) append_only = start is not None @@ -396,7 +542,7 @@ class OpenVikingMemoryManager(MemoryManager): pending_signatures = [signature for _, signature in pending_pairs] if not pending: - self._save_cursor( + self._save_cursor_with_policy( session_id, _advanced_cursor( state, @@ -410,7 +556,7 @@ class OpenVikingMemoryManager(MemoryManager): try: with self._actor_peer_scope(peer_id): - self._recorder.record( + recorder.record( session_id, pending, peer_id=peer_id, @@ -427,16 +573,23 @@ class OpenVikingMemoryManager(MemoryManager): commit_pending = bool(getattr(exc, "commit_pending", False)) if confirmed or commit_pending: confirmed_prefix = signatures[: int(start or 0) + consumed] if append_only else None - self._save_cursor( - session_id, - _advanced_cursor( - state, - confirmed_prefix, - confirmed, - max_seen=self._config.max_seen_message_ids, - commit_pending=commit_pending, - ), - ) + try: + self._save_cursor( + session_id, + _advanced_cursor( + state, + confirmed_prefix, + confirmed, + max_seen=self._config.max_seen_message_ids, + commit_pending=commit_pending, + ), + ) + except OSError as cursor_exc: + logger.warning( + "Failed to persist partial OpenViking capture cursor (session=%s, error=%s)", + session_id, + type(cursor_exc).__name__, + ) self._handle_write_error( exc, "OpenViking partially recorded a conversation; confirmed progress was preserved", @@ -451,7 +604,7 @@ class OpenVikingMemoryManager(MemoryManager): ) return - self._save_cursor( + self._save_cursor_with_policy( session_id, _advanced_cursor( state, @@ -466,17 +619,58 @@ class OpenVikingMemoryManager(MemoryManager): self, user_id: str | None, agent_name: str | None, - ) -> str: - resolved_user = str(user_id or "default") - if resolved_user != self._config.owner_user_id: - raise MemoryManagerError(f"OpenViking USER API key is bound to DeerFlow owner_user_id {self._config.owner_user_id!r}, but this request belongs to {resolved_user!r}. Refusing to share one credential across users.") - return _canonical_peer_id(agent_name, self._config.default_peer_id) + ) -> tuple[str, OpenVikingCredential, str]: + if self._config.isolation_mode == "single_user": + resolved_user = str(user_id or "default") + if resolved_user != self._config.owner_user_id: + raise MemoryManagerError(f"OpenViking USER API key is bound to DeerFlow owner_user_id {self._config.owner_user_id!r}, but this request belongs to {resolved_user!r}. Refusing to share one credential across users.") + assert self._single_user_credential is not None + try: + peer_id = _canonical_peer_id(agent_name, self._config.default_peer_id) + except ValueError as exc: + raise MemoryManagerError(str(exc)) from exc + return resolved_user, self._single_user_credential, peer_id + + if user_id is None: + raise MemoryManagerError("OpenViking multi-user mode requires a non-empty DeerFlow user_id; refusing anonymous fallback.") + resolved_user = str(user_id) + if not resolved_user or not resolved_user.strip(): + raise MemoryManagerError("OpenViking multi-user mode requires a non-empty DeerFlow user_id; refusing blank fallback.") + try: + resolved_user = validate_user_key(resolved_user) + except ValueError as exc: + raise MemoryManagerError(f"OpenViking multi-user mode requires a stripped DeerFlow user_id without control characters, got {resolved_user!r}") from exc + + credential = self._config.user_credentials.get(resolved_user) + if credential is None and self._credential_provider is not None: + try: + resolve_fn = getattr(self._credential_provider, "resolve", None) + if callable(resolve_fn): + raw = resolve_fn(resolved_user) + else: + raw = self._credential_provider(resolved_user) + except Exception as exc: + raise MemoryManagerError(f"OpenViking credential provider failed for DeerFlow user {resolved_user!r} ({type(exc).__name__})") from None + try: + credential = normalize_resolved_credential(raw, user_id=resolved_user) + except ValueError as exc: + raise MemoryManagerError(str(exc)) from exc + + if credential is None: + self._retire_user_entries(resolved_user) + raise MemoryManagerError(f"No OpenViking USER API key is configured for DeerFlow user {resolved_user!r}. Refusing to share or fall back to another credential.") + + try: + peer_id = _canonical_peer_id(agent_name, self._config.default_peer_id) + except ValueError as exc: + raise MemoryManagerError(str(exc)) from exc + return resolved_user, credential, peer_id def _resolve_read_scope( self, user_id: str | None, agent_name: str | None, - ) -> str: + ) -> tuple[str, OpenVikingCredential, str]: try: return self._resolve_scope(user_id, agent_name) except MemoryManagerError as exc: @@ -484,6 +678,267 @@ class OpenVikingMemoryManager(MemoryManager): raise MemoryReadError(str(exc)) from exc raise + def _build_scoped_entry( + self, + *, + key: _ClientPoolKey, + api_key: str, + now: float, + ) -> _ScopedClientEntry: + if not api_key: + raise MemoryManagerError("Refusing to construct OpenViking client with an empty API key") + commit_policy = self._integration["OpenVikingCommitPolicy"](mode="always") + recorder = self._integration["OpenVikingSessionRecorder"]( + url=self._config.base_url, + api_key=api_key, + timeout=self._config.timeout_seconds, + # An explicit mapping disables the SDK's ovcli.conf header fallback. + extra_headers={}, + commit_policy=commit_policy, + ) + try: + # The recorder owns one recovery-aware SDK client. Retrieval borrows the + # same handle, so each scope has one connection pool and one owner. + client = recorder.client + retriever = self._integration["OpenVikingRetriever"]( + client=client, + search_mode="find", + limit=self._config.search_top_k, + score_threshold=self._config.score_threshold, + context_types=("memory",), + content_mode=self._config.content_mode, + max_content_chars=self._config.max_injection_chars, + ) + except BaseException: + try: + recorder.close() + except Exception as close_exc: + logger.debug("Failed to close OpenViking recorder after setup error (%s)", type(close_exc).__name__) + raise + return _ScopedClientEntry( + key=key, + recorder=recorder, + retriever=retriever, + client=client, + last_used=now, + ) + + def _acquire_client( + self, + user_id: str, + credential: OpenVikingCredential, + ) -> _ScopedClientEntry: + key: _ClientPoolKey = (credential.tenant_id, user_id, credential.key_fingerprint) + if self._config.isolation_mode == "single_user": + with self._pool_lock: + if self._resources_closed: + raise MemoryManagerError("OpenViking memory backend is closed") + entry = self._pool.get(key) + if entry is None or entry.retired or entry.closed: + raise MemoryManagerError("OpenViking client handle is unavailable") + entry.active_ops += 1 + entry.last_used = self._clock() + self._pool.move_to_end(key) + self._inflight_entries.add(entry) + return entry + + to_close: list[_ScopedClientEntry] = [] + error: MemoryManagerError | None = None + acquired: _ScopedClientEntry | None = None + now = self._clock() + + with self._pool_lock: + if self._resources_closed: + raise MemoryManagerError("OpenViking memory backend is closed") + to_close.extend(self._evict_idle_ttl_locked(now)) + error = self._check_fingerprint_conflict_locked(user_id=user_id, credential=credential) + if error is None: + existing = self._pool.get(key) + if existing is not None and not existing.retired and not existing.closed: + existing.active_ops += 1 + existing.last_used = now + self._pool.move_to_end(key) + self._inflight_entries.add(existing) + acquired = existing + + self._close_entries(to_close) + if error is not None: + raise error + if acquired is not None: + return acquired + + # Build the SDK handles outside _pool_lock so concurrent users never stall on init/I/O. + try: + new_entry = self._build_scoped_entry( + key=key, + api_key=credential.api_key, + now=now, + ) + except MemoryManagerError: + raise + except Exception as exc: + raise MemoryManagerError(f"Failed to initialize OpenViking client for DeerFlow user {user_id!r} ({type(exc).__name__})") from None + + to_close = [] + discard_new = False + publish_error: MemoryManagerError | None = None + winner: _ScopedClientEntry | None = None + now = self._clock() + + with self._pool_lock: + if self._resources_closed: + discard_new = True + publish_error = MemoryManagerError("OpenViking memory backend is closed") + else: + to_close.extend(self._evict_idle_ttl_locked(now)) + publish_error = self._check_fingerprint_conflict_locked(user_id=user_id, credential=credential) + if publish_error is not None: + discard_new = True + else: + existing = self._pool.get(key) + if existing is not None and not existing.retired and not existing.closed: + existing.active_ops += 1 + existing.last_used = now + self._pool.move_to_end(key) + self._inflight_entries.add(existing) + winner = existing + discard_new = True + else: + to_close.extend(self._retire_scope_rotations_locked(key)) + to_close.extend(self._evict_lru_locked()) + new_entry.active_ops = 1 + new_entry.last_used = now + self._pool[key] = new_entry + self._inflight_entries.add(new_entry) + winner = new_entry + + if discard_new: + to_close.append(new_entry) + self._close_entries(to_close) + if publish_error is not None: + raise publish_error + assert winner is not None + return winner + + def _release_client(self, entry: _ScopedClientEntry) -> None: + should_close = False + with self._pool_lock: + if entry.active_ops > 0: + entry.active_ops -= 1 + if self._config.isolation_mode == "multi_user": + entry.last_used = self._clock() + if entry.active_ops == 0: + self._inflight_entries.discard(entry) + if entry.retired and not entry.closed: + entry.closed = True + should_close = True + if should_close: + self._close_entries([entry]) + + def _evict_idle_ttl_locked(self, now: float) -> list[_ScopedClientEntry]: + ttl = self._config.pool_idle_ttl_seconds + if ttl is None: + return [] + evicted: list[_ScopedClientEntry] = [] + for entry_key in list(self._pool): + entry = self._pool[entry_key] + if entry.active_ops == 0 and (now - entry.last_used) >= ttl: + del self._pool[entry_key] + entry.retired = True + if not entry.closed: + entry.closed = True + evicted.append(entry) + return evicted + + def _check_fingerprint_conflict_locked( + self, + *, + user_id: str, + credential: OpenVikingCredential, + ) -> MemoryManagerError | None: + target_scope = (credential.tenant_id, user_id) + # In hybrid mode, also reject reuse of uncached or LRU/TTL-evicted static credentials. + for static_user, static_cred in self._config.user_credentials.items(): + static_scope = (static_cred.tenant_id, static_user) + if static_cred.key_fingerprint == credential.key_fingerprint and static_scope != target_scope: + return MemoryManagerError(f"OpenViking USER API key cannot be shared across distinct DeerFlow scopes ({static_scope!r} and {target_scope!r})") + for entry in (*self._pool.values(), *self._inflight_entries): + if entry.key[2] == credential.key_fingerprint and (entry.key[0], entry.key[1]) != target_scope: + other_scope = (entry.key[0], entry.key[1]) + return MemoryManagerError(f"OpenViking USER API key cannot be shared across distinct DeerFlow scopes ({other_scope!r} and {target_scope!r})") + return None + + def _retire_scope_rotations_locked( + self, + new_key: _ClientPoolKey, + ) -> list[_ScopedClientEntry]: + user_id = new_key[1] + retired: list[_ScopedClientEntry] = [] + for entry_key in list(self._pool): + if entry_key[1] == user_id and entry_key != new_key: + entry = self._pool.pop(entry_key) + entry.retired = True + if entry.active_ops == 0 and not entry.closed: + entry.closed = True + retired.append(entry) + for entry in self._inflight_entries: + if entry.key[1] == user_id and entry.key != new_key: + entry.retired = True + return retired + + def _evict_lru_locked(self) -> list[_ScopedClientEntry]: + evicted: list[_ScopedClientEntry] = [] + while len(self._pool) >= self._config.pool_max_clients: + victim_key = next( + (k for k, entry in self._pool.items() if entry.active_ops == 0), + None, + ) + if victim_key is None: + victim_key, victim = self._pool.popitem(last=False) + else: + victim = self._pool.pop(victim_key) + victim.retired = True + if victim.active_ops == 0 and not victim.closed: + victim.closed = True + evicted.append(victim) + return evicted + + def _retire_user_entries(self, user_id: str) -> None: + to_close: list[_ScopedClientEntry] = [] + with self._pool_lock: + for entry_key in [k for k in self._pool if k[1] == user_id]: + entry = self._pool.pop(entry_key) + entry.retired = True + if entry.active_ops == 0 and not entry.closed: + entry.closed = True + to_close.append(entry) + for entry in self._inflight_entries: + if entry.key[1] == user_id: + entry.retired = True + self._close_entries(to_close) + + @staticmethod + def _close_entries(entries: list[_ScopedClientEntry]) -> None: + for entry in entries: + try: + entry.recorder.close() + except Exception as exc: + logger.warning( + "Failed to close OpenViking recorder for scope (%r, %r) (%s)", + entry.key[0], + entry.key[1], + type(exc).__name__, + ) + + def _close_credential_provider(self) -> None: + provider = self._credential_provider + close_fn = getattr(provider, "close", None) + if callable(close_fn): + try: + close_fn() + except Exception as exc: + logger.warning("Failed to close OpenViking credential provider (%s)", type(exc).__name__) + def _actor_peer_scope( self, peer_id: str, @@ -512,17 +967,59 @@ class OpenVikingMemoryManager(MemoryManager): self._lifecycle.notify_all() should_close = self._close_requested if should_close: - try: - self._close_resources() - except Exception: - logger.exception("Failed to close OpenViking memory resources") + # Start single-flight cleanup without blocking the finishing operation's + # executor worker; shutdown_flush()/close() own any cleanup wait budget. + self._start_resource_cleanup() - def _close_resources(self) -> None: + def _start_resource_cleanup(self) -> threading.Event: + to_close: list[_ScopedClientEntry] = [] + should_spawn = False with self._resource_lock: - if self._resources_closed: - return - self._recorder.close() - self._resources_closed = True + if not self._cleanup_started: + self._cleanup_started = True + with self._pool_lock: + self._resources_closed = True + drained = list(self._pool.values()) + self._pool.clear() + for entry in drained: + entry.retired = True + if entry.active_ops == 0 and not entry.closed: + entry.closed = True + to_close.append(entry) + for entry in self._inflight_entries: + entry.retired = True + if entry.active_ops == 0 and not entry.closed: + entry.closed = True + to_close.append(entry) + close_fn = getattr(self._credential_provider, "close", None) + if not to_close and not callable(close_fn): + self._cleanup_done.set() + else: + should_spawn = True + + if should_spawn: + + def _run_cleanup() -> None: + try: + self._close_entries(to_close) + self._close_credential_provider() + except Exception as exc: + logger.warning("Failed to close OpenViking memory resources (%s)", type(exc).__name__) + finally: + self._cleanup_done.set() + + try: + threading.Thread( + target=_run_cleanup, + name="openviking-resource-cleanup", + daemon=True, + ).start() + except Exception as exc: + logger.warning("Failed to start OpenViking cleanup worker (%s)", type(exc).__name__) + self._cleanup_failed = True + self._cleanup_done.set() + + return self._cleanup_done def _state_path(self, session_id: str) -> Path: root = Path(self._config.storage_path or ".") / "openviking" / "sessions" @@ -560,6 +1057,36 @@ class OpenVikingMemoryManager(MemoryManager): exc_info=True, ) + def _save_cursor_with_policy(self, session_id: str, state: dict[str, Any]) -> bool: + try: + self._save_cursor(session_id, state) + return True + except OSError as exc: + self._handle_write_error( + exc, + "OpenViking capture cursor persistence failed", + session_id, + ) + return False + + def _invoke_retriever(self, retriever: Any, query: str, *, peer_id: str) -> list[Any]: + use_home = self._use_home_alias_uris + retriever.target_uri = _memory_target_uris(peer_id, use_home_alias=use_home) + try: + with self._actor_peer_scope(peer_id): + return retriever.invoke(query) + except Exception as exc: + if use_home or not _should_retry_with_home_alias(exc): + raise + # OpenViking >=0.5.5 rejects uid-less ``viking://user/`` shorthands; + # retry once with ``viking://~/...`` and remember it for future calls. + self._use_home_alias_uris = True + logger.info("OpenViking server requires 'viking://~/' user-space URIs; switching target_uri format") + retry_retriever = copy.copy(retriever) + retry_retriever.target_uri = _memory_target_uris(peer_id, use_home_alias=True) + with self._actor_peer_scope(peer_id): + return retry_retriever.invoke(query) + def _handle_write_error( self, exc: Exception, @@ -572,6 +1099,14 @@ class OpenVikingMemoryManager(MemoryManager): logger.error(detail, exc_info=True) +def _should_retry_with_home_alias(exc: Exception) -> bool: + """Return True when an OpenViking >=0.5.5 server rejected legacy uid-less URIs.""" + + if "viking://~/" not in str(exc): + return False + return getattr(exc, "code", None) == "INVALID_URI" or type(exc).__name__ == "InvalidURIError" + + def _load_official_integration() -> dict[str, Any]: try: from langchain_openviking import ( diff --git a/backend/packages/harness/deerflow/agents/memory/backends/openviking/session.py b/backend/packages/harness/deerflow/agents/memory/backends/openviking/session.py index 293e6a56fc..163af14a71 100644 --- a/backend/packages/harness/deerflow/agents/memory/backends/openviking/session.py +++ b/backend/packages/harness/deerflow/agents/memory/backends/openviking/session.py @@ -10,6 +10,7 @@ from typing import Any from .config import GENERATED_PEER_PREFIX, is_safe_peer_id _SESSION_NAMESPACE = "deerflow-openviking-adapter-v1" +_TENANT_SESSION_NAMESPACE = "deerflow-openviking-adapter-v2" _DEFAULT_AGENT_SCOPE = "__default__" _CURSOR_SCHEMA_VERSION = 1 @@ -40,19 +41,26 @@ def _session_id( owner_user_id: str, peer_id: str, thread_id: str, + *, + tenant_id: str | None = None, ) -> str: """Derive one stable OpenViking session for one DeerFlow thread.""" - digest = hashlib.sha256(f"{_SESSION_NAMESPACE}\0{owner_user_id}\0{peer_id}\0{thread_id}".encode()).hexdigest() + if tenant_id is None: + raw = f"{_SESSION_NAMESPACE}\0{owner_user_id}\0{peer_id}\0{thread_id}" + else: + raw = f"{_TENANT_SESSION_NAMESPACE}\0{tenant_id}\0{owner_user_id}\0{peer_id}\0{thread_id}" + digest = hashlib.sha256(raw.encode("utf-8")).hexdigest() return f"df_{digest[:48]}" -def _memory_target_uris(peer_id: str) -> list[str]: +def _memory_target_uris(peer_id: str, *, use_home_alias: bool = False) -> list[str]: """Return the self and current-peer memory roots for a request.""" + prefix = "viking://~" if use_home_alias else "viking://user" return [ - "viking://user/memories", - f"viking://user/peers/{peer_id}/memories", + f"{prefix}/memories", + f"{prefix}/peers/{peer_id}/memories", ] diff --git a/backend/tests/blocking_io/test_openviking_memory_backend.py b/backend/tests/blocking_io/test_openviking_memory_backend.py index 7de1f57491..37278e1c6c 100644 --- a/backend/tests/blocking_io/test_openviking_memory_backend.py +++ b/backend/tests/blocking_io/test_openviking_memory_backend.py @@ -2,6 +2,9 @@ from __future__ import annotations +import asyncio +import json +import threading from contextlib import nullcontext from pathlib import Path from typing import Any @@ -145,3 +148,149 @@ async def test_async_openviking_operations_do_not_block_event_loop( "score": 0.9, } ] + + +@pytest.mark.asyncio +async def test_multi_user_async_openviking_operations_and_eviction_do_not_block_event_loop( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import deerflow.agents.memory.backends.openviking.openviking_manager as module + + probe_dir = tmp_path / "probes" + probe_dir.mkdir() + creds_path = tmp_path / "credentials.json" + creds_path.write_text( + json.dumps( + { + "alice": {"api_key": "alice-key", "tenant_id": "acme"}, + "bob": {"api_key": "bob-key", "tenant_id": "globex"}, + } + ), + encoding="utf-8", + ) + + events: list[tuple[str, str, int]] = [] + close_files: list[Path] = [] + lock = threading.Lock() + + def _record_event(kind: str, label: str) -> int: + idx_holder: int + with lock: + events.append((kind, label, threading.get_ident())) + idx_holder = len(events) + return idx_holder + + class _FileCredentialProvider: + def resolve(self, user_id: str) -> dict[str, Any] | None: + _record_event("resolve", user_id) + data = json.loads(creds_path.read_text(encoding="utf-8")) + return data.get(user_id) + + class _MultiUserClient(_Client): + def __init__(self, api_key: str) -> None: + self.api_key = api_key + + class _MultiUserBlockingRecorder: + def __init__(self, *, commit_policy: Any, api_key: str, **kwargs: Any): + del kwargs + self.commit_policy = commit_policy + self.api_key = api_key + self.client = _MultiUserClient(api_key) + idx = _record_event("init", api_key) + (probe_dir / f"init-{api_key}-{idx}.txt").write_text("init", encoding="utf-8") + + def record( + self, + session_id: str, + messages: list[Any], + peer_id: str | None = None, + ) -> None: + del session_id, messages, peer_id + idx = _record_event("record", self.api_key) + (probe_dir / f"record-{self.api_key}-{idx}.txt").write_text("record", encoding="utf-8") + + def flush(self, session_id: str) -> None: + del session_id + + def close(self) -> None: + idx = _record_event("close", self.api_key) + path = probe_dir / f"close-{self.api_key}-{idx}.txt" + path.write_text("close", encoding="utf-8") + close_files.append(path) + + class _MultiUserBlockingRetriever(_BlockingRetriever): + def __init__(self, *, client: Any, **kwargs: Any): + super().__init__(client=client, **kwargs) + self._api_key = getattr(client, "api_key", "") + + def __copy__(self) -> _MultiUserBlockingRetriever: + copied = type(self)(client=None) + copied.__dict__.update(self.__dict__) + return copied + + def invoke(self, query: str) -> list[Document]: + del query + idx = _record_event("retrieve", self._api_key) + (probe_dir / f"retrieve-{self._api_key}-{idx}.txt").write_text("retrieve", encoding="utf-8") + return [ + Document( + page_content="Prefers concise answers.", + metadata={ + "openviking_uri": "viking://user/memories/preferences/test.md", + "openviking_category": "preferences", + "openviking_score": 0.9, + }, + ) + ] + + monkeypatch.setattr( + module, + "_load_official_integration", + lambda: { + "OpenVikingCommitPolicy": _CommitPolicy, + "OpenVikingPartialWriteError": RuntimeError, + "OpenVikingRetriever": _MultiUserBlockingRetriever, + "OpenVikingSessionRecorder": _MultiUserBlockingRecorder, + "use_actor_peer": lambda peer_id: nullcontext(), + }, + ) + + manager = OpenVikingMemoryManager.from_config( + { + "base_url": "http://openviking:1933", + "storage_path": str(tmp_path), + "startup_policy": "warn", + "failure_policy": {"read": "raise", "write": "raise"}, + "client_pool": {"max_clients": 1}, + }, + credential_provider=_FileCredentialProvider(), + ) + + event_loop_thread = threading.get_ident() + messages: list[Any] = [HumanMessage("hello", id="h1"), AIMessage("hi", id="a1")] + try: + await manager.aadd("thread-1", messages, user_id="alice") + context = await manager.aget_context("bob", thread_id="thread-1") + results = await manager.asearch("answer style", user_id="alice") + + assert context == "- [preferences] Prefers concise answers." + assert results == [ + { + "id": "viking://user/memories/preferences/test.md", + "content": "Prefers concise answers.", + "category": "preferences", + "confidence": 0.9, + "source": "viking://user/memories/preferences/test.md", + "score": 0.9, + } + ] + eviction_closes = [(label, tid) for kind, label, tid in events if kind == "close"] + assert [label for label, _ in eviction_closes] == ["alice-key", "bob-key"] + assert len(close_files) == 2 + assert all(path.exists() for path in close_files) + assert {kind for kind, _, _ in events} == {"resolve", "init", "record", "retrieve", "close"} + assert all(tid != event_loop_thread for _, _, tid in events) + assert list((tmp_path / "openviking" / "sessions").glob("*.json")) + finally: + await asyncio.to_thread(manager.close) diff --git a/backend/tests/test_doctor_script.py b/backend/tests/test_doctor_script.py index 6fa58b3fea..4177e31d10 100644 --- a/backend/tests/test_doctor_script.py +++ b/backend/tests/test_doctor_script.py @@ -170,6 +170,71 @@ class TestMemoryBackendConfigCheck: assert "USER API key is missing" in result.detail assert result.fix == "Add OPENVIKING_API_KEY= to your .env file" + def test_multi_user_valid_config_passes(self, doctor, monkeypatch): + monkeypatch.setenv("ALICE_OV_KEY", "alice-secret") + monkeypatch.setenv("BOB_OV_KEY", "bob-secret") + static_cfg = self._config( + "openviking", + { + "base_url": "http://127.0.0.1:1933", + "user_credentials": { + "alice": {"api_key_env": "ALICE_OV_KEY", "tenant_id": "acme"}, + "bob": {"api_key_env": "BOB_OV_KEY", "tenant_id": "globex"}, + }, + "client_pool": {"max_clients": 16, "idle_ttl_seconds": None}, + }, + ) + assert doctor._check_memory_backend_config(static_cfg).status == "ok" + + provider_cfg = self._config( + "openviking", + { + "base_url": "http://127.0.0.1:1933", + "credential_provider": "nonexistent_doctor_mod.auth:VaultProvider", + "credential_provider_config": {"endpoint": "https://vault.internal"}, + }, + ) + assert doctor._check_memory_backend_config(provider_cfg).status == "ok" + + def test_multi_user_missing_api_key_advises_dotenv(self, doctor, monkeypatch): + monkeypatch.setenv("ALICE_OV_KEY", "alice-secret") + monkeypatch.delenv("BOB_OV_KEY", raising=False) + config = self._config( + "openviking", + { + "base_url": "http://127.0.0.1:1933", + "user_credentials": { + "alice": {"api_key_env": "ALICE_OV_KEY"}, + "bob": {"api_key_env": "BOB_OV_KEY"}, + }, + }, + ) + + result = doctor._check_memory_backend_config(config) + + assert result.status == "fail" + assert "USER API key is missing" in result.detail + assert "bob" in result.detail + assert result.fix == "Add BOB_OV_KEY= to your .env file" + + def test_conflicting_owner_user_id_and_user_credentials_fails(self, doctor, monkeypatch): + monkeypatch.setenv("ALICE_OV_KEY", "alice-secret") + config = self._config( + "openviking", + { + "base_url": "http://127.0.0.1:1933", + "owner_user_id": "alice", + "user_credentials": { + "alice": {"api_key_env": "ALICE_OV_KEY"}, + }, + }, + ) + + result = doctor._check_memory_backend_config(config) + + assert result.status == "fail" + assert "owner_user_id" in result.detail + def test_memory_backend_config_failure_is_reported_end_to_end(doctor_checkout: Path): (doctor_checkout / "config.yaml").write_text( diff --git a/backend/tests/test_openviking_memory_backend.py b/backend/tests/test_openviking_memory_backend.py index 72cd85c208..ef089ae4fe 100644 --- a/backend/tests/test_openviking_memory_backend.py +++ b/backend/tests/test_openviking_memory_backend.py @@ -4,10 +4,14 @@ from __future__ import annotations import copy import gc +import hashlib +import importlib import json import logging import socket +import sys import threading +import time import weakref from collections.abc import Iterator from contextlib import contextmanager @@ -21,6 +25,13 @@ from langchain_core.documents import Document from langchain_core.messages import AIMessage, HumanMessage from deerflow.agents.memory.backends.openviking.config import OpenVikingConfig +from deerflow.agents.memory.backends.openviking.credentials import ( + OpenVikingCredential, + OpenVikingCredentialProvider, + load_credential_provider, + normalize_resolved_credential, + validate_provider_path, +) from deerflow.agents.memory.backends.openviking.openviking_manager import ( OpenVikingMemoryManager, _canonical_peer_id, @@ -60,7 +71,7 @@ def openviking_http_server(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[st def do_POST(self) -> None: payload = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) requests.append({"path": self.path, "headers": {key.lower(): value for key, value in self.headers.items()}, "payload": payload}) - if self.path == "/api/v1/search/find": + if self.path in {"/api/v1/search/find", "/api/v1/search/search"}: result = {"memories": [{"uri": "viking://user/alice/memories/style.md", "category": "preferences", "overview": "Prefers concise answers.", "score": 0.9}]} elif self.path.endswith("/messages/batch"): result = {"pending_tokens": 2} @@ -1144,6 +1155,7 @@ def test_shutdown_timeout_closes_resources_after_active_write_finishes( writer.join(2.0) assert not writer.is_alive() + assert manager._cleanup_done.wait(timeout=2.0) assert manager._recorder.closed is True assert manager._recorder.client.closed is True assert manager.shutdown_flush(1.0) is True @@ -1201,3 +1213,2250 @@ def test_capture_cursor_contains_no_message_content( assert "very private text" not in serialized assert state["submitted_prefix_count"] == 1 + + +def _multi_user_backend_config(tmp_path: Path, **overrides: Any) -> dict[str, Any]: + config: dict[str, Any] = { + "base_url": "http://openviking:1933", + "storage_path": str(tmp_path), + "startup_policy": "warn", + "retrieval": { + "top_k": 4, + "max_injection_chars": 1_000, + "injection_query": "profile preferences and prior decisions", + }, + } + config.update(overrides) + return config + + +def _track_official_integration(monkeypatch: pytest.MonkeyPatch) -> tuple[list[_Recorder], list[_Retriever]]: + import deerflow.agents.memory.backends.openviking.openviking_manager as module + + recorders: list[_Recorder] = [] + retrievers: list[_Retriever] = [] + + class _TrackedRecorder(_Recorder): + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + recorders.append(self) + + class _TrackedRetriever(_Retriever): + def __init__(self, *, client: _Client, **kwargs: Any) -> None: + super().__init__(client=client, **kwargs) + retrievers.append(self) + + monkeypatch.setattr( + module, + "_load_official_integration", + lambda: { + "OpenVikingCommitPolicy": _CommitPolicy, + "OpenVikingPartialWriteError": _PartialWriteError, + "OpenVikingRetriever": _TrackedRetriever, + "OpenVikingSessionRecorder": _TrackedRecorder, + "use_actor_peer": _use_actor_peer, + }, + ) + return recorders, retrievers + + +def test_multi_user_config_validation_pool_masking_and_side_effect_free( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("ALICE_OV_KEY", "alice-env-secret-123") + cfg = OpenVikingConfig.from_backend_config( + _multi_user_backend_config( + tmp_path, + user_credentials={ + "alice": {"api_key_env": "ALICE_OV_KEY", "tenant_id": "acme"}, + "bob": {"api_key": "bob-inline-secret-456"}, + }, + client_pool={"max_clients": 16, "idle_ttl_seconds": 120.5}, + ) + ) + assert cfg.isolation_mode == "multi_user" + assert cfg.owner_user_id is None + assert cfg.api_key_env is None + assert cfg.api_key == "" + assert cfg.pool_max_clients == 16 + assert cfg.pool_idle_ttl_seconds == 120.5 + assert cfg.user_credentials["alice"].api_key == "alice-env-secret-123" + assert cfg.user_credentials["alice"].api_key_env == "ALICE_OV_KEY" + assert cfg.user_credentials["alice"].tenant_id == "acme" + assert cfg.user_credentials["bob"].api_key == "bob-inline-secret-456" + assert cfg.user_credentials["bob"].tenant_id is None + for secret in ("alice-env-secret-123", "bob-inline-secret-456"): + assert secret not in repr(cfg) + assert "alice-env-secret-123" not in repr(cfg.user_credentials["alice"]) + + # Defaults and explicit null idle_ttl_seconds disabling TTL eviction + default_pool_cfg = OpenVikingConfig.from_backend_config(_multi_user_backend_config(tmp_path, user_credentials={"alice": {"api_key": "alice-key"}})) + assert default_pool_cfg.pool_max_clients == 64 + assert default_pool_cfg.pool_idle_ttl_seconds == 900.0 + + no_ttl_cfg = OpenVikingConfig.from_backend_config( + _multi_user_backend_config( + tmp_path, + user_credentials={"alice": {"api_key": "alice-key"}}, + client_pool={"idle_ttl_seconds": None}, + ) + ) + assert no_ttl_cfg.pool_idle_ttl_seconds is None + + # Side-effect-free validation: must never import credential_provider + nonexistent_pkg = "nonexistent_ov_provider_pkg_for_test" + monkeypatch.setattr( + importlib, + "import_module", + lambda name: (_ for _ in ()).throw(AssertionError(f"unexpected import: {name}")), + ) + provider_cfg = OpenVikingConfig.from_backend_config( + _multi_user_backend_config( + tmp_path, + credential_provider=f"{nonexistent_pkg}.mod:VaultProvider", + credential_provider_config={"endpoint": "https://vault.internal", "api_key": "vault-secret-999"}, + ) + ) + assert provider_cfg.isolation_mode == "multi_user" + assert provider_cfg.credential_provider == f"{nonexistent_pkg}.mod:VaultProvider" + assert "vault-secret-999" not in repr(provider_cfg) + assert nonexistent_pkg not in sys.modules + + # Also accepted with dot separator and injected provider hook + dot_cfg = OpenVikingConfig.from_backend_config(_multi_user_backend_config(tmp_path, credential_provider=f"{nonexistent_pkg}.mod.VaultProvider")) + assert dot_cfg.credential_provider == f"{nonexistent_pkg}.mod.VaultProvider" + injected_cfg = OpenVikingConfig.from_backend_config( + _multi_user_backend_config(tmp_path, client_pool={"max_clients": 8}), + has_injected_credential_provider=True, + ) + assert injected_cfg.isolation_mode == "multi_user" + assert injected_cfg.pool_max_clients == 8 + monkeypatch.setenv("OPENVIKING_API_KEY", "single-user-secret") + single_empty_pool_cfg = OpenVikingConfig.from_backend_config( + _backend_config(tmp_path, client_pool={}), + ) + assert single_empty_pool_cfg.isolation_mode == "single_user" + assert OpenVikingConfig.from_backend_config(_backend_config(tmp_path, client_pool=None)).isolation_mode == "single_user" + with pytest.raises(ValueError, match="credential_provider_config requires credential_provider"): + OpenVikingConfig.from_backend_config( + _multi_user_backend_config(tmp_path, credential_provider_config={"namespace": "prod"}), + has_injected_credential_provider=True, + ) + + # read_failures_are_fatal_for_config supports multi-user configs without importing provider + assert ( + OpenVikingMemoryManager.read_failures_are_fatal_for_config( + _multi_user_backend_config( + tmp_path, + credential_provider=f"{nonexistent_pkg}.mod:VaultProvider", + failure_policy={"read": "fail_open"}, + ) + ) + is False + ) + assert ( + OpenVikingMemoryManager.read_failures_are_fatal_for_config( + _multi_user_backend_config( + tmp_path, + credential_provider=f"{nonexistent_pkg}.mod:VaultProvider", + failure_policy={"read": "raise"}, + ) + ) + is True + ) + + +@pytest.mark.parametrize( + ("overrides", "match"), + [ + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "owner_user_id": "alice"}, "owner_user_id and api_key_env"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "api_key_env": "ALICE_KEY"}, "owner_user_id and api_key_env"), + ({"credential_provider": "pkg.mod:Provider", "owner_user_id": "alice"}, "owner_user_id and api_key_env"), + ({"credential_provider": "pkg.mod:Provider", "api_key_env": "ALICE_KEY"}, "owner_user_id and api_key_env"), + ({"user_credentials": {}}, "must not be empty"), + ({"user_credentials": "not-a-dict"}, "user_credentials must be a mapping"), + ({"user_credentials": {" alice": {"api_key": "a-key"}}}, "non-empty stripped"), + ({"user_credentials": {"alice\x00": {"api_key": "a-key"}}}, "control characters"), + ({"user_credentials": {"alice": "a-key"}}, r"user_credentials\.alice must be a mapping"), + ({"user_credentials": {"alice": {"api_key": "a-key", "api_key_env": "ALICE_KEY"}}}, "exactly one of"), + ({"user_credentials": {"alice": {"tenant_id": "acme"}}}, "exactly one of"), + ({"user_credentials": {"alice": {"api_key": "a-key", "unknown": 1}}}, r"user_credentials\.alice\.unknown"), + ({"user_credentials": {"alice": {"api_key_env": "MISSING_OV_KEY_TEST"}}}, "OpenViking USER API key is missing for user 'alice'; set MISSING_OV_KEY_TEST"), + ({"user_credentials": {"alice": {"api_key": "dup-secret"}, "bob": {"api_key": "dup-secret"}}}, "must not share the same API key"), + ({"user_credentials": {"alice": {"api_key": "bad key"}}}, "printable ASCII"), + ({"user_credentials": {"alice": {"api_key": "bad\r\nkey"}}}, "printable ASCII"), + ({"user_credentials": {"alice": {"api_key": "a-key", "tenant_id": ""}}}, r"user_credentials\.alice:.*tenant_id must not be empty"), + ({"user_credentials": {"alice": {"api_key": "a-key", "tenant_id": 123}}}, r"user_credentials\.alice:.*tenant_id must be a string"), + ({"user_credentials": {"alice": {"api_key": "a-key", "tenant_id": " acme"}}}, r"user_credentials\.alice:.*leading or trailing whitespace"), + ({"user_credentials": {"alice": {"api_key": "a-key", "tenant_id": "t" * 129}}}, r"user_credentials\.alice:.*at most 128"), + ({"user_credentials": {"alice": {"api_key": "a-key", "tenant_id": "ac\x00me"}}}, r"user_credentials\.alice:.*control characters"), + ({"credential_provider": ""}, "must not be empty"), + ({"credential_provider": "SingleName"}, "expected 'pkg.mod:Attr'"), + ({"credential_provider": "pkg:mod:Attr"}, "at most one ':'"), + ({"credential_provider": "pkg.class:Attr"}, "valid Python identifiers"), + ({"owner_user_id": "alice", "credential_provider_config": {"endpoint": "x"}}, "requires credential_provider"), + ({"owner_user_id": "alice", "client_pool": {"max_clients": 4}}, "client_pool is only supported in multi-user mode"), + ({"owner_user_id": "alice", "client_pool": {"idle_ttl_seconds": 30.0}}, "client_pool is only supported in multi-user mode"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "client_pool": {"max_clients": True}}, r"client_pool\.max_clients must be an integer"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "client_pool": {"max_clients": 1.5}}, r"client_pool\.max_clients must be an integer"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "client_pool": {"max_clients": 0}}, "between 1 and 4096"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "client_pool": {"max_clients": 4097}}, "between 1 and 4096"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "client_pool": {"idle_ttl_seconds": False}}, r"client_pool\.idle_ttl_seconds must be a number"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "client_pool": {"idle_ttl_seconds": 0}}, "finite value > 0 or null"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "client_pool": {"idle_ttl_seconds": -5}}, "finite value > 0 or null"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "client_pool": {"idle_ttl_seconds": float("inf")}}, "finite value > 0 or null"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "client_pool": {"idle_ttl_seconds": float("nan")}}, "finite value > 0 or null"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "client_pool": {"idle_ttl_seconds": ""}}, "number or null, got empty str"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "client_pool": {"extra_knob": 1}}, r"client_pool\.extra_knob"), + ({"user_credentials": {"alice": {"api_key": "a-key"}}, "auth_mode": "trusted"}, "trusted mode is no longer supported"), + ], +) +def test_multi_user_config_rejects_invalid_inputs_and_never_leaks_secrets( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + overrides: dict[str, Any], + match: str, +) -> None: + monkeypatch.setenv("ALICE_KEY", "secret-val") + monkeypatch.delenv("MISSING_OV_KEY_TEST", raising=False) + cfg = _multi_user_backend_config(tmp_path, **overrides) + if "owner_user_id" not in overrides and "user_credentials" not in overrides and "credential_provider" not in overrides: + cfg["owner_user_id"] = "alice" + if cfg.get("owner_user_id") == "alice" and "api_key_env" not in cfg and "user_credentials" not in cfg and "credential_provider" not in cfg: + cfg["api_key_env"] = "ALICE_KEY" + + with pytest.raises(ValueError, match=match) as exc_info: + OpenVikingConfig.from_backend_config(cfg) + + for forbidden in ("dup-secret", "bad key", "bad\r\nkey"): + assert forbidden not in str(exc_info.value) + + +@pytest.mark.parametrize( + ("section", "key", "value"), + [ + (None, "timeout_seconds", True), + (None, "max_seen_message_ids", False), + ("retrieval", "top_k", True), + ("retrieval", "max_injection_chars", False), + ("retrieval", "score_threshold", True), + ], +) +def test_existing_numeric_knobs_reject_booleans( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + section: str | None, + key: str, + value: bool, +) -> None: + monkeypatch.setenv("OPENVIKING_API_KEY", "user-key") + config = _backend_config(tmp_path) + target = config if section is None else config[section] + target[key] = value + + with pytest.raises(ValueError, match=f"OpenViking {key} must be a number"): + OpenVikingConfig.from_backend_config(config) + + +def test_session_id_tenant_isolation_and_v1_backward_compat() -> None: + v1_default = _session_id("alice", "research", "thread-1") + v1_explicit_none = _session_id("alice", "research", "thread-1", tenant_id=None) + expected_v1 = f"df_{hashlib.sha256(b'deerflow-openviking-adapter-v1\0alice\0research\0thread-1').hexdigest()[:48]}" + assert v1_default == v1_explicit_none == expected_v1 + + acme = _session_id("alice", "research", "thread-1", tenant_id="acme") + globex = _session_id("alice", "research", "thread-1", tenant_id="globex") + expected_acme = f"df_{hashlib.sha256(b'deerflow-openviking-adapter-v2\0acme\0alice\0research\0thread-1').hexdigest()[:48]}" + assert acme == expected_acme + assert len({v1_default, acme, globex}) == 3 + # Null-byte delimiter separation prevents boundary collisions + assert _session_id("bc", "research", "thread-1", tenant_id="a") != _session_id("c", "research", "thread-1", tenant_id="ab") + + +def test_multi_user_real_loopback_http_isolation_and_warm_health( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + isolated_cli_config: Path, + openviking_http_server: tuple[str, list[dict[str, Any]]], +) -> None: + monkeypatch.setenv("OPENVIKING_API_KEY", "ambient-key-must-never-leak") + monkeypatch.setenv("ALICE_ACME_KEY", "alice-acme-secret") + monkeypatch.setenv("BOB_GLOBEX_KEY", "bob-globex-secret") + isolated_cli_config.write_text( + json.dumps( + { + "url": "http://unused.invalid", + "api_key": "cli-key-must-never-leak", + "extra_headers": {"X-CLI-Only": "must-not-leak", "X-API-Key": "cli-header-key"}, + } + ), + encoding="utf-8", + ) + + base_url, requests = openviking_http_server + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + base_url=base_url, + timeout_seconds=2, + startup_policy="fail_fast", + failure_policy={"read": "raise"}, + user_credentials={ + "alice": {"api_key_env": "ALICE_ACME_KEY", "tenant_id": "acme"}, + "bob": {"api_key_env": "BOB_GLOBEX_KEY", "tenant_id": "globex"}, + }, + ) + ) + try: + assert manager.warm() is True + assert len(requests) == 1 + assert requests[0]["path"] == "/health" + assert "x-api-key" not in requests[0]["headers"] + assert "x-cli-only" not in requests[0]["headers"] + assert "authorization" not in requests[0]["headers"] + + shared_thread = "shared-thread-1" + alice_msgs = [HumanMessage("Alice prefers dark mode", id="ah1"), AIMessage("Noted", id="aa1")] + bob_msgs = [HumanMessage("Bob prefers light mode", id="bh1"), AIMessage("Noted", id="ba1")] + + manager.add(shared_thread, alice_msgs, user_id="alice") + manager.add(shared_thread, bob_msgs, user_id="bob") + + alice_ctx = manager.get_context("alice", thread_id=shared_thread) + bob_ctx = manager.get_context("bob", thread_id=shared_thread) + assert "Prefers concise answers." in alice_ctx + assert "Prefers concise answers." in bob_ctx + + alice_facts = manager.search("theme", top_k=2, user_id="alice") + bob_facts = manager.search("theme", top_k=2, user_id="bob") + assert len(alice_facts) == 1 and len(bob_facts) == 1 + + alice_sid = _session_id("alice", "deerflow", shared_thread, tenant_id="acme") + bob_sid = _session_id("bob", "deerflow", shared_thread, tenant_id="globex") + assert alice_sid != bob_sid + + alice_reqs = [r for r in requests[1:] if r["headers"].get("x-api-key") == "alice-acme-secret"] + bob_reqs = [r for r in requests[1:] if r["headers"].get("x-api-key") == "bob-globex-secret"] + assert len(alice_reqs) == 4 # batch, commit, search/search, search/find + assert len(bob_reqs) == 4 + assert len(requests) == 1 + 4 + 4 + + assert alice_reqs[0]["path"] == f"/api/v1/sessions/{alice_sid}/messages/batch" + assert alice_reqs[1]["path"] == f"/api/v1/sessions/{alice_sid}/commit" + assert alice_reqs[2]["path"] == "/api/v1/search/search" + assert alice_reqs[2]["payload"]["session_id"] == alice_sid + assert alice_reqs[3]["path"] == "/api/v1/search/find" + + assert bob_reqs[0]["path"] == f"/api/v1/sessions/{bob_sid}/messages/batch" + assert bob_reqs[1]["path"] == f"/api/v1/sessions/{bob_sid}/commit" + assert bob_reqs[2]["path"] == "/api/v1/search/search" + assert bob_reqs[2]["payload"]["session_id"] == bob_sid + assert bob_reqs[3]["path"] == "/api/v1/search/find" + + for req in requests: + headers_str = json.dumps(req["headers"]) + for forbidden in ("ambient-key-must-never-leak", "cli-key-must-never-leak", "cli-header-key", "x-cli-only"): + assert forbidden not in headers_str + + # Isolated capture cursors: repeating alice does not re-send or affect bob + before = len(requests) + manager.add(shared_thread, alice_msgs, user_id="alice") + assert len(requests) == before + assert manager._state_path(alice_sid).exists() + assert manager._state_path(bob_sid).exists() + finally: + manager.close() + + +def test_multi_user_warm_honors_startup_policy( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + unreachable_openviking_url: str, +) -> None: + for name in ("NO_PROXY", "no_proxy"): + monkeypatch.setenv(name, "127.0.0.1,localhost,::1") + + state = {"status_code": 503, "body": {"status": "degraded"}} + + class _HealthHandler(BaseHTTPRequestHandler): + def do_GET(self) -> None: + encoded = json.dumps(state["body"]).encode("utf-8") + self.send_response(state["status_code"]) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + def log_message(self, format: str, *args: Any) -> None: + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), _HealthHandler) + thread = threading.Thread(target=lambda: server.serve_forever(poll_interval=0.01), daemon=True) + thread.start() + try: + health_url = f"http://127.0.0.1:{server.server_port}" + for bad_state in ( + {"status_code": 503, "body": {"status": "ok"}}, + {"status_code": 200, "body": {"status": "degraded"}}, + ): + state.update(bad_state) + strict_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + base_url=health_url, + startup_policy="fail_fast", + user_credentials={"alice": {"api_key": "alice-key"}}, + ) + ) + warn_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + base_url=health_url, + startup_policy="warn", + user_credentials={"alice": {"api_key": "alice-key"}}, + ) + ) + try: + with pytest.raises(MemoryManagerError, match="unhealthy"): + strict_mgr.warm() + assert warn_mgr.warm() is False + finally: + strict_mgr.close() + warn_mgr.close() + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + assert not thread.is_alive() + + unreachable_strict = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + base_url=unreachable_openviking_url, + timeout_seconds=0.1, + startup_policy="fail_fast", + user_credentials={"alice": {"api_key": "alice-key"}}, + ) + ) + unreachable_warn = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + base_url=unreachable_openviking_url, + timeout_seconds=0.1, + startup_policy="warn", + user_credentials={"alice": {"api_key": "alice-key"}}, + ) + ) + try: + with pytest.raises(MemoryManagerError, match="startup validation failed"): + unreachable_strict.warm() + assert unreachable_warn.warm() is False + finally: + unreachable_strict.close() + unreachable_warn.close() + + +@pytest.mark.parametrize("write_policy", ["log_and_drop", "raise"]) +@pytest.mark.parametrize("read_policy", ["fail_open", "raise"]) +@pytest.mark.parametrize("bad_user", [None, "", " ", "unmapped-user"]) +def test_multi_user_fail_closed_for_missing_blank_and_unmapped_user( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + write_policy: str, + read_policy: str, + bad_user: str | None, +) -> None: + recorders, retrievers = _track_official_integration(monkeypatch) + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + failure_policy={"read": read_policy, "write": write_policy}, + user_credentials={"alice": {"api_key": "alice-secret"}}, + ) + ) + try: + with caplog.at_level(logging.ERROR, logger=OpenVikingMemoryManager.__module__): + if write_policy == "raise": + with pytest.raises(MemoryManagerError): + manager.add("thread-1", [HumanMessage("secret", id="h1")], user_id=bad_user) + else: + assert manager.add("thread-1", [HumanMessage("secret", id="h1")], user_id=bad_user) is None + assert any("Dropping the memory write" in record.getMessage() for record in caplog.records) + assert "secret" not in caplog.text + + expected_read_exc = MemoryReadError if read_policy == "raise" else MemoryManagerError + with pytest.raises(expected_read_exc) as ctx_exc: + manager.get_context(bad_user, thread_id="thread-1") + with pytest.raises(expected_read_exc) as search_exc: + manager.search("prefs", user_id=bad_user) + + if read_policy == "raise": + assert isinstance(ctx_exc.value.__cause__, MemoryManagerError) + assert isinstance(search_exc.value.__cause__, MemoryManagerError) + assert recorders == [] + assert retrievers == [] + assert not list((tmp_path / "openviking").rglob("*.json")) + finally: + manager.close() + + +@pytest.mark.parametrize( + "bad_return", + [ + None, + 12345, + ["super-secret-list"], + {"tenant_id": "acme"}, + {"api_key": "super-secret-extra", "extra_field": "super-secret-field"}, + {123: "super-secret-non-str-key"}, + {"api_key": "super-secret-bad-tenant", "tenant_id": 999}, + "super-secret-crlf\r\nX-Injected: evil", + "super-secret with space", + {"api_key": "super-secret\nnewline"}, + ], +) +def test_multi_user_fail_closed_on_malformed_or_illegal_provider_output( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + bad_return: Any, +) -> None: + recorders, retrievers = _track_official_integration(monkeypatch) + calls: list[str] = [] + + def bad_provider(user_id: str) -> Any: + calls.append(user_id) + return bad_return + + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path, failure_policy={"read": "raise", "write": "raise"}), + credential_provider=bad_provider, + ) + try: + with pytest.raises(MemoryManagerError) as add_exc: + manager.add("thread-1", [HumanMessage("hi", id="h1")], user_id="mallory") + with pytest.raises(MemoryReadError) as read_exc: + manager.get_context("mallory") + + assert len(calls) == 2 + for exc in (add_exc.value, read_exc.value): + assert "super-secret" not in str(exc) + assert "evil" not in str(exc) + assert recorders == [] + assert retrievers == [] + finally: + manager.close() + + +def test_multi_user_fail_closed_when_provider_raises_never_leaks_secret( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + recorders, _ = _track_official_integration(monkeypatch) + invoked = False + + def failing_provider(user_id: str) -> Any: + nonlocal invoked + invoked = True + raise RuntimeError(f"vault failure for {user_id}: sk-vault-secret-999") + + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path, failure_policy={"read": "raise", "write": "raise"}), + credential_provider=failing_provider, + ) + drop_manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path / "drop", failure_policy={"read": "raise", "write": "log_and_drop"}), + credential_provider=failing_provider, + ) + try: + with pytest.raises(MemoryManagerError, match="RuntimeError") as add_exc: + manager.add("thread-1", [HumanMessage("hi", id="h1")], user_id="alice") + assert invoked is True + assert "sk-vault-secret-999" not in str(add_exc.value) + assert add_exc.value.__cause__ is None + + with caplog.at_level(logging.ERROR, logger=OpenVikingMemoryManager.__module__): + assert drop_manager.add("thread-1", [HumanMessage("top-secret-msg", id="h1")], user_id="alice") is None + assert "sk-vault-secret-999" not in caplog.text + assert "top-secret-msg" not in caplog.text + assert any("RuntimeError" in record.getMessage() and "Dropping the memory write" in record.getMessage() for record in caplog.records) + + with pytest.raises(MemoryReadError, match="RuntimeError") as read_exc: + manager.search("prefs", user_id="alice") + assert "sk-vault-secret-999" not in str(read_exc.value) + assert recorders == [] + finally: + manager.close() + drop_manager.close() + + +def test_provider_memory_read_error_respects_configured_read_policy( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from deerflow.agents import memory as memory_pkg + from deerflow.agents.lead_agent.prompt import _get_memory_context + from deerflow.config.app_config import AppConfig + from deerflow.config.memory_config import MemoryConfig + from deerflow.config.sandbox_config import SandboxConfig + + recorders, retrievers = _track_official_integration(monkeypatch) + + def failing_provider(user_id: str) -> Any: + raise MemoryReadError(f"vault outage for {user_id}: sk-vault-secret-999") + + fail_open_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path / "open", failure_policy={"read": "fail_open"}), + credential_provider=failing_provider, + ) + raise_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path / "raise", failure_policy={"read": "raise"}), + credential_provider=failing_provider, + ) + try: + with pytest.raises(MemoryManagerError, match="MemoryReadError") as ctx_exc: + fail_open_mgr.get_context("alice") + assert type(ctx_exc.value) is MemoryManagerError + assert ctx_exc.value.__cause__ is None + assert "sk-vault-secret-999" not in str(ctx_exc.value) + + with pytest.raises(MemoryManagerError, match="MemoryReadError") as search_exc: + fail_open_mgr.search("prefs", user_id="alice") + assert type(search_exc.value) is MemoryManagerError + assert search_exc.value.__cause__ is None + assert "sk-vault-secret-999" not in str(search_exc.value) + + fail_open_app_cfg = AppConfig( + sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider"), + memory=MemoryConfig( + enabled=True, + injection_enabled=True, + manager_class="openviking", + backend_config=fail_open_mgr.backend_config, + ), + ) + monkeypatch.setattr(memory_pkg, "get_memory_manager", lambda: fail_open_mgr) + assert _get_memory_context(app_config=fail_open_app_cfg, user_id="alice") == "" + + with pytest.raises(MemoryReadError) as strict_exc: + raise_mgr.get_context("alice") + assert isinstance(strict_exc.value.__cause__, MemoryManagerError) + assert "sk-vault-secret-999" not in str(strict_exc.value) + assert "sk-vault-secret-999" not in str(strict_exc.value.__cause__) + + strict_app_cfg = AppConfig( + sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider"), + memory=MemoryConfig( + enabled=True, + injection_enabled=True, + manager_class="openviking", + backend_config=raise_mgr.backend_config, + ), + ) + monkeypatch.setattr(memory_pkg, "get_memory_manager", lambda: raise_mgr) + with pytest.raises(MemoryReadError): + _get_memory_context(app_config=strict_app_cfg, user_id="alice") + + assert recorders == [] + assert retrievers == [] + finally: + fail_open_mgr.close() + raise_mgr.close() + + +def test_dynamic_credential_provider_class_callable_and_hook_paths( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorders, _ = _track_official_integration(monkeypatch) + pkg_dir = tmp_path / "dyn_ov_providers" + pkg_dir.mkdir() + (pkg_dir / "__init__.py").write_text("", encoding="utf-8") + (pkg_dir / "mod.py").write_text( + "class DictProvider:\n" + " def __init__(self, prefix: str, tenant: str | None = None) -> None:\n" + " self.prefix = prefix\n" + " self.tenant = tenant\n" + " self.closed = False\n" + " def resolve(self, user_id: str):\n" + " return {'api_key': f'{self.prefix}-{user_id}', 'tenant_id': self.tenant}\n" + " def close(self) -> None:\n" + " self.closed = True\n" + "\n" + "def fn_provider(user_id: str):\n" + " return f'fn-key-{user_id}'\n" + "\n" + "def factory_provider(suffix: str):\n" + " return lambda user_id: {'api_key': f'{user_id}-{suffix}'}\n" + "\n" + "NOT_CALLABLE = 42\n" + "\n" + "class BadProvider:\n" + " pass\n" + "\n" + "def bad_factory(flag: bool):\n" + " return 123\n", + encoding="utf-8", + ) + monkeypatch.syspath_prepend(str(tmp_path)) + importlib.invalidate_caches() + + try: + validate_provider_path("dyn_ov_providers.mod:DictProvider") + with pytest.raises(ValueError, match="must resolve to a class or callable"): + load_credential_provider("dyn_ov_providers.mod:NOT_CALLABLE", {}) + with pytest.raises(ValueError, match="must define a callable 'resolve"): + load_credential_provider("dyn_ov_providers.mod:BadProvider", {}) + with pytest.raises(ValueError, match="factory"): + load_credential_provider("dyn_ov_providers.mod:bad_factory", {"flag": True}) + cred = normalize_resolved_credential({"api_key": "norm-key", "tenant_id": "acme"}, user_id="alice") + assert cred is not None and cred.api_key == "norm-key" and cred.tenant_id == "acme" + assert normalize_resolved_credential(cred, user_id="alice") is cred + # 1. Class path with credential_provider_config + cls_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + credential_provider="dyn_ov_providers.mod:DictProvider", + credential_provider_config={"prefix": "cls", "tenant": "acme"}, + ) + ) + try: + assert isinstance(cls_mgr._credential_provider, OpenVikingCredentialProvider) + cls_mgr.add("t1", [HumanMessage("hi", id="h1")], user_id="alice") + assert recorders[-1].connection["api_key"] == "cls-alice" + assert cls_mgr._state_path(_session_id("alice", "deerflow", "t1", tenant_id="acme")).exists() + finally: + assert cls_mgr.shutdown_flush(2.0) is True + assert cls_mgr._credential_provider.closed is True + + # 2. Direct callable path (no config) + fn_mgr = OpenVikingMemoryManager.from_config(_multi_user_backend_config(tmp_path, credential_provider="dyn_ov_providers.mod.fn_provider")) + try: + fn_mgr.search("prefs", user_id="bob") + assert recorders[-1].connection["api_key"] == "fn-key-bob" + finally: + fn_mgr.close() + + # 3. Factory callable path (with config) + fac_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + credential_provider="dyn_ov_providers.mod:factory_provider", + credential_provider_config={"suffix": "v2"}, + ) + ) + try: + fac_mgr.get_context("carol") + assert recorders[-1].connection["api_key"] == "carol-v2" + finally: + fac_mgr.close() + + # 4. Injected host_hooks["credential_provider"] + hook_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path), + credential_provider=lambda uid: OpenVikingCredential(api_key=f"hook-{uid}", tenant_id="t-hook"), + ) + strict_hook_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path, failure_policy={"read": "raise"}), + credential_provider=lambda uid: OpenVikingCredential(api_key=f"hook-{uid}", tenant_id="t-hook"), + ) + try: + assert hook_mgr.read_failures_are_fatal is False + assert strict_hook_mgr.read_failures_are_fatal is True + hook_mgr.add("t2", [HumanMessage("hi", id="h1")], user_id="dave") + assert recorders[-1].connection["api_key"] == "hook-dave" + assert hook_mgr._state_path(_session_id("dave", "deerflow", "t2", tenant_id="t-hook")).exists() + finally: + hook_mgr.close() + strict_hook_mgr.close() + + # Cannot specify both config credential_provider and injected hook + with pytest.raises(ValueError, match="cannot configure both"): + OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path, credential_provider="dyn_ov_providers.mod:fn_provider"), + credential_provider=lambda uid: "x", + ) + with pytest.raises(ValueError, match="injected credential_provider"): + OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path), + credential_provider="not-callable", + ) + finally: + for mod_name in list(sys.modules): + if mod_name == "dyn_ov_providers" or mod_name.startswith("dyn_ov_providers."): + monkeypatch.delitem(sys.modules, mod_name, raising=False) + + +def test_dynamic_provider_key_rotation_revocation_and_cross_identity_rejection( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorders, _ = _track_official_integration(monkeypatch) + keys: dict[str, str | None] = {"alice": "alice-v1", "bob": "bob-v1"} + + class _DynamicProvider: + def resolve(self, user_id: str) -> str | None: + return keys.get(user_id) + + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path, failure_policy={"read": "raise", "write": "raise"}), + credential_provider=_DynamicProvider(), + ) + try: + # Initial acquisition + manager.add("t1", [HumanMessage("m1", id="m1")], user_id="alice") + assert len(recorders) == 1 + rec_v1 = recorders[0] + assert rec_v1.connection["api_key"] == "alice-v1" + assert rec_v1.closed is False + + # Idle key rotation: creates new recorder and immediately closes old idle one + keys["alice"] = "alice-v2" + manager.add("t1", [HumanMessage("m1", id="m1"), HumanMessage("m2", id="m2")], user_id="alice") + assert len(recorders) == 2 + rec_v2 = recorders[1] + assert rec_v2.connection["api_key"] == "alice-v2" + assert rec_v1.closed is True + assert rec_v2.closed is False + + # In-flight key rotation: old recorder stays open until in-flight op finishes + started = threading.Event() + release = threading.Event() + orig_record = rec_v2.record + + def blocked_record(*args: Any, **kwargs: Any) -> object: + started.set() + assert release.wait(5.0) + return orig_record(*args, **kwargs) + + rec_v2.record = blocked_record + t_inflight = threading.Thread( + target=manager.add, + args=("t-inflight", [HumanMessage("slow", id="s1")]), + kwargs={"user_id": "alice"}, + ) + t_inflight.start() + assert started.wait(5.0) + + keys["alice"] = "alice-v3" + manager.search("prefs", user_id="alice") + assert len(recorders) == 3 + rec_v3 = recorders[2] + assert rec_v3.connection["api_key"] == "alice-v3" + assert rec_v2.closed is False + + release.set() + t_inflight.join(5.0) + assert not t_inflight.is_alive() + assert rec_v2.closed is True + assert rec_v3.closed is False + + # Cross-identity key-reuse rejection in runtime pool + keys["bob"] = "alice-v3" + with pytest.raises(MemoryManagerError, match="cannot be shared across distinct DeerFlow scopes"): + manager.add("t1", [HumanMessage("leak", id="l1")], user_id="bob") + with pytest.raises(MemoryReadError, match="cannot be shared across distinct DeerFlow scopes"): + manager.get_context("bob") + assert len(recorders) == 3 + assert rec_v3.closed is False + + # Revocation retires cached handle immediately and refuses next call + keys["alice"] = None + with pytest.raises(MemoryManagerError, match="No OpenViking USER API key"): + manager.add("t1", [HumanMessage("after revoke", id="r1")], user_id="alice") + assert rec_v3.closed is True + + # Re-granting later creates a fresh recorder instead of reusing retired one + keys["alice"] = "alice-v3" + manager.search("prefs", user_id="alice") + assert len(recorders) == 4 + assert recorders[3] is not rec_v3 + assert recorders[3].closed is False + finally: + manager.close() + + +def test_client_pool_lru_eviction_and_inflight_refcount_safety( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorders, _ = _track_official_integration(monkeypatch) + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + client_pool={"max_clients": 2}, + user_credentials={ + "alice": {"api_key": "k-alice"}, + "bob": {"api_key": "k-bob"}, + "carol": {"api_key": "k-carol"}, + }, + ) + ) + try: + manager.search("q", user_id="alice") + manager.search("q", user_id="bob") + # Refresh alice so bob becomes LRU + manager.search("q", user_id="alice") + rec_alice, rec_bob = recorders + assert rec_alice.closed is False + assert rec_bob.closed is False + + # Adding carol evicts idle LRU bob + manager.search("q", user_id="carol") + assert len(recorders) == 3 + rec_carol = recorders[2] + assert rec_bob.closed is True + assert rec_alice.closed is False + assert rec_carol.closed is False + + # Now alice is LRU and carol is MRU. Park alice in-flight: idle carol should be evicted first + started_a = threading.Event() + release_a = threading.Event() + orig_a_record = rec_alice.record + + def slow_a(*args: Any, **kwargs: Any) -> object: + started_a.set() + assert release_a.wait(5.0) + return orig_a_record(*args, **kwargs) + + rec_alice.record = slow_a + t_a = threading.Thread(target=manager.add, args=("t1", [HumanMessage("a", id="a1")]), kwargs={"user_id": "alice"}) + t_a.start() + assert started_a.wait(5.0) + + manager.search("q", user_id="bob") + rec_bob_2 = recorders[3] + assert rec_carol.closed is True + assert rec_alice.closed is False + assert rec_bob_2.closed is False + + # Now bob_2 is busy too; carol enters when BOTH pooled entries are busy -> alice (oldest) evicted from pool, close deferred + started_b = threading.Event() + release_b = threading.Event() + orig_b_record = rec_bob_2.record + + def slow_b(*args: Any, **kwargs: Any) -> object: + started_b.set() + assert release_b.wait(5.0) + return orig_b_record(*args, **kwargs) + + rec_bob_2.record = slow_b + t_b = threading.Thread(target=manager.add, args=("t2", [HumanMessage("b", id="b1")]), kwargs={"user_id": "bob"}) + t_b.start() + assert started_b.wait(5.0) + + manager.search("q", user_id="carol") + assert len(recorders) == 5 + # Deferred close: alice was evicted while active_ops == 1, so it MUST still be open + assert rec_alice.closed is False + + release_a.set() + release_b.set() + t_a.join(5.0) + t_b.join(5.0) + assert not t_a.is_alive() and not t_b.is_alive() + assert rec_alice.closed is True + assert rec_bob_2.closed is False + finally: + manager.close() + + +def test_client_pool_idle_ttl_eviction_and_null_ttl_disabled( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorders, _ = _track_official_integration(monkeypatch) + now = [100.0] + + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + client_pool={"max_clients": 4, "idle_ttl_seconds": 30.0}, + user_credentials={ + "alice": {"api_key": "k-alice"}, + "bob": {"api_key": "k-bob"}, + }, + ) + ) + manager._clock = lambda: now[0] + try: + manager.search("q", user_id="alice") + now[0] = 120.0 + manager.search("q", user_id="bob") + rec_alice, rec_bob = recorders + + # At t=130.0: alice idle 30.0s (>= 30.0 -> evicted), bob idle 10.0s (< 30.0 -> retained) + now[0] = 130.0 + manager.search("q", user_id="bob") + assert rec_alice.closed is True + assert rec_bob.closed is False + assert len(recorders) == 2 + + # Re-acquiring alice builds a fresh recorder + manager.search("q", user_id="alice") + assert len(recorders) == 3 + assert recorders[2].closed is False + finally: + manager.close() + + # Explicit null disables TTL eviction completely + recorders2, _ = _track_official_integration(monkeypatch) + now2 = [0.0] + no_ttl_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path / "no-ttl", + client_pool={"idle_ttl_seconds": None}, + user_credentials={ + "alice": {"api_key": "k-alice"}, + "bob": {"api_key": "k-bob"}, + }, + ) + ) + no_ttl_mgr._clock = lambda: now2[0] + try: + no_ttl_mgr.search("q", user_id="alice") + now2[0] = 100_000.0 + no_ttl_mgr.search("q", user_id="bob") + no_ttl_mgr.search("q", user_id="alice") + assert len(recorders2) == 2 + assert all(not r.closed for r in recorders2) + finally: + no_ttl_mgr.close() + + +def test_client_pool_concurrent_stress_and_shutdown_flush( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorders, _ = _track_official_integration(monkeypatch) + provider_closed = False + + class _StressProvider: + def resolve(self, user_id: str) -> dict[str, Any]: + return {"api_key": f"stress-key-{user_id}", "tenant_id": f"tenant-{user_id}"} + + def close(self) -> None: + nonlocal provider_closed + provider_closed = True + + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path, client_pool={"max_clients": 2}), + credential_provider=_StressProvider(), + ) + + users = ["alice", "bob", "carol", "dave"] + barrier = threading.Barrier(len(users)) + errors: list[BaseException] = [] + + def worker(uid: str) -> None: + try: + barrier.wait(5.0) + for idx in range(5): + manager.add(f"thread-{idx}", [HumanMessage(f"{uid}-{idx}", id=f"{uid}-{idx}")], user_id=uid) + ctx = manager.get_context(uid, thread_id=f"thread-{idx}") + facts = manager.search("prefs", user_id=uid) + assert "Prefers concise answers." in ctx + assert len(facts) == 1 + except BaseException as exc: + errors.append(exc) + + threads = [threading.Thread(target=worker, args=(uid,)) for uid in users] + try: + for t in threads: + t.start() + for t in threads: + t.join(10.0) + assert not t.is_alive() + assert errors == [] + assert recorders + + for rec in recorders: + expected_key = rec.connection["api_key"] + uid = expected_key.removeprefix("stress-key-") + for sid, _, _, _ in rec.calls: + assert sid.startswith("df_") + assert any(sid == _session_id(uid, "deerflow", f"thread-{idx}", tenant_id=f"tenant-{uid}") for idx in range(5)) + finally: + assert manager.shutdown_flush(5.0) is True + + assert provider_closed is True + assert all(rec.closed and rec.client.closed for rec in recorders) + assert len(manager._pool) == 0 + assert manager.shutdown_flush(1.0) is True + + +def test_multi_user_shutdown_flush_drains_inflight_and_closes_provider( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorders, _ = _track_official_integration(monkeypatch) + close_calls = 0 + + class _ClosableProvider: + def resolve(self, user_id: str) -> str: + return f"key-{user_id}" + + def close(self) -> None: + nonlocal close_calls + close_calls += 1 + raise RuntimeError("best-effort close") + + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path), + credential_provider=_ClosableProvider(), + ) + manager.search("warmup", user_id="bob") + manager.search("warmup", user_id="alice") + rec_bob, rec_alice = recorders + + started = threading.Event() + release = threading.Event() + orig_record = rec_alice.record + + def blocking_record(*args: Any, **kwargs: Any) -> object: + started.set() + assert release.wait(5.0) + return orig_record(*args, **kwargs) + + rec_alice.record = blocking_record + writer = threading.Thread( + target=manager.add, + args=("thread-1", [HumanMessage("hello", id="h1")]), + kwargs={"user_id": "alice"}, + ) + writer.start() + try: + assert started.wait(5.0) + assert manager.shutdown_flush(0.0) is False + assert rec_alice.closed is False + assert rec_bob.closed is False + assert close_calls == 0 + finally: + release.set() + writer.join(5.0) + + assert not writer.is_alive() + assert manager._cleanup_done.wait(timeout=2.0) + assert rec_alice.closed is True + assert rec_bob.closed is True + assert close_calls == 1 + assert manager.shutdown_flush(1.0) is True + assert close_calls == 1 + + +def test_shutdown_flush_drains_admitted_write_pending_credential_resolution( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorders, _ = _track_official_integration(monkeypatch) + resolve_started = threading.Event() + release_resolve = threading.Event() + provider_calls: list[str] = [] + close_calls = 0 + + class _BlockingProvider: + def resolve(self, user_id: str) -> str: + provider_calls.append(user_id) + if user_id == "alice": + resolve_started.set() + assert release_resolve.wait(timeout=5.0) + return f"key-{user_id}" + + def close(self) -> None: + nonlocal close_calls + close_calls += 1 + + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path), + credential_provider=_BlockingProvider(), + ) + + write_errors: list[BaseException] = [] + flush_results: list[bool] = [] + + def _write_alice() -> None: + try: + manager.add( + "thread-1", + [HumanMessage("admitted before shutdown", id="h1")], + user_id="alice", + ) + except BaseException as exc: # pragma: no cover - diagnostic capture + write_errors.append(exc) + + def _run_shutdown() -> None: + flush_results.append(manager.shutdown_flush(5.0)) + + writer = threading.Thread(target=_write_alice) + writer.start() + shutdown_thread = threading.Thread(target=_run_shutdown) + try: + assert resolve_started.wait(timeout=5.0) + shutdown_thread.start() + + deadline = time.monotonic() + 5.0 + while not manager._closed and time.monotonic() < deadline: + time.sleep(0.01) + assert manager._closed is True + + manager.add( + "thread-2", + [HumanMessage("late", id="h2")], + user_id="bob", + ) + assert provider_calls == ["alice"] + finally: + release_resolve.set() + if writer.is_alive(): + writer.join(timeout=5.0) + if shutdown_thread.is_alive(): + shutdown_thread.join(timeout=5.0) + + assert not writer.is_alive() + assert not shutdown_thread.is_alive() + assert write_errors == [] + assert flush_results == [True] + assert provider_calls == ["alice"] + assert len(recorders) == 1 + assert len(recorders[0].calls) == 1 + assert recorders[0].closed is True + assert len(manager._pool) == 0 + assert close_calls == 1 + cursor_path = manager._state_path(_session_id("alice", "deerflow", "thread-1")) + assert cursor_path.exists() + assert not manager._state_path(_session_id("bob", "deerflow", "thread-2")).exists() + + +def test_shutdown_flush_bounds_provider_cleanup_within_timeout_and_closes_once( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + _track_official_integration(monkeypatch) + close_started = threading.Event() + release_close = threading.Event() + close_calls = 0 + + class _SlowClosableProvider: + def resolve(self, user_id: str) -> str: + return f"key-{user_id}" + + def close(self) -> None: + nonlocal close_calls + close_calls += 1 + close_started.set() + assert release_close.wait(timeout=5.0) + + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path, timeout_seconds=2.0), + credential_provider=_SlowClosableProvider(), + ) + + try: + t0 = time.monotonic() + assert manager.shutdown_flush(0.05) is False + flush_elapsed = time.monotonic() - t0 + assert flush_elapsed < 1.0 + assert close_started.wait(timeout=1.0) + assert not release_close.is_set() + + t1 = time.monotonic() + manager.close() + close_elapsed = time.monotonic() - t1 + assert close_elapsed < 0.5 + assert close_calls == 1 + finally: + release_close.set() + + assert manager.shutdown_flush(1.0) is True + assert close_calls == 1 + + +def test_credential_provider_close_failure_logs_only_exception_class( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + _track_official_integration(monkeypatch) + + class _BrokenCloseProvider: + def resolve(self, user_id: str) -> str: + return f"key-{user_id}" + + def close(self) -> None: + raise RuntimeError("postgres://svc:super-secret-dsn@vault.internal:5432/keys") + + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path), + credential_provider=_BrokenCloseProvider(), + ) + + with caplog.at_level(logging.WARNING, logger=OpenVikingMemoryManager.__module__): + assert manager.shutdown_flush(1.0) is True + + warnings = [r for r in caplog.records if "Failed to close OpenViking credential provider" in r.getMessage()] + assert len(warnings) == 1 + assert warnings[0].getMessage() == "Failed to close OpenViking credential provider (RuntimeError)" + assert warnings[0].exc_info is None + assert "super-secret-dsn" not in caplog.text + assert "vault.internal" not in caplog.text + + +def test_multi_user_lazy_client_init_error_honors_failure_policies_and_sanitizes( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + import deerflow.agents.memory.backends.openviking.openviking_manager as module + from deerflow.agents import memory as memory_pkg + from deerflow.agents.lead_agent.prompt import _get_memory_context + from deerflow.config.app_config import AppConfig + from deerflow.config.memory_config import MemoryConfig + from deerflow.config.sandbox_config import SandboxConfig + + class _ExplodingRecorder: + def __init__(self, *, url: str, api_key: str, **kwargs: Any) -> None: + del url, kwargs + raise RuntimeError(f"handshake failed: {api_key}") + + def _loader() -> dict[str, Any]: + return { + "OpenVikingCommitPolicy": _CommitPolicy, + "OpenVikingPartialWriteError": _PartialWriteError, + "OpenVikingRetriever": _Retriever, + "OpenVikingSessionRecorder": _ExplodingRecorder, + "use_actor_peer": _use_actor_peer, + } + + monkeypatch.setattr(module, "_load_official_integration", _loader) + + drop_open_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path / "open", + user_credentials={"alice": {"api_key": "ov-alice-super-secret"}}, + failure_policy={"read": "fail_open", "write": "log_and_drop"}, + ) + ) + raise_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path / "raise", + user_credentials={"alice": {"api_key": "ov-alice-super-secret"}}, + failure_policy={"read": "raise", "write": "raise"}, + ) + ) + try: + with caplog.at_level(logging.ERROR, logger=OpenVikingMemoryManager.__module__): + assert drop_open_mgr.add("thread-1", [HumanMessage("msg", id="h1")], user_id="alice") is None + assert any("Failed to initialize OpenViking client for DeerFlow user 'alice' (RuntimeError)" in r.getMessage() and "Dropping the memory write" in r.getMessage() for r in caplog.records) + assert "ov-alice-super-secret" not in caplog.text + + open_app_cfg = AppConfig( + sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider"), + memory=MemoryConfig( + enabled=True, + injection_enabled=True, + manager_class="openviking", + backend_config=drop_open_mgr.backend_config, + ), + ) + monkeypatch.setattr(memory_pkg, "get_memory_manager", lambda: drop_open_mgr) + assert _get_memory_context(app_config=open_app_cfg, user_id="alice") == "" + + with pytest.raises(MemoryReadError, match="RuntimeError") as read_exc: + raise_mgr.get_context("alice") + assert "ov-alice-super-secret" not in str(read_exc.value) + assert read_exc.value.__cause__ is not None + assert "ov-alice-super-secret" not in str(read_exc.value.__cause__) + + with pytest.raises(MemoryManagerError, match="RuntimeError") as write_exc: + raise_mgr.add("thread-1", [HumanMessage("msg", id="h1")], user_id="alice") + assert "ov-alice-super-secret" not in str(write_exc.value) + finally: + drop_open_mgr.close() + raise_mgr.close() + + +def test_gateway_memory_config_response_masks_multi_user_secrets() -> None: + from app.gateway.routers.memory import MemoryConfigResponse + + parsed = MemoryConfigResponse( + enabled=True, + mode="middleware", + injection_enabled=True, + shutdown_flush_timeout_seconds=30.0, + manager_class="openviking", + backend_config={ + "base_url": "http://127.0.0.1:1933", + "user_credentials": { + "alice": {"api_key": "alice-plaintext-secret", "tenant_id": "acme"}, + "bob": {"api_key_env": "BOB_OV_KEY"}, + }, + "credential_provider": "myapp.creds:VaultProvider", + "credential_provider_config": { + "endpoint": "https://vault.internal", + "namespace": "prod", + "timeout_seconds": 5, + "api_key": "vault-api-secret", + "client_secret": "vault-client-secret", + "token": "vault-bearer-token", + }, + "client_pool": { + "max_clients": 32, + "idle_ttl_seconds": 600, + }, + }, + ) + + assert parsed.backend_config["user_credentials"] == "***" + assert parsed.backend_config["credential_provider"] == "myapp.creds:VaultProvider" + provider_cfg = parsed.backend_config["credential_provider_config"] + assert provider_cfg["endpoint"] == "https://vault.internal" + assert provider_cfg["namespace"] == "prod" + assert provider_cfg["timeout_seconds"] == 5 + assert provider_cfg["api_key"] == "***" + assert provider_cfg["client_secret"] == "***" + assert provider_cfg["token"] == "***" + assert parsed.backend_config["client_pool"] == {"max_clients": 32, "idle_ttl_seconds": 600} + + serialized = parsed.model_dump_json() + for secret in ("alice-plaintext-secret", "BOB_OV_KEY", "vault-api-secret", "vault-client-secret", "vault-bearer-token"): + assert secret not in serialized + + +def test_memory_target_uris_supports_home_alias() -> None: + from deerflow.agents.memory.backends.openviking.session import _memory_target_uris + + assert _memory_target_uris("research") == [ + "viking://user/memories", + "viking://user/peers/research/memories", + ] + assert _memory_target_uris("research", use_home_alias=True) == [ + "viking://~/memories", + "viking://~/peers/research/memories", + ] + + +class _FakeInvalidURIError(Exception): + code = "INVALID_URI" + + +def test_get_context_falls_back_to_home_alias_and_caches_for_subsequent_reads( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + official_integration: None, +) -> None: + import deerflow.agents.memory.backends.openviking.openviking_manager as module + + class _CompatRetriever(_Retriever): + def invoke(self, query: str) -> list[Document]: + result = super().invoke(query) + if self.target_uri[0] == "viking://user/memories": + raise _FakeInvalidURIError("Invalid URI: viking://user/memories (Use 'viking://~/memories' for the current user)") + return result + + orig_loader = module._load_official_integration + + def _loader_with_compat() -> dict[str, Any]: + loaded = orig_loader() + loaded["OpenVikingRetriever"] = _CompatRetriever + return loaded + + monkeypatch.setattr(module, "_load_official_integration", _loader_with_compat) + manager = _manager(tmp_path, monkeypatch, failure_policy={"read": "raise"}) + + context = manager.get_context("alice", agent_name="research", thread_id="thread-1") + assert context == "- [preferences] Prefers concise answers." + assert [c["target_uri"] for c in manager._retriever.calls] == [ + ["viking://user/memories", "viking://user/peers/research/memories"], + ["viking://~/memories", "viking://~/peers/research/memories"], + ] + + # Sticky cache: subsequent get_context and search skip legacy URIs altogether. + hits = manager.search("concise", user_id="alice", agent_name="research") + assert len(hits) == 1 + assert manager._retriever.calls[2]["target_uri"] == [ + "viking://~/memories", + "viking://~/peers/research/memories", + ] + + +def test_search_falls_back_to_home_alias_when_first_read( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + official_integration: None, +) -> None: + import deerflow.agents.memory.backends.openviking.openviking_manager as module + + class _CompatRetriever(_Retriever): + def invoke(self, query: str) -> list[Document]: + result = super().invoke(query) + if self.target_uri[0] == "viking://user/memories": + raise _FakeInvalidURIError("Use 'viking://~/memories'") + return result + + orig_loader = module._load_official_integration + + def _loader_with_compat() -> dict[str, Any]: + loaded = orig_loader() + loaded["OpenVikingRetriever"] = _CompatRetriever + return loaded + + monkeypatch.setattr(module, "_load_official_integration", _loader_with_compat) + manager = _manager(tmp_path, monkeypatch, failure_policy={"read": "raise"}) + + hits = manager.search("concise", user_id="alice") + assert len(hits) == 1 + assert [c["target_uri"] for c in manager._retriever.calls] == [ + ["viking://user/memories", "viking://user/peers/deerflow/memories"], + ["viking://~/memories", "viking://~/peers/deerflow/memories"], + ] + + +@pytest.mark.parametrize( + "exc_factory", + [ + lambda: _FakeInvalidURIError("Invalid URI: arbitrary syntax error"), + lambda: RuntimeError("transient connection drop"), + ], +) +def test_non_home_alias_errors_do_not_retry_or_flip_uri_mode( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + official_integration: None, + exc_factory: Any, +) -> None: + import deerflow.agents.memory.backends.openviking.openviking_manager as module + + class _FailingRetriever(_Retriever): + def invoke(self, query: str) -> list[Document]: + super().invoke(query) + raise exc_factory() + + orig_loader = module._load_official_integration + + def _loader() -> dict[str, Any]: + loaded = orig_loader() + loaded["OpenVikingRetriever"] = _FailingRetriever + return loaded + + monkeypatch.setattr(module, "_load_official_integration", _loader) + manager = _manager(tmp_path, monkeypatch, failure_policy={"read": "raise"}) + + with pytest.raises(MemoryReadError): + manager.get_context("alice") + + assert len(manager._retriever.calls) == 1 + assert manager._use_home_alias_uris is False + + +@pytest.mark.parametrize("bad_runtime_uid", [" alice", "alice ", "alice\x00bob", "alice\n", "alice\t"]) +def test_multi_user_rejects_untrimmed_or_control_char_runtime_user_id( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + bad_runtime_uid: str, +) -> None: + recorders, retrievers = _track_official_integration(monkeypatch) + provider_calls: list[str] = [] + + def provider(uid: str) -> str: + provider_calls.append(uid) + return f"key-{uid.strip()}" + + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path, failure_policy={"read": "raise", "write": "raise"}), + credential_provider=provider, + ) + try: + with pytest.raises(MemoryManagerError, match="stripped DeerFlow user_id"): + manager.add("thread-1", [HumanMessage("hi", id="h1")], user_id=bad_runtime_uid) + with pytest.raises(MemoryReadError) as ctx_exc: + manager.get_context(bad_runtime_uid, thread_id="thread-1") + assert isinstance(ctx_exc.value.__cause__, MemoryManagerError) + with pytest.raises(MemoryReadError) as search_exc: + manager.search("prefs", user_id=bad_runtime_uid) + assert isinstance(search_exc.value.__cause__, MemoryManagerError) + + assert provider_calls == [] + assert recorders == [] + assert retrievers == [] + finally: + manager.close() + + +def test_hybrid_mode_rejects_dynamic_reuse_of_uncached_or_evicted_static_key( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorders, _ = _track_official_integration(monkeypatch) + dynamic_keys = { + "bob": {"api_key": "alice-static-secret", "tenant_id": "acme"}, + "carol": {"api_key": "carol-dynamic-secret", "tenant_id": "globex"}, + } + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + failure_policy={"read": "raise", "write": "raise"}, + client_pool={"max_clients": 1}, + user_credentials={"alice": {"api_key": "alice-static-secret", "tenant_id": "acme"}}, + ), + credential_provider=lambda uid: dynamic_keys.get(uid), + ) + try: + # Case A: alice has never been acquired yet (not in _pool or _inflight_entries) + with pytest.raises(MemoryManagerError, match="cannot be shared across distinct DeerFlow scopes"): + manager.add("thread-1", [HumanMessage("leak", id="l1")], user_id="bob") + with pytest.raises(MemoryReadError, match="cannot be shared across distinct DeerFlow scopes"): + manager.get_context("bob") + assert recorders == [] + + # Case B: alice is acquired and then evicted from the size-1 pool by carol; conflict still catches bob + manager.search("prefs", user_id="alice") + assert len(recorders) == 1 + manager.search("prefs", user_id="carol") + assert len(recorders) == 2 + assert recorders[0].closed is True + + with pytest.raises(MemoryManagerError, match="cannot be shared across distinct DeerFlow scopes"): + manager.add("thread-1", [HumanMessage("leak2", id="l2")], user_id="bob") + assert len(recorders) == 2 + finally: + manager.close() + + +def test_tenant_reassignment_retires_cached_and_inflight_handles( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorders, _ = _track_official_integration(monkeypatch) + current = {"alice": OpenVikingCredential(api_key="alice-v1", tenant_id="acme")} + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + client_pool={"max_clients": 4, "idle_ttl_seconds": None}, + ), + credential_provider=lambda uid: current.get(uid), + ) + try: + # 1. Idle tenant reassignment closes the old acme handle immediately + manager.search("prefs", user_id="alice") + assert len(recorders) == 1 + rec_acme = recorders[0] + assert rec_acme.closed is False + + current["alice"] = OpenVikingCredential(api_key="alice-v2", tenant_id="globex") + manager.search("prefs", user_id="alice") + assert len(recorders) == 2 + rec_globex = recorders[1] + assert rec_acme.closed is True + assert rec_globex.closed is False + assert list(manager._pool) == [("globex", "alice", current["alice"].key_fingerprint)] + + # 2. In-flight entry across tenant reassignment is marked retired in _inflight_entries + started = threading.Event() + release = threading.Event() + orig_record = rec_globex.record + + def blocked_record(*args: Any, **kwargs: Any) -> object: + started.set() + assert release.wait(5.0) + return orig_record(*args, **kwargs) + + rec_globex.record = blocked_record + t_inflight = threading.Thread( + target=manager.add, + args=("t-tenant-rot", [HumanMessage("slow", id="s1")]), + kwargs={"user_id": "alice"}, + ) + t_inflight.start() + assert started.wait(5.0) + + # Simulate concurrent eviction/re-entry of an already-in-flight entry before reassignment + with manager._pool_lock: + inflight_entry = next(iter(manager._inflight_entries)) + assert inflight_entry.retired is False + + current["alice"] = OpenVikingCredential(api_key="alice-v3", tenant_id="initech") + manager.search("prefs", user_id="alice") + assert len(recorders) == 3 + rec_initech = recorders[2] + assert inflight_entry.retired is True + assert rec_globex.closed is False + + release.set() + t_inflight.join(5.0) + assert not t_inflight.is_alive() + assert rec_globex.closed is True + assert rec_initech.closed is False + finally: + manager.close() + + +@pytest.mark.parametrize("bad_agent_name", ["", " ", "__default__"]) +def test_invalid_agent_name_honors_failure_policies( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + bad_agent_name: str, +) -> None: + from deerflow.agents import memory as memory_pkg + from deerflow.agents.lead_agent.prompt import _get_memory_context + from deerflow.config.app_config import AppConfig + from deerflow.config.memory_config import MemoryConfig + from deerflow.config.sandbox_config import SandboxConfig + + recorders, retrievers = _track_official_integration(monkeypatch) + monkeypatch.setenv("OPENVIKING_API_KEY", "single-secret") + + single_drop = OpenVikingMemoryManager.from_config(_backend_config(tmp_path / "s-drop", failure_policy={"read": "fail_open", "write": "log_and_drop"})) + single_raise = OpenVikingMemoryManager.from_config(_backend_config(tmp_path / "s-raise", failure_policy={"read": "raise", "write": "raise"})) + multi_drop = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path / "m-drop", + user_credentials={"alice": {"api_key": "alice-secret"}}, + failure_policy={"read": "fail_open", "write": "log_and_drop"}, + ) + ) + multi_raise = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path / "m-raise", + user_credentials={"alice": {"api_key": "alice-secret"}}, + failure_policy={"read": "raise", "write": "raise"}, + ) + ) + try: + for drop_mgr, raise_mgr in ((single_drop, single_raise), (multi_drop, multi_raise)): + with caplog.at_level(logging.ERROR, logger=OpenVikingMemoryManager.__module__): + assert drop_mgr.add("thread-1", [HumanMessage("secret", id="h1")], user_id="alice", agent_name=bad_agent_name) is None + with pytest.raises(MemoryManagerError, match="Invalid OpenViking peer scope"): + raise_mgr.add("thread-1", [HumanMessage("secret", id="h1")], user_id="alice", agent_name=bad_agent_name) + + with pytest.raises(MemoryManagerError, match="Invalid OpenViking peer scope"): + drop_mgr.get_context("alice", agent_name=bad_agent_name) + with pytest.raises(MemoryReadError, match="Invalid OpenViking peer scope"): + raise_mgr.get_context("alice", agent_name=bad_agent_name) + with pytest.raises(MemoryReadError, match="Invalid OpenViking peer scope"): + raise_mgr.search("prefs", user_id="alice", agent_name=bad_agent_name) + + open_cfg = AppConfig( + sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider"), + memory=MemoryConfig( + enabled=True, + injection_enabled=True, + manager_class="openviking", + backend_config=drop_mgr.backend_config, + ), + ) + monkeypatch.setattr(memory_pkg, "get_memory_manager", lambda m=drop_mgr: m) + assert _get_memory_context(app_config=open_cfg, user_id="alice", agent_name=bad_agent_name) == "" + + raise_cfg = AppConfig( + sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider"), + memory=MemoryConfig( + enabled=True, + injection_enabled=True, + manager_class="openviking", + backend_config=raise_mgr.backend_config, + ), + ) + monkeypatch.setattr(memory_pkg, "get_memory_manager", lambda m=raise_mgr: m) + with pytest.raises(MemoryReadError, match="Invalid OpenViking peer scope"): + _get_memory_context(app_config=raise_cfg, user_id="alice", agent_name=bad_agent_name) + + assert all(rec.calls == [] for rec in recorders) + assert all(ret.calls == [] for ret in retrievers) + finally: + for mgr in (single_drop, single_raise, multi_drop, multi_raise): + mgr.close() + + +def test_save_cursor_oserror_honors_write_failure_policy( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + _track_official_integration(monkeypatch) + drop_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path / "drop", + user_credentials={"alice": {"api_key": "alice-secret"}}, + failure_policy={"write": "log_and_drop"}, + ) + ) + raise_mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path / "raise", + user_credentials={"alice": {"api_key": "alice-secret"}}, + failure_policy={"write": "raise"}, + ) + ) + try: + + def fail_save(session_id: str, state: dict[str, Any]) -> None: + del session_id, state + raise OSError("disk full") + + monkeypatch.setattr(drop_mgr, "_save_cursor", fail_save) + monkeypatch.setattr(raise_mgr, "_save_cursor", fail_save) + + with caplog.at_level(logging.ERROR, logger=OpenVikingMemoryManager.__module__): + assert drop_mgr.add("thread-1", [HumanMessage("msg", id="h1")], user_id="alice") is None + assert any("OpenViking capture cursor persistence failed" in r.getMessage() for r in caplog.records) + + with pytest.raises(MemoryManagerError, match="OpenViking capture cursor persistence failed"): + raise_mgr.add("thread-1", [HumanMessage("msg", id="h1")], user_id="alice") + finally: + drop_mgr.close() + raise_mgr.close() + + +def test_constructor_exceptions_sanitize_secrets_and_close_loaded_provider_on_init_failure( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import deerflow.agents.memory.backends.openviking.openviking_manager as module + + pkg = tmp_path / "dyn_ov_ctor_err" + pkg.mkdir() + (pkg / "__init__.py").write_text("", encoding="utf-8") + (pkg / "mod.py").write_text( + "class FailingCtorProvider:\n" + " def __init__(self, dsn: str):\n" + " raise RuntimeError(f'bad dsn: {dsn}')\n" + "\n" + "def failing_factory(token: str):\n" + " raise ValueError(f'bad token: {token}')\n" + "\n" + "events = []\n" + "class CleanupTrackerProvider:\n" + " def resolve(self, user_id: str):\n" + " return 'key-' + user_id\n" + " def close(self):\n" + " events.append('closed')\n", + encoding="utf-8", + ) + monkeypatch.syspath_prepend(str(tmp_path)) + importlib.invalidate_caches() + + with pytest.raises(ValueError, match=r"initialization failed \(RuntimeError\)") as cls_exc: + load_credential_provider("dyn_ov_ctor_err.mod:FailingCtorProvider", {"dsn": "postgres://u:super-secret-dsn@h/db"}) + assert "super-secret-dsn" not in str(cls_exc.value) + assert cls_exc.value.__cause__ is None + + with pytest.raises(ValueError, match=r"initialization failed \(ValueError\)") as fac_exc: + load_credential_provider("dyn_ov_ctor_err.mod:failing_factory", {"token": "factory-super-secret"}) + assert "factory-super-secret" not in str(fac_exc.value) + assert fac_exc.value.__cause__ is None + + # If model_post_init fails after load_credential_provider(), loaded provider must be closed + monkeypatch.setattr(module, "_load_official_integration", lambda: (_ for _ in ()).throw(ImportError("missing integration"))) + with pytest.raises(ImportError, match="missing integration"): + OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + credential_provider="dyn_ov_ctor_err.mod:CleanupTrackerProvider", + ) + ) + mod = importlib.import_module("dyn_ov_ctor_err.mod") + assert mod.events == ["closed"] + + # Single-user startup _build_scoped_entry failure must also sanitize API key + class _ExplodingSingleRecorder: + def __init__(self, *, url: str, api_key: str, **kwargs: Any) -> None: + del url, kwargs + raise RuntimeError(f"boom with {api_key}") + + monkeypatch.setattr( + module, + "_load_official_integration", + lambda: { + "OpenVikingCommitPolicy": _CommitPolicy, + "OpenVikingPartialWriteError": _PartialWriteError, + "OpenVikingRetriever": _Retriever, + "OpenVikingSessionRecorder": _ExplodingSingleRecorder, + "use_actor_peer": _use_actor_peer, + }, + ) + monkeypatch.setenv("OPENVIKING_API_KEY", "single-super-secret") + with pytest.raises(MemoryManagerError, match=r"Failed to initialize OpenViking client \(RuntimeError\)") as init_exc: + OpenVikingMemoryManager.from_config(_backend_config(tmp_path)) + assert "single-super-secret" not in str(init_exc.value) + assert init_exc.value.__cause__ is None + + +def test_inflight_revocation_defers_close_and_inflight_evicted_key_conflict_rejects( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorders, _ = _track_official_integration(monkeypatch) + keys: dict[str, str | None] = {"alice": "shared-secret", "bob": "bob-secret"} + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + client_pool={"max_clients": 1}, + failure_policy={"read": "raise", "write": "raise"}, + ), + credential_provider=lambda uid: keys.get(uid), + ) + try: + manager.search("warmup", user_id="alice") + assert len(recorders) == 1 + rec_alice = recorders[0] + + started = threading.Event() + release = threading.Event() + orig_record = rec_alice.record + + def blocked_record(*args: Any, **kwargs: Any) -> object: + started.set() + assert release.wait(timeout=5.0) + return orig_record(*args, **kwargs) + + rec_alice.record = blocked_record + t_inflight = threading.Thread( + target=manager.add, + args=("t-revoke", [HumanMessage("slow", id="s1")]), + kwargs={"user_id": "alice"}, + ) + t_inflight.start() + try: + assert started.wait(timeout=5.0) + + # Evict alice from max_clients=1 pool via bob while alice's entry stays in _inflight_entries + manager.search("warmup", user_id="bob") + assert len(recorders) == 2 + assert rec_alice.closed is False + + # Another user reusing alice's still-in-flight evicted key must be rejected + keys["carol"] = "shared-secret" + with pytest.raises(MemoryManagerError, match="cannot be shared across distinct DeerFlow scopes"): + manager.add("t-conflict", [HumanMessage("leak", id="c1")], user_id="carol") + assert len(recorders) == 2 + + # Revoke alice while alice's entry is still in-flight -> retired now, closed only after completion + keys["alice"] = None + with pytest.raises(MemoryManagerError, match="No OpenViking USER API key"): + manager.add("t-revoked", [HumanMessage("after revoke", id="r1")], user_id="alice") + assert rec_alice.closed is False + finally: + release.set() + t_inflight.join(timeout=5.0) + + assert not t_inflight.is_alive() + assert rec_alice.closed is True + finally: + manager.close() + + +def test_single_user_config_parity_and_multi_user_edge_cases( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("OPENVIKING_API_KEY", "valid-single-key") + + with pytest.raises(ValueError, match="must not embed credentials"): + OpenVikingConfig.from_backend_config(_backend_config(tmp_path, base_url="http://user:pass@127.0.0.1:1933")) + + for bad_owner in (123, True, "alice\x00bob", "alice\nbob"): + with pytest.raises(ValueError, match="owner_user_id must be a string without control characters"): + OpenVikingConfig.from_backend_config(_backend_config(tmp_path, owner_user_id=bad_owner)) + + for bad_env in (123, "ENV\x00KEY", "ENV\nKEY"): + with pytest.raises(ValueError, match="api_key_env must be a string without control characters"): + OpenVikingConfig.from_backend_config(_backend_config(tmp_path, api_key_env=bad_env)) + with pytest.raises(ValueError, match=r"user_credentials\.alice\.api_key_env must be a non-empty string without control characters"): + OpenVikingConfig.from_backend_config(_multi_user_backend_config(tmp_path, user_credentials={"alice": {"api_key_env": bad_env}})) + + with pytest.raises(ValueError, match="api_key_env must be a non-empty string without control characters"): + OpenVikingCredential(api_key="valid-key", api_key_env="OV\nKEY") + + # Duplicate secrets across two different env vars in multi-user mode + monkeypatch.setenv("ALICE_ENV_KEY", "shared-env-secret") + monkeypatch.setenv("BOB_ENV_KEY", "shared-env-secret") + with pytest.raises(ValueError, match="must not share the same API key") as dup_exc: + OpenVikingConfig.from_backend_config( + _multi_user_backend_config( + tmp_path, + user_credentials={ + "alice": {"api_key_env": "ALICE_ENV_KEY"}, + "bob": {"api_key_env": "BOB_ENV_KEY"}, + }, + ) + ) + assert "shared-env-secret" not in str(dup_exc.value) + + # Empty user_credentials paired with credential_provider is valid, and __call__-only provider objects work + class _CallableOnlyProvider: + def __call__(self, user_id: str) -> str: + return f"callable-key-{user_id}" + + cfg = OpenVikingConfig.from_backend_config( + _multi_user_backend_config(tmp_path, user_credentials={}), + has_injected_credential_provider=True, + ) + assert cfg.isolation_mode == "multi_user" + assert len(cfg.user_credentials) == 0 + + recorders, _ = _track_official_integration(monkeypatch) + mgr = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path, user_credentials={}), + credential_provider=_CallableOnlyProvider(), + ) + try: + mgr.search("prefs", user_id="alice") + assert recorders[-1].connection["api_key"] == "callable-key-alice" + finally: + mgr.close() + + +@pytest.mark.asyncio +async def test_admitted_async_write_does_not_wait_on_slow_provider_cleanup_during_shutdown( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import asyncio + + recorders, _ = _track_official_integration(monkeypatch) + resolve_started = threading.Event() + release_resolve = threading.Event() + close_started = threading.Event() + release_close = threading.Event() + close_calls = 0 + + class _SlowCleanupProvider: + def resolve(self, user_id: str) -> str: + resolve_started.set() + assert release_resolve.wait(timeout=5.0) + return f"key-{user_id}" + + def close(self) -> None: + nonlocal close_calls + close_calls += 1 + close_started.set() + assert release_close.wait(timeout=5.0) + + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config(tmp_path, timeout_seconds=5.0), + credential_provider=_SlowCleanupProvider(), + ) + + write_task = asyncio.create_task( + manager.aadd( + "thread-1", + [HumanMessage("admitted async write", id="h1")], + user_id="alice", + ) + ) + flush_task: asyncio.Task[bool] | None = None + try: + assert await asyncio.to_thread(resolve_started.wait, 5.0) + + flush_task = asyncio.create_task(asyncio.to_thread(manager.shutdown_flush, 0.15)) + deadline = time.monotonic() + 5.0 + while not manager._closed and time.monotonic() < deadline: + await asyncio.sleep(0.01) + assert manager._closed is True + + release_resolve.set() + + # The last admitted async write must finish immediately after recording its + # update without blocking on slow provider cleanup (timeout_seconds=5.0). + await asyncio.wait_for(write_task, timeout=1.0) + assert len(recorders) == 1 + assert len(recorders[0].calls) == 1 + assert manager._state_path(_session_id("alice", "deerflow", "thread-1")).exists() + + # Shutdown flush owns the bounded cleanup wait and times out on schedule. + assert await asyncio.wait_for(flush_task, timeout=1.0) is False + assert await asyncio.to_thread(close_started.wait, 1.0) + assert recorders[0].closed is True + assert not release_close.is_set() + + # Follow-up Gateway close() must not block past the already-timed-out flush. + await asyncio.wait_for(asyncio.to_thread(manager.close), timeout=0.5) + assert close_calls == 1 + finally: + release_resolve.set() + release_close.set() + if not write_task.done(): + await asyncio.wait_for(write_task, timeout=5.0) + if flush_task is not None and not flush_task.done(): + await asyncio.wait_for(flush_task, timeout=5.0) + + assert manager.shutdown_flush(1.0) is True + assert close_calls == 1 + + +@pytest.mark.parametrize("mode", ["single_user", "multi_user"]) +def test_shutdown_flush_bounds_slow_recorder_teardown_without_provider_close( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mode: str, +) -> None: + recorders, _ = _track_official_integration(monkeypatch) + monkeypatch.setenv("OPENVIKING_API_KEY", "single-secret") + + if mode == "single_user": + manager = OpenVikingMemoryManager.from_config(_backend_config(tmp_path, timeout_seconds=2.0)) + else: + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + timeout_seconds=2.0, + user_credentials={"alice": {"api_key": "alice-secret"}}, + ) + ) + manager.search("warmup", user_id="alice") + + assert len(recorders) == 1 + recorder = recorders[0] + close_started = threading.Event() + release_close = threading.Event() + close_calls = 0 + orig_close = recorder.close + + def slow_close() -> None: + nonlocal close_calls + close_calls += 1 + close_started.set() + assert release_close.wait(timeout=5.0) + orig_close() + + recorder.close = slow_close + + try: + t0 = time.monotonic() + assert manager.shutdown_flush(0.05) is False + assert time.monotonic() - t0 < 0.5 + assert close_started.wait(timeout=1.0) + assert not release_close.is_set() + + t1 = time.monotonic() + manager.close() + assert time.monotonic() - t1 < 0.5 + assert close_calls == 1 + finally: + release_close.set() + + assert manager.shutdown_flush(1.0) is True + assert recorder.closed is True + assert close_calls == 1 + + +@pytest.mark.asyncio +async def test_admitted_async_write_does_not_wait_on_slow_recorder_teardown( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import asyncio + + recorders, _ = _track_official_integration(monkeypatch) + manager = OpenVikingMemoryManager.from_config( + _multi_user_backend_config( + tmp_path, + timeout_seconds=5.0, + user_credentials={"alice": {"api_key": "alice-secret"}}, + ) + ) + manager.search("warmup", user_id="alice") + assert len(recorders) == 1 + recorder = recorders[0] + + record_started = threading.Event() + release_record = threading.Event() + close_started = threading.Event() + release_close = threading.Event() + close_calls = 0 + orig_record = recorder.record + orig_close = recorder.close + + def blocked_record(*args: Any, **kwargs: Any) -> object: + record_started.set() + assert release_record.wait(timeout=5.0) + return orig_record(*args, **kwargs) + + def slow_close() -> None: + nonlocal close_calls + close_calls += 1 + close_started.set() + assert release_close.wait(timeout=5.0) + orig_close() + + recorder.record = blocked_record + recorder.close = slow_close + + write_task = asyncio.create_task( + manager.aadd( + "thread-1", + [HumanMessage("admitted async write", id="h1")], + user_id="alice", + ) + ) + flush_task: asyncio.Task[bool] | None = None + try: + assert await asyncio.to_thread(record_started.wait, 5.0) + + flush_task = asyncio.create_task(asyncio.to_thread(manager.shutdown_flush, 0.15)) + deadline = time.monotonic() + 5.0 + while not manager._closed and time.monotonic() < deadline: + await asyncio.sleep(0.01) + assert manager._closed is True + + release_record.set() + + # Finishing write starts cleanup worker and returns promptly without waiting on slow recorder.close(). + await asyncio.wait_for(write_task, timeout=1.0) + assert len(recorder.calls) == 1 + assert manager._state_path(_session_id("alice", "deerflow", "thread-1")).exists() + + # Bounded shutdown_flush returns False on schedule while recorder.close() is still pending. + assert await asyncio.wait_for(flush_task, timeout=1.0) is False + assert await asyncio.to_thread(close_started.wait, 1.0) + assert not release_close.is_set() + + # Follow-up Gateway close() returns promptly without double-closing recorder. + await asyncio.wait_for(asyncio.to_thread(manager.close), timeout=0.5) + assert close_calls == 1 + finally: + release_record.set() + release_close.set() + if not write_task.done(): + await asyncio.wait_for(write_task, timeout=5.0) + if flush_task is not None and not flush_task.done(): + await asyncio.wait_for(flush_task, timeout=5.0) + + assert manager.shutdown_flush(1.0) is True + assert recorder.closed is True + assert close_calls == 1 + + +def test_cleanup_worker_start_failure_marks_cleanup_done_and_sanitizes_log( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + import deerflow.agents.memory.backends.openviking.openviking_manager as module + + _track_official_integration(monkeypatch) + manager = OpenVikingMemoryManager.from_config(_multi_user_backend_config(tmp_path, user_credentials={"alice": {"api_key": "alice-secret"}})) + manager.search("warmup", user_id="alice") + + class _FailingThread: + def __init__(self, *args: Any, **kwargs: Any) -> None: + del args, kwargs + + def start(self) -> None: + raise RuntimeError("can't start new thread: secret-stack-info") + + monkeypatch.setattr(module.threading, "Thread", _FailingThread) + + with caplog.at_level(logging.WARNING, logger=OpenVikingMemoryManager.__module__): + assert manager.shutdown_flush(1.0) is False + + assert manager._cleanup_done.is_set() + assert manager._cleanup_failed is True + warnings = [r for r in caplog.records if "Failed to start OpenViking cleanup worker" in r.getMessage()] + assert len(warnings) == 1 + assert warnings[0].getMessage() == "Failed to start OpenViking cleanup worker (RuntimeError)" + assert warnings[0].exc_info is None + assert "secret-stack-info" not in caplog.text diff --git a/config.example.yaml b/config.example.yaml index 2b857f2497..19ccb22667 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -2582,10 +2582,9 @@ memory: # Backend-private config (a dict), passed verbatim to the backend __init__. # Each backend self-interprets it (DeerMem parses it into DeerMemConfig). # - # OpenViking example (replace this DeerMem backend_config block when - # manager_class is openviking). This first official-adapter integration uses - # one credential-bound OpenViking USER key for one DeerFlow user and supports - # middleware mode only. Use owner_user_id: default when DeerFlow auth is off. + # OpenViking single-user example (replace this DeerMem backend_config block + # when manager_class is openviking; supports middleware mode only). Use + # owner_user_id: default when DeerFlow auth is off. # # backend_config: # base_url: http://openviking:1933 @@ -2607,6 +2606,26 @@ memory: # user profile preferences important entities events ongoing goals # constraints and prior decisions # + # OpenViking multi-user / multi-tenant isolation example (api_key mode, + # middleware mode only; mutually exclusive with owner_user_id/api_key_env): + # + # backend_config: + # base_url: http://openviking:1933 + # user_credentials: + # alice: + # api_key_env: OPENVIKING_API_KEY_ALICE + # tenant_id: acme # optional; derives tenant-isolated v2 session IDs + # bob: + # api_key_env: OPENVIKING_API_KEY_BOB + # tenant_id: globex + # # Or resolve credentials dynamically (optionally paired with user_credentials + # # or injected programmatically via host_hooks["credential_provider"]): + # # credential_provider: my_company.openviking_auth:VaultCredentialProvider + # # credential_provider_config: {} + # client_pool: # multi-user mode only + # max_clients: 64 # LRU cap (1..4096) + # idle_ttl_seconds: 900.0 # null disables idle TTL eviction + # # For a host-installed OpenViking used by Docker DeerFlow, set base_url to # http://host.docker.internal:1933 and allow_insecure_http: true. The bundled # optional Compose overlay uses the internal http://openviking:1933 address. diff --git a/docs/OPENVIKING.md b/docs/OPENVIKING.md index ceb8b0c938..e1ee1829aa 100644 --- a/docs/OPENVIKING.md +++ b/docs/OPENVIKING.md @@ -7,8 +7,8 @@ package instead of implementing OpenViking's HTTP protocol inside DeerFlow. ## Current scope -The first official-adapter integration deliberately preserves DeerFlow's -existing automatic-memory behavior: +The OpenViking integration preserves DeerFlow's automatic-memory behavior across +both single-user and multi-user / multi-tenant deployments: - memory is recalled through DeerFlow's existing fixed memory query; - completed turns are captured by the existing memory middleware; @@ -16,8 +16,10 @@ existing automatic-memory behavior: - every accepted capture is committed to the thread's stable OpenViking Session; - the official adapter handles message conversion, tool calls and results, 100-message batching, partial-write progress, commit retry, and SDK transport; -- one recorder-owned SDK client is shared with retrieval and closed through - DeerFlow's existing memory shutdown contract. +- in single-user mode, one recorder-owned SDK client is shared with retrieval + and closed on shutdown; in multi-user mode, a bounded LRU/TTL `client_pool` + manages isolated per-scope SDK clients and drains/closes them cleanly on + eviction, key rotation, revocation, and shutdown. This backend supports `memory.mode: middleware`. It does not implement DeerMem fact CRUD, import/export, or the Settings memory-document view. OpenViking MCP @@ -25,44 +27,62 @@ tools are a separate integration surface and are not enabled by this backend. ## Authentication boundary -This version is for one DeerFlow user backed by one ordinary OpenViking **USER -API key**. OpenViking derives the account and user from that credential. -DeerFlow does not configure trusted account/user headers and must not receive a -root key for normal memory traffic. +The supported server configuration is OpenViking `api_key` mode, where each +ordinary OpenViking **USER API key** determines the OpenViking account and user +server-side. DeerFlow supports two isolation modes on top of `api_key` mode: -The supported server configuration is OpenViking `api_key` mode, where the USER -key determines the account and user. DeerFlow supplies its URL and API key -explicitly, overrides any ambient actor peer during memory operations, and does -not inherit arbitrary HTTP headers from `ovcli.conf`. +- **Single-user mode** (`owner_user_id` + `api_key_env`): binds one DeerFlow + user identity to one OpenViking USER API key. Use `owner_user_id: default` + when DeerFlow authentication is disabled, or that user's DeerFlow ID in an + authenticated single-user deployment. A request for another DeerFlow user is + rejected before OpenViking is contacted, preventing one USER key from silently + sharing memory across users. The failure policies below decide what that + rejection does to the turn: with `write: log_and_drop` the other user's write + is logged as refused, without message content, and dropped, and the run still + completes. +- **Multi-user / multi-tenant isolation mode** (`user_credentials` and/or + `credential_provider` / `host_hooks["credential_provider"]`, plus optional + `tenant_id` and `client_pool`): resolves a distinct OpenViking USER API key + (and optional `tenant_id`) per DeerFlow user and isolates each scope's + client handle, headers, and session IDs. Multi-user configuration is mutually + exclusive with `owner_user_id` and `api_key_env`. + +### Why `auth_mode: trusted` / `account` remains unsupported + +In OpenViking `api_key` mode, OpenViking derives `account` and `user` +server-side from the USER API key (`X-API-Key`). Accepting `auth_mode: trusted` +or `account` headers in DeerFlow would trust caller-asserted identity headers +instead of key-derived identity and is therefore rejected at configuration time +(pointing operators to `owner_user_id`, `user_credentials`, or +`credential_provider`). DeerFlow also must not receive a root key for normal +memory traffic, overrides any ambient actor peer during memory operations, and +passes an explicit empty `extra_headers={}` mapping so the SDK never inherits +arbitrary HTTP headers from `ovcli.conf`. Before enabling this backend, remove legacy `OPENVIKING_ACCOUNT` and `OPENVIKING_USER` values from DeerFlow's repository-root `.env` and service environment, and remove `account` and `user` defaults from -`~/.openviking/ovcli.conf`. Those settings belong to trusted-mode -configurations and are outside this adapter's supported setup. - -`owner_user_id` binds the configured key to one DeerFlow identity. Use -`default` when DeerFlow authentication is disabled. In an authenticated -single-user deployment, use that user's DeerFlow ID. A request for another -DeerFlow user is rejected before OpenViking is contacted, preventing one USER -key from silently sharing memory across users. The failure policies below -decide what that rejection does to the turn: with `write: log_and_drop` the -other user's write is logged as refused, without message content, and dropped, -and the run still completes. - -Multi-user credential provisioning and storage are intentionally outside this -first adapter PR. +`~/.openviking/ovcli.conf`. Those settings belong to trusted-mode configurations +and are outside this adapter's supported setup. In multi-user mode, do not rely +on a shared ambient `OPENVIKING_API_KEY`; per-user keys are never resolved from +an ambient fallback. Existing trusted-mode configurations are not migrated automatically. Configure the OpenViking server in `api_key` mode, replace `auth_mode`, `account`, and the -root key with `owner_user_id` and a USER key, and remove the legacy ambient -identity settings listed above. Because the credential-bound user and Session -mapping differ from the old trusted-user mapping, previously captured +root key with either single-user (`owner_user_id` + `api_key_env`) or multi-user +(`user_credentials` / `credential_provider`) USER keys, and remove the legacy +ambient identity settings listed above. Because credential-bound user and Session +mappings differ from the old trusted-user mapping, previously captured trusted-mode data remains in its old OpenViking namespace rather than being silently reassigned. ## Configure DeerFlow +The dependency on `langchain-openviking==0.1.0` is declared by DeerFlow's +harness package and is installed by the normal `uv sync` flow. + +### Single-user mode + Create or select an OpenViking user, then copy its USER API key into DeerFlow's repository-root `.env`: @@ -101,8 +121,144 @@ For a host-installed OpenViking used by Docker DeerFlow, set `base_url` to `http://host.docker.internal:1933` and `allow_insecure_http: true`. The optional Compose overlay uses the internal `http://openviking:1933` address. -The dependency on `langchain-openviking==0.1.0` is declared by DeerFlow's -harness package and is installed by the normal `uv sync` flow. +### Multi-user and multi-tenant isolation mode + +Use `user_credentials` for a static per-user mapping, `credential_provider` +for dynamic resolution, or both together (static `user_credentials` is checked +first, and `credential_provider` resolves users not listed statically). Do **not** +set `owner_user_id` or `api_key_env` at the `backend_config` top level when +using multi-user mode. + +#### Static per-user mapping (`user_credentials`) + +Put each user's OpenViking USER API key in DeerFlow's `.env` or service +environment: + +```dotenv +OPENVIKING_API_KEY_ALICE=replace-with-alice-user-api-key +OPENVIKING_API_KEY_BOB=replace-with-bob-user-api-key +``` + +Configure `user_credentials` and `client_pool` in `config.yaml`: + +```yaml +memory: + enabled: true + injection_enabled: true + shutdown_flush_timeout_seconds: 30 + manager_class: openviking + mode: middleware + backend_config: + base_url: http://127.0.0.1:1933 + user_credentials: + alice: + api_key_env: OPENVIKING_API_KEY_ALICE + tenant_id: acme + bob: + api_key_env: OPENVIKING_API_KEY_BOB + tenant_id: globex + client_pool: + max_clients: 64 + idle_ttl_seconds: 900.0 + startup_policy: fail_fast + failure_policy: + read: fail_open + write: log_and_drop + retrieval: + top_k: 8 + score_threshold: 0.25 + max_injection_chars: 12000 + content_mode: overview + injection_query: >- + user profile preferences important entities events ongoing goals + constraints and prior decisions +``` + +`user_credentials` rules: + +- Each mapping key is the exact DeerFlow `user_id` (non-empty stripped string + with no control characters or `\0`). +- Each user entry accepts only `api_key_env`, `api_key`, and optional + `tenant_id`. Exactly **one** of `api_key_env` or `api_key` is required per + entry; `api_key_env` is recommended so secret keys stay out of `config.yaml`. +- `tenant_id` is optional. When set, it must be a non-empty stripped string of + at most 128 characters with no control characters or `\0`. +- When `credential_provider` (or `host_hooks["credential_provider"]`) is not + configured, `user_credentials` must be non-empty. +- Every statically configured user must have a distinct API key. + +#### Dynamic credential resolution (`credential_provider` and `host_hooks`) + +For dynamic, KMS/vault-backed, or rotating user credentials, specify a dotted +Python import path in `credential_provider` (`pkg.module:Attr` or +`pkg.module.Attr`) and optional constructor/factory keyword arguments in +`credential_provider_config`: + +```yaml +memory: + enabled: true + injection_enabled: true + manager_class: openviking + mode: middleware + backend_config: + base_url: http://127.0.0.1:1933 + credential_provider: my_company.openviking_auth:VaultCredentialProvider + credential_provider_config: + vault_url: https://vault.internal + namespace: deerflow + client_pool: + max_clients: 128 + idle_ttl_seconds: 900.0 +``` + +Provider resolution contract (`OpenVikingCredentialProvider`): + +- `OpenVikingConfig.from_backend_config()` validates `credential_provider` + path syntax without importing the module or performing I/O, keeping `make doctor` + and policy checks side-effect-free. +- At manager initialization, DeerFlow imports the target attribute: + - If the target is a class, DeerFlow instantiates + `Attr(**credential_provider_config)` and expects a callable `.resolve` + method or callable instance. + - If the target is a callable factory/function and `credential_provider_config` + is non-empty, DeerFlow calls `Attr(**credential_provider_config)` and uses + the returned resolver (`.resolve` method or callable). If + `credential_provider_config` is empty, `Attr` itself is used directly. +- Embedded hosts and custom extensions can also inject a provider instance or + callable programmatically via `host_hooks["credential_provider"]` when calling + `OpenVikingMemoryManager.from_config(..., credential_provider=...)`, without + declaring an import path in `config.yaml`. Because Gateway and + `DynamicContextMiddleware` config bootstrap consult + `OpenVikingMemoryManager.read_failures_are_fatal_for_config(backend_config)` + (which requires `user_credentials` or `credential_provider` in + `backend_config`), `host_hooks["credential_provider"]` is intended for direct + programmatic callers outside config-driven Gateway/`DynamicContextMiddleware` + wiring. +- `credential_provider_config` applies only when DeerFlow instantiates a + config-declared `credential_provider` and must be omitted or empty when + `credential_provider` is not set in `backend_config` (including when passing an + already-instantiated hook via `host_hooks["credential_provider"]`). +- At request time, the provider's `resolve(user_id)` returns one of: + - `OpenVikingCredential(api_key=..., tenant_id=...)` + - a mapping containing only `api_key` and optional `tenant_id` + - a plain `str` (treated as `api_key` with `tenant_id=None`) + - `None` (treated as unmapped or revoked; fails closed) +- If the provider defines a callable `.close()` method, DeerFlow invokes it + during graceful shutdown (`shutdown_flush()` / `close()`). + +#### Client pool (`client_pool`) + +Multi-user mode caches scoped `(tenant_id, user_id, key_fingerprint)` SDK +recorder/retriever handles in a bounded pool: + +- `max_clients` (integer `1..4096`, default `64`): maximum active client + handles retained in the LRU pool. When full, the least-recently-used idle + handle is evicted and closed; if an evicted handle still has active in-flight + operations, `close()` is deferred until those operations finish. +- `idle_ttl_seconds` (positive finite float or `null`, default `900.0`): idle + eviction threshold in seconds. Omitting `idle_ttl_seconds` keeps the + `900.0`-second default; setting `idle_ttl_seconds: null` explicitly disables + TTL-based eviction. ## Start the services @@ -140,9 +296,16 @@ docker compose \ up -d --build ``` -Configure OpenViking in API-key mode and obtain a USER key through its identity -management flow. Only that USER key belongs in DeerFlow's -`OPENVIKING_API_KEY` variable. +Configure OpenViking in `api_key` mode and obtain ordinary USER keys through +its identity management flow. Put only USER keys in DeerFlow's `OPENVIKING_API_KEY` +(single-user), per-user environment variables referenced by `user_credentials`, +or your `credential_provider` store. + +In single-user mode, `warm()` verifies OpenViking health through the configured +client's `health()` check. In multi-user mode, because no single user key owns +the backend, `warm()` probes `GET {base_url}/health` without any user API key +or ambient `ovcli.conf` headers, checks for HTTP 200 and JSON `status == "ok"`, +and honors `startup_policy` (`fail_fast` vs `warn`). ## Identity and session mapping @@ -150,12 +313,75 @@ One DeerFlow thread maps deterministically to one OpenViking Session. A commit creates an archive inside that Session; it does not create a new Session, so a thread keeps the same identity when the user returns later. +Session ID derivation depends on whether `tenant_id` is set: + +- **Unscoped (`tenant_id` is unset / `None`)**: preserves the v1 derivation + (`deerflow-openviking-adapter-v1`, hashing namespace, `user_id`, `peer_id`, + and `thread_id`), so existing single-user deployments and unscoped multi-user + entries keep their stable v1 `df_` session IDs. +- **Tenant-scoped (`tenant_id` is set)**: uses the v2 derivation + (`deerflow-openviking-adapter-v2`, hashing namespace, `tenant_id`, `user_id`, + `peer_id`, and `thread_id`). Even when two tenants use the same DeerFlow + `user_id`, `agent_name`, and `thread_id`, their OpenViking `session_id` + values and local capture cursors are completely disjoint from each other and + from unscoped v1 sessions. + The default DeerFlow agent uses `default_peer_id` (`deerflow` by default). Named agents use lowercase OpenViking peer IDs. Names that are not valid peer IDs, conflict with the default, or enter the reserved `df-agent-` namespace are mapped to collision-resistant IDs. USER-key identity remains the security boundary; peers separate memory scopes within that user. +## Security and isolation invariants + +- **Fail-closed user resolution**: in multi-user mode, `None`, empty, or + whitespace-only `user_id` values, leading/trailing whitespace or control + characters (`\0`) on runtime `user_id` values, unmapped users, revoked users + (`None` from `credential_provider`), invalid/blank keys, and provider errors + are all rejected before any OpenViking HTTP call is made or local cursor file + is written: read paths raise `MemoryManagerError` (or `MemoryReadError` when + `failure_policy.read: raise`), and write paths follow `failure_policy.write` + (`log_and_drop` logs the refusal without message content or secrets and drops + the write; `raise` propagates `MemoryManagerError`). +- **No fallback to shared or ambient credentials**: DeerFlow never falls back + to another user's key, a default key, ambient `OPENVIKING_API_KEY`, or + `ovcli.conf` headers. +- **Cross-user duplicate key rejection**: DeerFlow tracks each key by its + SHA-256 `key_fingerprint` and refuses to share the same API key across + different users—both statically during `user_credentials` config validation + and dynamically in the runtime `client_pool`. Static `user_credentials` + fingerprints are always checked globally (including in hybrid deployments even + when a static user has not yet been called or was evicted); for purely dynamic + providers, runtime duplicate-key detection covers currently cached and + in-flight pool entries rather than evicted historical scopes. +- **Key validation without secret echoes**: API keys must contain printable + ASCII (`0x21..0x7E`) only (rejecting whitespace, newlines, `\0`, control + characters, and non-ASCII to prevent header injection). Config/validation + errors and `repr(OpenVikingConfig)` never echo raw API keys. +- **Key rotation and revocation**: pool entries are keyed by + `(tenant_id, user_id, key_fingerprint)`. When a provider rotates a user's key + or reassigns their `tenant_id`, DeerFlow opens a fresh scoped handle and + retires all previous cached and in-flight handles for that `user_id` so they + close once active operations complete. When a provider revokes a user by + returning `None`, DeerFlow immediately retires all cached and in-flight + handles for that user and refuses the request. +- **Refcount-safe, lock-free handle lifecycle**: in-flight operations hold a + reference count on the acquired entry so evicted, rotated, or revoked handles + are never closed out from under an active request, and pool locks are never + held while calling `credential_provider.resolve()`, constructing SDK clients, + or calling `close()`. +- **Gateway `/api/memory/config` masking**: `GET /api/memory/config` masks + `user_credentials` wholesale as `"***"` (hiding nested `api_key`, + `api_key_env`, and `tenant_id` entries) and masks secret-named keys inside + `credential_provider_config` (keys matching `api_key`, `secret`, `token`, + `password`, `credentials`, `authorization`, `bearer`, or `cookie`), while + keeping top-level non-secret settings (`base_url`, single-user `api_key_env`, + `client_pool`, and non-secret provider options) visible. Providers that need + DSNs or URLs with embedded credentials should read them from environment + variables or secret stores inside the provider rather than passing them via + non-secret keys in `credential_provider_config`. Note that `GET /api/memory/status` + returns HTTP `501` for OpenViking (same as `GET /api/memory`). + ## Retry and failure behavior - `read: fail_open` logs retrieval failures and continues the turn without @@ -169,18 +395,21 @@ boundary; peers separate memory scopes within that user. - `write: log_and_drop` logs capture failures without failing an already generated answer. `write: raise` propagates them. - DeerFlow stores only hashes and counters in a bounded local capture cursor - under `{storage_path}/openviking/sessions/`. It never stores message text - there. + under `{storage_path}/openviking/sessions/{session_id}.json`. It never stores + message text there. - The cursor prevents full LangGraph transcript snapshots from being submitted again. It also records confirmed progress from partial batches and retries a failed commit before appending more messages. - An unreadable cursor fails closed because replaying an unknown prefix could duplicate private conversation history. -- Graceful shutdown stops new memory work, waits up to - `shutdown_flush_timeout_seconds` for accepted operations, and closes the - recorder-owned SDK client. It does not introduce a new DeerFlow lifecycle or - background worker. +- Capture cursors remain local per Gateway instance. Shared DB-backed capture + cursors for multi-replica Gateways writing concurrently to the same thread + remain a Phase 2 follow-up. +- Graceful shutdown stops new memory work, drains accepted operations, and + bounds closing pooled recorder-owned SDK clients and + `credential_provider.close()` (if defined) within the same + `shutdown_flush_timeout_seconds` budget via a single-flight teardown, without + introducing a new DeerFlow lifecycle or persistent background worker. For deployments where a lost memory update is unacceptable, a durable outbox -is still required. This initial integration does not claim at-least-once -delivery. +is still required. This integration does not claim at-least-once delivery. diff --git a/docs/guide/memory.md b/docs/guide/memory.md index ee55e06275..8b486a1e79 100644 --- a/docs/guide/memory.md +++ b/docs/guide/memory.md @@ -83,9 +83,12 @@ is off by default and does not affect targeted fact updates. DeerFlow also includes an optional `openviking` memory backend. It uses the official `langchain-openviking` package to capture completed turns into stable OpenViking Sessions and recall memory for prompt injection while leaving -DeerMem as the default. The initial integration supports one DeerFlow user with -one credential-bound OpenViking USER API key in `memory.mode: middleware` and -does not inherit arbitrary HTTP headers from `ovcli.conf`. +DeerMem as the default. It runs in `memory.mode: middleware` with either +single-user binding (`owner_user_id` + `api_key_env`) or fail-closed +multi-user / multi-tenant isolation (`user_credentials` or +`credential_provider` with optional `tenant_id` and a bounded `client_pool`) in +OpenViking `api_key` mode, and does not inherit arbitrary HTTP headers from +`ovcli.conf`. See [OpenViking memory backend](../../docs/OPENVIKING.md) for its configuration, behavior, and current boundaries. diff --git a/frontend/src/content/en/application/configuration.mdx b/frontend/src/content/en/application/configuration.mdx index aec70da700..8f4f92a636 100644 --- a/frontend/src/content/en/application/configuration.mdx +++ b/frontend/src/content/en/application/configuration.mdx @@ -313,10 +313,12 @@ memory: ``` The optional `openviking` backend connects to an independent OpenViking server -through `langchain-openviking` and currently supports one DeerFlow user in -`mode: middleware`. Its private configuration uses `base_url`, -`owner_user_id`, `api_key_env`, `failure_policy`, and `retrieval` with an -ordinary OpenViking USER API key instead of the DeerMem fields shown above. See +through `langchain-openviking` in `mode: middleware` instead of using the +DeerMem fields shown above. It supports single-user deployments +(`owner_user_id` + `api_key_env`) as well as fail-closed multi-user and +multi-tenant isolation using per-user OpenViking USER API keys via +`user_credentials` or `credential_provider` (with optional `tenant_id` and +`client_pool`), alongside `base_url`, `failure_policy`, and `retrieval`. See `docs/OPENVIKING.md` in the repository for the complete configuration and Docker startup sequence. diff --git a/frontend/src/content/en/harness/memory.mdx b/frontend/src/content/en/harness/memory.mdx index 7f679e4e94..0587271e47 100644 --- a/frontend/src/content/en/harness/memory.mdx +++ b/frontend/src/content/en/harness/memory.mdx @@ -100,6 +100,8 @@ deermem is the default backend and implements the full contract: OpenViking is a remote memory backend with a crisp responsibility split: **DeerFlow owns capture timing, the recall query, and the transcript cursor; the `langchain-openviking` package owns transport, message conversion, batching, and Session commits.** +Single-user example: + ```yaml memory: enabled: true @@ -119,11 +121,34 @@ memory: max_injection_chars: 12000 ``` +Multi-user / multi-tenant example: + +```yaml +memory: + enabled: true + injection_enabled: true + manager_class: openviking + mode: middleware + backend_config: + base_url: http://openviking:1933 + user_credentials: + alice: + api_key_env: OPENVIKING_API_KEY_ALICE + tenant_id: acme + bob: + api_key_env: OPENVIKING_API_KEY_BOB + tenant_id: globex + # Or use credential_provider (+ credential_provider_config) / host_hooks["credential_provider"] + client_pool: + max_clients: 64 + idle_ttl_seconds: 900.0 +``` + Integration notes: -- **One API key is bound to one DeerFlow owner**; accessing another owner is rejected. Keep the USER key in the server environment (`api_key_env`), never in `config.yaml`. -- **One DeerFlow thread maps to one stable OpenViking Session**; bounded hash-only cursors live under `{storage_path}/openviking/sessions/`. -- This version supports one user with one key in middleware mode; multi-user key provisioning is out of scope. See `docs/OPENVIKING.md` for the full boundary and startup guide. +- **Single-user vs. multi-user isolation in `api_key` mode**: single-user mode binds one OpenViking USER API key (`api_key_env`) to `owner_user_id`. Multi-user mode uses `user_credentials` (`api_key_env` or `api_key`, plus optional `tenant_id`) and/or a dynamic `credential_provider` (`credential_provider` + `credential_provider_config`, or programmatic `host_hooks["credential_provider"]`) with a bounded LRU/TTL `client_pool`. Mutually exclusive with `owner_user_id` / `api_key_env`; unmapped, blank, or revoked users fail closed without falling back to another key or ambient `OPENVIKING_API_KEY`. +- **One DeerFlow thread maps to one stable OpenViking Session** (unscoped requests keep v1 session hashes while `tenant_id` derives disjoint v2 hashes); bounded hash-only local cursors live under `{storage_path}/openviking/sessions/`. +- **Middleware mode only**: `auth_mode: trusted` / `account` headers remain unsupported because OpenViking derives account and user server-side from each USER API key. See `docs/OPENVIKING.md` for the full security boundary, key rotation/revocation, and startup guide. ## Implementing your own memory backend @@ -264,9 +289,12 @@ memory: Set `manager_class: openviking` to send completed turns to an independent OpenViking server and recall its memory through the official -`langchain-openviking` adapter. This first version supports one DeerFlow user -with one OpenViking USER API key in middleware mode; DeerMem remains the -default. +`langchain-openviking` adapter. It supports `memory.mode: middleware` in both +single-user mode (`owner_user_id` + `api_key_env`) and fail-closed multi-user +/ multi-tenant isolation (`user_credentials` or `credential_provider` with +optional `tenant_id` and `client_pool`); DeerMem remains the default. + +Single-user configuration: ```yaml memory: @@ -287,11 +315,38 @@ memory: max_injection_chars: 12000 ``` -Use `owner_user_id: default` when DeerFlow authentication is disabled. Put the -USER key in the server environment, not directly in `config.yaml`. Trusted-mode -account headers, root-key memory access, and multi-user key provisioning are not -part of this version. See `docs/OPENVIKING.md` for the full boundary and startup -guide. +Multi-user / multi-tenant configuration (mutually exclusive with +`owner_user_id` and `api_key_env`): + +```yaml +memory: + enabled: true + injection_enabled: true + manager_class: openviking + mode: middleware + backend_config: + base_url: http://openviking:1933 + user_credentials: + alice: + api_key_env: OPENVIKING_API_KEY_ALICE + tenant_id: acme + bob: + api_key_env: OPENVIKING_API_KEY_BOB + tenant_id: globex + # Or resolve keys dynamically with credential_provider (+ credential_provider_config) + # or programmatic host_hooks["credential_provider"] + client_pool: + max_clients: 64 + idle_ttl_seconds: 900.0 +``` + +Use `owner_user_id: default` when DeerFlow authentication is disabled in +single-user deployments. Put USER keys in the server environment (or resolve +them through `credential_provider`), not directly in `config.yaml`. +Trusted-mode `auth_mode` / `account` headers and root-key memory access remain +unsupported because OpenViking derives `account` and `user` server-side from +each USER API key. See `docs/OPENVIKING.md` for the full security boundary, +session-ID scoping, key rotation/revocation, and startup guide. ## Global vs per-agent memory diff --git a/frontend/src/content/zh/harness/memory.mdx b/frontend/src/content/zh/harness/memory.mdx index 676e069a5e..818e36c80b 100644 --- a/frontend/src/content/zh/harness/memory.mdx +++ b/frontend/src/content/zh/harness/memory.mdx @@ -99,6 +99,8 @@ deermem 是默认后端,完整实现了契约的全部能力: OpenViking 是远程记忆后端,职责边界划分得很清楚:**DeerFlow 负责捕获时机、召回查询和会话游标;`langchain-openviking` 包负责传输、消息转换、批处理与 Session 提交**。 +单用户示例: + ```yaml memory: enabled: true @@ -118,11 +120,34 @@ memory: max_injection_chars: 12000 ``` +多用户 / 多租户隔离示例: + +```yaml +memory: + enabled: true + injection_enabled: true + manager_class: openviking + mode: middleware + backend_config: + base_url: http://openviking:1933 + user_credentials: + alice: + api_key_env: OPENVIKING_API_KEY_ALICE + tenant_id: acme + bob: + api_key_env: OPENVIKING_API_KEY_BOB + tenant_id: globex + # 或使用 credential_provider(+ credential_provider_config)/ host_hooks["credential_provider"] + client_pool: + max_clients: 64 + idle_ttl_seconds: 900.0 +``` + 接入要点: -- **一个 API Key 绑定一个 DeerFlow 拥有者**,访问其他用户会被拒绝;USER Key 放在服务端环境变量(`api_key_env`),不要写进 `config.yaml`。 -- **一个 DeerFlow 线程映射到一个稳定的 OpenViking Session**,会话游标以哈希形式存于 `{storage_path}/openviking/sessions/` 下。 -- 当前版本支持单用户单 Key、middleware 模式;多用户 Key 分发不在本版本范围内。完整边界与启动指南见 `docs/OPENVIKING.md`。 +- **支持 `api_key` 模式下的单用户绑定与多用户 / 多租户隔离**:单用户模式通过 `owner_user_id` + `api_key_env` 将一个 USER API Key 绑定到一个 DeerFlow 拥有者;多用户模式通过 `user_credentials`(每用户 `api_key_env` 或 `api_key`,以及可选 `tenant_id`)或动态 `credential_provider`(`credential_provider` + `credential_provider_config`,或宿主注入 `host_hooks["credential_provider"]`)与有界 LRU/TTL `client_pool` 实现按作用域隔离。多用户配置与 `owner_user_id` / `api_key_env` 互斥,未映射、空白或已吊销的用户一律 fail-closed 拒绝,绝不回退到其他用户的 Key 或环境变量 `OPENVIKING_API_KEY`。 +- **一个 DeerFlow 线程映射到一个稳定的 OpenViking Session**(未配置 `tenant_id` 时保留 v1 会话哈希,配置 `tenant_id` 时生成互相隔离的 v2 哈希),仅含哈希的本地游标存于 `{storage_path}/openviking/sessions/` 下。 +- **仅支持 `memory.mode: middleware`**:不支持 `auth_mode: trusted` / `account` 头(OpenViking 服务端由每个 USER API Key 推导 `account` 与 `user`)。完整安全边界、密钥轮换/吊销与启动指南见 `docs/OPENVIKING.md`。 ## 实现自己的记忆后端 diff --git a/scripts/doctor.py b/scripts/doctor.py index c71f51ab01..454b2e17b5 100644 --- a/scripts/doctor.py +++ b/scripts/doctor.py @@ -485,13 +485,13 @@ def _resolves_to_builtin_openviking(manager_class: str) -> bool: def _memory_backend_config_fix(detail: str) -> str | None: """Remediation matched to the validator's failure modes; None lets the verbatim error speak for itself.""" - if "USER API key is missing; set" in detail: - var = detail.rsplit("set ", 1)[-1].strip().rstrip(".") + if "USER API key is missing" in detail and "; set " in detail: + var = detail.rsplit("; set ", 1)[-1].strip().rstrip(".") return f"Add {var}= to your .env file" if "Unknown OpenViking backend_config fields" in detail: return "Remove the fields named in the error from memory.backend_config, or switch manager_class back" if "trusted mode is no longer supported" in detail: - return "Use a USER API key (api_key_env) and configure owner_user_id instead of auth_mode/account" + return "Use a USER API key and configure owner_user_id, user_credentials, or credential_provider instead of auth_mode/account" if "custom HTTP client fields are no longer supported" in detail: return "Remove the custom HTTP client fields from memory.backend_config" return None