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
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import hashlib
import json
import re
import sys
from typing import TYPE_CHECKING, Any, ClassVar, Literal, Self

Expand Down Expand Up @@ -405,9 +406,13 @@ async def _redis_search(
await self._ensure_index()
self._validate_filters()

q = (text or "").strip()
if not q:
if not (text or "").strip():
raise IntegrationInvalidRequestException("text_search() requires non-empty text")
# TextQuery escapes each term itself, so a backslash added here gets escaped again
# and the char stays bare. Drop the syntax chars its escaper misses instead.
q = " ".join(re.sub(r"[|?`]", " ", text).split())
if not q:
return []
num_results = max(int(num_results or 10), 1)

combined_filter = self._build_filter_from_dict({
Expand Down
76 changes: 76 additions & 0 deletions python/packages/redis/tests/test_context_provider_edges.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,82 @@ async def test_redis_search_combines_explicit_filter_expression(
mock_index.query.assert_awaited_once()


@pytest.mark.parametrize(
("message", "terms"),
[
("Why ?", "(why)"),
("ps aux | grep python", "(ps | aux | grep | python)"),
("Is it A | B?", "(is | it | a | b)"),
("Run ` ls ` please", "(run | ls | please)"),
("| name | age |", "(name | age)"),
("see e.g. v1.2", r"(see | e\.g\. | v1\.2)"),
],
)
async def test_redis_search_drops_query_syntax_in_user_text(
message: str,
terms: str,
mock_index: AsyncMock,
patch_index: MagicMock, # noqa: ARG001
) -> None:
"""User prose reaches RediSearch as plain terms, not as query syntax (#10002).

A bare `|`, `?` or backtick in a message previously turned the generated query
string into malformed grammar (`@content:(ps | aux | | | grep | python)`), and
the syntax error failed the whole agent run. redisvl escapes every term itself,
so nothing here may add a backslash of its own (it would be escaped again).
"""
provider = RedisContextProvider(source_id="ctx", user_id="user-1")

with patch.object(provider, "_ensure_index", AsyncMock()):
await provider._redis_search(text=message)

query = mock_index.query.await_args.args[0]
query_string = query.query_string()
assert f"@content:{terms}" in query_string
assert "\\\\" not in query_string


async def test_redis_search_only_syntax_chars_returns_no_results(
mock_index: AsyncMock,
patch_index: MagicMock, # noqa: ARG001
) -> None:
"""A message made only of query syntax has no terms to search for."""
provider = RedisContextProvider(source_id="ctx", user_id="user-1")

with patch.object(provider, "_ensure_index", AsyncMock()):
assert await provider._redis_search(text=" ? | ` ") == []

mock_index.query.assert_not_awaited()


async def test_redis_search_drops_syntax_for_hybrid_query(
mock_index: AsyncMock,
patch_index: MagicMock, # noqa: ARG001
) -> None:
"""The hybrid vector path gets the same cleaned text."""
mock_vectorizer = MagicMock(spec=BaseVectorizer)
mock_vectorizer.dims = 128
mock_vectorizer.dtype = "float32"
mock_vectorizer.aembed = AsyncMock(return_value=[0.1] * 128)

provider = RedisContextProvider(
source_id="ctx",
user_id="u1",
redis_vectorizer=mock_vectorizer,
vector_field_name="embedding",
)

with (
patch.object(provider, "_ensure_index", AsyncMock()),
patch("agent_framework_redis._context_provider.AggregateHybridQuery") as hybrid_query,
):
hybrid_query.return_value = MagicMock()
await provider._redis_search(text="ps aux | grep python")

assert hybrid_query.call_args.kwargs["text"] == "ps aux grep python"
mock_index.query.assert_awaited_once()


async def test_search_all_collects_paginated_batches(
mock_index: AsyncMock,
patch_index: MagicMock, # noqa: ARG001
Expand Down
Loading