Skip to content
Draft
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
2 changes: 1 addition & 1 deletion docs/concepts/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ Two things about filters are easy to conflate:

For that reason a profile accepts only the **object** form of a filter from the model. A raw filter string is rejected both by the advertised schema and by the tool itself, because strings bypass the DSL's field validation and have no safe composition with a locked expression.

Structure is only half of it: the nesting guarantee holds only while every filter *value* stays inside its own clause. Text `eq`/`ne` values are handled by the `Text` filter itself, which renders them as a quoted phrase with any `"` or `\` replaced by a space, so a parenthesis or a `|` the value carries is literal text rather than syntax. Text `like` values are patterns, so the library leaves them raw and this boundary escapes them instead — the delimiters that would close the clause are escaped, the pattern metacharacters are not. Tag values have their delimiters escaped and numeric values are type-checked. A caller filter that still renders as something able to break out is refused rather than combined.
Structure is only half of it: the nesting guarantee holds only while every filter *value* stays inside its own clause. Text `eq`/`ne` values are handled by the `Text` filter itself, which renders them as a quoted phrase that no `"` or `\` in the value can close early, so a parenthesis or a `|` the value carries is literal text rather than syntax. Text `like` values are patterns, so the library leaves them raw and this boundary escapes them instead — the delimiters that would close the clause are escaped, the pattern metacharacters are not. Tag values have their delimiters escaped and numeric values are type-checked. A caller filter that still renders as something able to break out is refused rather than combined.

Profiles resolve to a built-in call and nothing more, so they inherit the concurrency cap, request timeout, read-only policy, auth scoping, and error mapping already applied to `search-records`.

