Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion src/surreal_memory/engine/encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

from __future__ import annotations

import asyncio
import logging
import os
import re
from dataclasses import dataclass, field
from datetime import datetime
Expand Down Expand Up @@ -47,6 +49,27 @@

logger = logging.getLogger(__name__)


def _inline_embed_timeout() -> float:
"""Seconds the write path will wait for inline embeddings before giving up.

Default 10s: comfortably above a local endpoint (bge-m3 via llamastash answers
in ~15 ms) and comfortably below the 30s tool-call cap that MCP hosts such as
Claude Code and Claude Desktop enforce, so a slow provider can never turn a
successful write into a client-side timeout. Override with
``SURREAL_MEMORY_INLINE_EMBED_TIMEOUT`` (<= 0 disables the bound).
"""
raw = os.environ.get("SURREAL_MEMORY_INLINE_EMBED_TIMEOUT", "").strip()
if not raw:
return 10.0
try:
value = float(raw)
except ValueError:
logger.warning("Invalid SURREAL_MEMORY_INLINE_EMBED_TIMEOUT=%r — falling back to 10s", raw)
return 10.0
return value if value > 0 else 0.0


if TYPE_CHECKING:
from surreal_memory.core.brain import BrainConfig
from surreal_memory.core.fiber import Fiber
Expand Down Expand Up @@ -499,7 +522,27 @@ async def _embed_created_neurons(self, ctx: PipelineContext) -> None:

try:
provider = _create_provider(self._config, task_type="RETRIEVAL_DOCUMENT")
vectors = await provider.embed_batch([n.content for n in candidates])
# Bound the wait. This method is fail-soft by design — "no provider"
# already means "keyword-only memory, no error" — but an *unavailable*
# provider and a *slow* one used to be treated differently: a remote or
# rate-limited endpoint blocked the write until its own timeout, pushing
# `smem_remember` past the 30s tool-call cap MCP hosts impose. The write
# itself had already succeeded, so the caller saw a timeout and could not
# tell whether the memory landed — the exact failure this tool exists to
# prevent. A local endpoint (bge-m3 via llamastash, ~15 ms) is nowhere
# near this budget; anything that is pays with a slightly later vector
# instead of a lost write. `smem reindex` back-fills.
budget = _inline_embed_timeout()
embed = provider.embed_batch([n.content for n in candidates])
vectors = await (asyncio.wait_for(embed, timeout=budget) if budget else embed)
except TimeoutError:
logger.warning(
"Inline embedding exceeded %.0fs for %d neuron(s) — memory saved "
"keyword-only; run `smem reindex` to back-fill the vectors.",
_inline_embed_timeout(),
len(candidates),
)
return
except Exception:
logger.debug("Inline embedding skipped (provider unavailable)", exc_info=True)
return
Expand Down
106 changes: 106 additions & 0 deletions tests/unit/test_inline_embed_timeout.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
"""Regression test for #79: a slow embedding provider must not fail the write.

``_embed_created_neurons`` runs inside the write path so a fresh memory is
semantically recallable immediately. It was already fail-soft about a *missing*
provider ("keyword-only memory, no error"), but not about a *slow* one: a remote
or rate-limited endpoint blocked until its own timeout, pushing ``smem_remember``
past the 30s tool-call cap MCP hosts impose. The write had already succeeded, so
the caller saw a timeout and could not tell whether the memory landed — the exact
loss this tool exists to prevent.

The bound turns "slow provider" into "vector arrives later" rather than
"caller cannot tell what happened".
"""

from __future__ import annotations

import asyncio
from typing import Any

import pytest

from surreal_memory.engine.encoder import MemoryEncoder, _inline_embed_timeout


class TestInlineEmbedTimeoutConfig:
def test_default_sits_under_the_mcp_tool_cap(self, monkeypatch: Any) -> None:
"""Must be well below the 30s cap, or the bound does not solve #79."""
monkeypatch.delenv("SURREAL_MEMORY_INLINE_EMBED_TIMEOUT", raising=False)
assert 0 < _inline_embed_timeout() < 30.0

def test_env_override_is_honoured(self, monkeypatch: Any) -> None:
monkeypatch.setenv("SURREAL_MEMORY_INLINE_EMBED_TIMEOUT", "2.5")
assert _inline_embed_timeout() == 2.5

def test_non_positive_disables_the_bound(self, monkeypatch: Any) -> None:
"""Escape hatch for anyone who prefers the old blocking behaviour."""
monkeypatch.setenv("SURREAL_MEMORY_INLINE_EMBED_TIMEOUT", "0")
assert _inline_embed_timeout() == 0.0

def test_garbage_falls_back_instead_of_raising(self, monkeypatch: Any) -> None:
"""A typo in the env must not take down every write."""
monkeypatch.setenv("SURREAL_MEMORY_INLINE_EMBED_TIMEOUT", "soon")
assert _inline_embed_timeout() == 10.0


class _Neuron:
"""Minimal stand-in for a created neuron."""

def __init__(self, nid: str) -> None:
from surreal_memory.core.neuron import NeuronType

self.id = nid
self.content = "alpha content"
self.metadata: dict[str, Any] = {}
self.ephemeral = False
self.type = NeuronType.CONCEPT


class _Ctx:
def __init__(self, neurons: list[Any]) -> None:
self.neurons_created = neurons
self.anchor_neuron = None


class _HangingProvider:
"""Never answers — stands in for a rate-limited / cold-start remote endpoint."""

async def embed_batch(self, _texts: list[str]) -> list[list[float]]:
await asyncio.sleep(3600)
raise AssertionError("unreachable")


@pytest.mark.asyncio
async def test_slow_provider_does_not_block_the_write(monkeypatch: Any) -> None:
"""The write path returns promptly; the memory is simply left keyword-only."""
monkeypatch.setenv("SURREAL_MEMORY_INLINE_EMBED_TIMEOUT", "0.2")
monkeypatch.setattr(
"surreal_memory.engine.semantic_discovery._effective_embedding",
lambda _cfg: (True, None, None),
raising=True,
)
monkeypatch.setattr(
"surreal_memory.engine.semantic_discovery._create_provider",
lambda _cfg, task_type=None: _HangingProvider(),
raising=True,
)

updates: list[Any] = []

class _Storage:
async def update_neuron(self, neuron: Any) -> None:
updates.append(neuron)

encoder = MemoryEncoder.__new__(MemoryEncoder)
encoder._storage = _Storage() # type: ignore[attr-defined]
encoder._config = object() # type: ignore[attr-defined]

ctx = _Ctx([_Neuron("n1")])

# Generous ceiling: the point is that it returns on the 0.2s budget, not on
# the provider's own (here: never).
await asyncio.wait_for(encoder._embed_created_neurons(ctx), timeout=10)

# Fail-soft: no vector was written, and crucially no exception propagated —
# the neuron itself was already persisted upstream.
assert updates == []
Loading