Expand Down
8 changes: 4 additions & 4 deletions docs/user_guide/02_complex_filtering.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -695,10 +695,10 @@
"\n",
"Text filters are filters that are applied to text fields. These filters are applied to the entire text field. For example, if you have a text field that contains the text \"The quick brown fox jumps over the lazy dog\", a text filter of \"quick\" will match this text field.\n",
"\n",
"A value passed to `==` or `!=` is matched as a literal phrase, so a `\"` or a\n",
"`\\` inside it is insignificant rather than interpreted. The `%` operator is the\n",
"opposite: its value is a raw pattern, so pass it only patterns your own code\n",
"composes."
"A value passed to `==` or `!=` is matched as a literal phrase, read the way the\n",
"document's own text was indexed, so a `\"` or a `\\` inside it is never interpreted\n",
"as query syntax. The `%` operator is the opposite: its value is a raw pattern, so\n",
"pass it only patterns your own code composes."
]
},
{
Expand Down
10 changes: 8 additions & 2 deletions redisvl/mcp/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from redisvl.schema import IndexSchema
from redisvl.utils.token_escaper import TokenEscaper

# `Text` neutralizes its own eq/ne values (see `_PHRASE_UNSAFE` in
# `Text` makes its own eq/ne values phrase-safe (see `_phrase_value` in
# `redisvl.query.filter`), so this boundary must not treat them again -- doubled
# handling mangles ordinary values. `like` below is the exception, because the
# library leaves `%` raw by design.
Expand Down Expand Up @@ -125,7 +125,13 @@ def _parse_expression(value: dict[str, Any], schema: IndexSchema) -> FilterExpre
if field.type == "tag":
return _parse_tag_expression(field_name, normalized_op, operand)
if field.type == "text":
return _parse_text_expression(field_name, normalized_op, operand)
try:
return _parse_text_expression(field_name, normalized_op, operand)
except ValueError as exc:
# `Text` refuses a phrase value that leaves no term to match.
raise RedisVLMCPError(
str(exc), code=MCPErrorCode.INVALID_FILTER, retryable=False
) from exc
if field.type == "numeric":
return _parse_numeric_expression(field_name, normalized_op, operand)

Expand Down
54 changes: 34 additions & 20 deletions redisvl/mcp/tools/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from redisvl.mcp.errors import MCPErrorCode, RedisVLMCPError, map_exception
from redisvl.mcp.filters import parse_filter
from redisvl.query import AggregateHybridQuery, HybridQuery, TextQuery, VectorQuery
from redisvl.query.filter import FilterExpression
from redisvl.query.filter import _PHRASE_ESCAPABLE, FilterExpression
from redisvl.schema import IndexSchema

DEFAULT_SEARCH_DESCRIPTION = "Search records in the configured Redis index."
Expand Down Expand Up @@ -402,6 +402,28 @@ def _find_unescaped(
return None


def _phrase_end(rendered: str, position: int) -> int | None:
"""Return the index of the quote closing the phrase opened at `position`.

Returns None when the phrase holds anything that could make the parser end
it elsewhere: a backslash escaping a character outside `_PHRASE_ESCAPABLE`,
a backslash right before the closing quote, or no closing quote at all.
These are the shapes `redisvl.query.filter._phrase_value` never renders.
"""
position += 1
while position < len(rendered):
character = rendered[position]
if character == "\\":
if rendered[position + 1 : position + 2] not in _PHRASE_ESCAPABLE:
return None
position += 2
continue
if character == '"':
return None if rendered[position - 1] == "\\" else position
position += 1
return None


def _reject_escapable_filter(caller: FilterExpression) -> None:
"""Refuse a caller filter whose rendering could break out of a locked AND.

Expand All @@ -413,11 +435,11 @@ def _reject_escapable_filter(caller: FilterExpression) -> None:
unlocked tool relies on those two layers alone.

The quoted-phrase skip below assumes a rendering's quotes arrive in
delimiting pairs, which holds for every value the DSL can render: ``==`` and
``!=`` quote the value and take any quote it carried out first, and ``Tag``
and ``like`` values arrive with theirs escaped, outside any phrase. If that
ever stops holding, the skip finds no closing quote and refuses the filter,
so the failure is loud rather than silent.
delimiting pairs, which holds for every value the DSL can render: ``==``
and ``!=`` quote the value after `_phrase_value` has made its body safe,
and ``Tag`` and ``like`` values arrive with their quotes escaped, outside any
phrase. A rendering that breaks the assumption is refused, so the failure
is loud rather than silent.
"""
# Braces scope as much as parens do: a tag clause holds its alternatives in
# braces, so `@category:{sports|health}` is one scoped clause rather than a
Expand Down Expand Up @@ -446,17 +468,9 @@ def _reject_escapable_filter(caller: FilterExpression) -> None:
# A quoted phrase is a literal, so nothing inside it is structure and
# a `|` inside it is a separator rather than a union. Unlike the range
# span below, the whole phrase can therefore be skipped.
#
# The scan deliberately does not treat `\` as escaping the closing
# quote, because RediSearch does not either: `@f:("x\")` closes the
# phrase and yields the term `x\`. Honouring the escape would read
# that as unterminated and refuse an ordinary value ending in a
# backslash, a Windows path among them. Nothing is given up, since a
# value cannot contribute a quote of its own -- `Text` replaces it,
# and `Tag` and `like` escape theirs outside any phrase.
end = rendered.find('"', position + 1)
if end == -1:
# Unterminated phrase: the remainder is unparsable.
# Refuse a phrase whose end is in doubt.
end = _phrase_end(rendered, position)
if end is None:
escaped = True
break
position = end + 1
Expand Down Expand Up @@ -522,9 +536,9 @@ def merge_locked_filter(
The locked expression always applies, so a caller can only narrow within it
and never widen past it. That rests on two things: the caller's expression
rendering nested inside the AND, and every value staying inside its own
clause. ``Text`` removes the quote that delimits a phrase, ``Tag`` escapes
the braces that delimit a tag clause, numeric values are type-checked, and
``like`` patterns are escaped at the filter boundary.
clause. ``Text`` renders no phrase whose closing quote a value can move,
``Tag`` escapes the braces that delimit a tag clause, numeric values are
type-checked, and ``like`` patterns are escaped at the filter boundary.
"""
if locked is None:
return caller
Expand Down
120 changes: 99 additions & 21 deletions redisvl/query/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,29 +737,100 @@ def __str__(self) -> str:
return self.OPERATOR_MAP[self._operator] % (self._field, self._value)


# A double quote is the only character that can terminate a quoted phrase, so it
# is the only one that needs replacing. (A trailing backslash does not terminate
# one either -- `@f:("x\")` parses as the term `x\`.)
#
# Replaced rather than escaped, because escaping is symmetric: a backslash joins
# the separator into the term, so `@f:("say \"hi\" now")` asks for a term with a
# quote in it, and RedisVL writes documents unescaped. On `==` that matches
# nothing, and on `!=` the unmatchable phrase makes the negation match
# everything. A space is what the tokenizer left at that position anyway.
_PHRASE_UNSAFE = re.compile(r'"')
# The characters a backslash may escape inside a quoted phrase: the term
# separators, whose escape the query parser and the indexer both read as joining
# the character into the term, and the backslash itself. The quote is left out
# because escaping one is what moves a phrase's end, and the tab because the
# indexer drops an escaped tab. The MCP filter backstop accepts a phrase only if
# its escapes come from this set, so the two must change together.
_PHRASE_ESCAPABLE = frozenset(" !#$%&'()*+,-./:;<=>?@[\\]^`{|}~")

# Control characters, which the indexer drops from a term. The tab separates
# terms instead, so it is left alone unless escaped.
_PHRASE_DROPPED = frozenset(map(chr, [*range(0x09), *range(0x0A, 0x20), 0x7F]))

# What the indexer drops together with the backslash escaping it.
_PHRASE_UNESCAPED = _PHRASE_DROPPED | {"\t"}

# What the indexer splits terms at, among the characters a rendered phrase body
# can still hold unescaped.
_TERM_SEPARATORS = (_PHRASE_ESCAPABLE - {"\\"}) | {"\t"}


def _phrase_value(value: str) -> str:
"""Return `value` as the body of a quoted phrase that ends where it appears to.

Each character goes the way the indexer took it, so the phrase asks for the
terms the document stored:

- A backslash before a character in `_PHRASE_ESCAPABLE` stays, since the
parser joins that pair into the term as the indexer did (`foo\\-bar`
indexes `foo-bar`).
- A control character goes, with any backslash before it, and so does an
escaped tab.
- Any other backslash goes, as the indexer dropped it where the parser
would keep it (`C:\\Users\\bob` indexes `usersbob`).
- A `"` or a bare `$` becomes a space: the indexer separated terms at each,
where the parser would end the phrase at a quote and keep a `$` inside
the term.

Some stored text stays out of reach. An escaped quote cannot be carried,
and the parser reads an escaped backslash differently from the indexer:
before `_` it drops it, and it reads a run of them as one.

A body ending in a backslash makes the parser pair the closing quote with a
later one, so a space follows it. (The membership tests rely on an empty
slice being in neither set.)

Raises:
ValueError: If `value` leaves no term, such as one of nothing but
separators, since the phrase would then match no document with
`==` and every document with `!=`.
"""
body = []
position = 0
while position < len(value):
character = value[position]
if character == "\\":
following = value[position + 1 : position + 2]
if following in _PHRASE_ESCAPABLE:
body.append(character + following)
if following in _PHRASE_ESCAPABLE or following in _PHRASE_UNESCAPED:
position += 2
continue
elif character in '"$':
body.append(" ")
elif character not in _PHRASE_DROPPED:
body.append(character)
position += 1

rendered = "".join(body)
# A kept escape pair is a term of its own; otherwise a term needs a
# character the indexer does not separate at.
if "\\" not in rendered and all(c in _TERM_SEPARATORS for c in rendered):
raise ValueError(
f"Text value {value!r} leaves no searchable term to match as a phrase"
)
if rendered.endswith("\\"):
rendered += " "
return rendered


class Text(FilterField):
"""A Text is a FilterField representing a text field in a Redis index.

Note:
``==`` and ``!=`` match the value as a quoted phrase. Any ``"`` in the
value becomes a space first, so the value cannot close that phrase; a
quote already separates tokens at index time, so this matches the same
documents that escaping it never could. A value of nothing but quotes
therefore becomes an empty phrase, which ``==`` matches no document
against. ``%`` is the pattern operator and interpolates its value
untouched.
``==`` and ``!=`` match the value as a literal phrase, read the way
the document's own text was indexed: a ``"`` separates terms, and a
``\\`` joins what follows it into the term, so ``C:\\Users\\bob`` and
``foo\\-bar`` each match a document holding that text. Stored text
with an escaped quote (``\\"``), or with an escaped backslash before
``_`` or before another escaped backslash, cannot be matched this way.
A value that leaves no term, such as one of nothing but punctuation or
whitespace, raises ``ValueError``, since it could match no document
with ``==`` and would match every document with ``!=``. Stopwords are
not checked, as they depend on the index. ``%`` is the pattern
operator and interpolates its value untouched.

An empty string raises ``ValueError``; pass ``None`` for no constraint.
"""
Expand Down Expand Up @@ -788,6 +859,8 @@ def _set_value(
val_type: type | tuple[type, ...],
operator: FilterOperator,
):
"""Refuse a value no filter can ask for before storing it, so that
rendering a stored value never raises."""
if isinstance(val, str) and not val:
# `@f:("")` is how RediSearch asks for an empty string, but after a
# TAG clause the server checks it against that tag field's
Expand All @@ -800,6 +873,8 @@ def _set_value(
f"{self.__class__.__name__} value must be a non-empty string; "
"pass None for no constraint"
)
if isinstance(val, str) and operator not in self._RAW_VALUE_OPERATORS:
_phrase_value(val)
super()._set_value(val, val_type, operator)

@check_operator_misuse
Expand All @@ -810,6 +885,9 @@ def __eq__(self, other: str) -> "FilterExpression":
Args:
other (str): The text value to filter on.

Raises:
ValueError: If the value leaves no searchable term.

.. code-block:: python

from redisvl.query.filter import Text
Expand All @@ -829,6 +907,9 @@ def __ne__(self, other: str) -> "FilterExpression":
Args:
other (str): The text value to filter on.

Raises:
ValueError: If the value leaves no searchable term.

.. code-block:: python

from redisvl.query.filter import Text
Expand Down Expand Up @@ -875,10 +956,7 @@ def __str__(self) -> str:

value = self._value
if self._operator not in self._RAW_VALUE_OPERATORS:
# Substituting a space never empties the value, so the phrase always
# holds at least one character and never trips the `INDEXEMPTY`
# error that a literal `@field:("")` raises.
value = _PHRASE_UNSAFE.sub(" ", value)
value = _phrase_value(value)

return self.OPERATOR_MAP[self._operator] % (
self._field,
Expand Down
56 changes: 56 additions & 0 deletions tests/integration/test_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,18 @@ def test_filters(index, query, sample_datetimes):
t = Text("description") != 'high stress,"'
search(query, index, t, 6)

# Backslashes with a phrase after them. Left raw, one makes the parser pair
# the first phrase's closing quote with the second's opening one, and the
# re-paired query silently matches nothing. The one inside `engi\neer` is
# dropped rather than splitting the term, or that phrase matches nothing.
t = (Text("job") == "engi\\neer\\") | (Text("job") == "doctor\\")
search(query, index, t, 4)

# A kept escape pair at the end of a phrase is spaced off its closing quote,
# which only Redis can confirm: unspaced, the next phrase is a syntax error.
t = (Text("job") == "engineer\\\\") | (Text("job") == "doctor")
search(query, index, t, 2)

# `None` is no constraint; an empty string is refused (see the unit tests)
t = Text("job") % None
search(query, index, t, 7)
Expand Down Expand Up @@ -554,6 +566,50 @@ def test_filters(index, query, sample_datetimes):
search(query, index, ts, 3)


@pytest.fixture
def phrase_index(client, worker_id):
index = SearchIndex.from_dict(
{
"index": {
"name": f"phrase_index_{worker_id}",
"prefix": f"phrase_{worker_id}",
"storage_type": "hash",
},
"fields": [{"name": "body", "type": "text"}],
},
redis_client=client,
)
index.create(overwrite=True, drop=True)
yield index
index.delete(drop=True)


@pytest.mark.parametrize(
"stored, neighbour",
[
# An escaped separator, which the indexer joins into one term.
("foo\\-bar", "foo bar"),
# Escaped letters, whose backslashes the indexer drops.
("C:\\Users\\bob", "C: Users bob"),
# A control character, which the indexer drops.
("hello world\nnext", "hello world next"),
# A bare `$`, where the indexer splits terms and the parser does not.
("price $100", "price100"),
],
)
def test_text_phrase_matches_the_document_holding_it(phrase_index, stored, neighbour):
# The neighbour holds the terms a phrase gets if it misreads the one
# character that differs, so a misread finds it instead of the original.
phrase_index.load([{"body": stored}, {"body": neighbour}])

def bodies(expression):
query = FilterQuery(expression, return_fields=["body"])
return [doc["body"] for doc in phrase_index.query(query)]

assert bodies(Text("body") == stored) == [stored]
assert bodies(Text("body") != stored) == [neighbour]


def test_manual_string_filters(index, query):
# Simple Tag Filter
t = "@credit_score:{high}"
Expand Down
Loading
Loading