From 785b085d8db16207d604da3a5e807942be09af10 Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Tue, 13 Oct 2026 17:26:35 +0200 Subject: [PATCH 1/8] fix: neutralise backslashes in Text phrase values A backslash anywhere before a phrase's closing quote makes RediSearch pair that quote with a later one, even when the backslash is itself escaped. Two `Text ==` values ending in a backslash therefore re-pair silently, and the MCP locked-filter backstop, which ended a phrase at the next quote, disagreed with the parser about which characters were live syntax. `Text` now replaces `\` in eq/ne phrases with a space, as it already did for `"`, and the backstop refuses any phrase that still holds a backslash. Resolves FDE-70. --- redisvl/mcp/tools/search.py | 33 +++++++++---------- redisvl/query/filter.py | 24 +++++++------- .../test_mcp/test_claim_injection.py | 7 ++++ tests/integration/test_query.py | 6 ++++ tests/unit/test_filter.py | 16 +++++---- tests/unit/test_mcp/test_filters.py | 21 +++++++----- 6 files changed, 62 insertions(+), 45 deletions(-) diff --git a/redisvl/mcp/tools/search.py b/redisvl/mcp/tools/search.py index 556521b08..ee4b22649 100644 --- a/redisvl/mcp/tools/search.py +++ b/redisvl/mcp/tools/search.py @@ -413,11 +413,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 with no backslash between them, which holds for every + value the DSL can render: ``==`` and ``!=`` quote the value and take any + quote or backslash it carried out first, and ``Tag`` and ``like`` values + arrive with theirs escaped, outside any phrase. A rendering that breaks + either 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 @@ -447,16 +447,14 @@ def _reject_escapable_filter(caller: FilterExpression) -> None: # 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. + # That skip is sound only while this scan and RediSearch agree on + # where the phrase ends. A backslash anywhere before the closing + # quote breaks the agreement: the parser pairs that quote with a + # later one, even when the backslash is itself escaped. `Text` + # replaces backslashes in its phrases, so one here means a value + # reached the phrase raw. end = rendered.find('"', position + 1) - if end == -1: - # Unterminated phrase: the remainder is unparsable. + if end == -1 or rendered.find("\\", position + 1, end) != -1: escaped = True break position = end + 1 @@ -522,9 +520,10 @@ 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`` removes the quotes and backslashes that decide where a + phrase ends, ``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 diff --git a/redisvl/query/filter.py b/redisvl/query/filter.py index 6411bd567..710f67c82 100644 --- a/redisvl/query/filter.py +++ b/redisvl/query/filter.py @@ -701,26 +701,26 @@ 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\`.) +# Either character can move a phrase's closing quote: a `"` ends the phrase +# early, and a `\` anywhere before the closing quote makes the parser pair that +# quote with a later one, even when the backslash is itself escaped. # # 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 next character 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. The cost is a document whose text holds a deliberate escape, such +# as `foo\-bar`: it indexed the joined term, which a phrase can no longer ask for. +_PHRASE_UNSAFE = re.compile(r'["\\]') 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 + ``==`` and ``!=`` match the value as a quoted phrase. Any ``"`` or + ``\\`` in the value becomes a space first, so the value cannot move + where that phrase ends. A value of nothing but those characters therefore becomes an empty phrase, which ``==`` matches no document against. ``%`` is the pattern operator and interpolates its value untouched. diff --git a/tests/integration/test_mcp/test_claim_injection.py b/tests/integration/test_mcp/test_claim_injection.py index cf936cf25..d466204f9 100644 --- a/tests/integration/test_mcp/test_claim_injection.py +++ b/tests/integration/test_mcp/test_claim_injection.py @@ -216,6 +216,13 @@ async def test_a_pipe_in_the_claim_is_one_identifier_not_a_union( ["acme", "acme"], id="or-widening", ), + # Each phrase ends in a backslash with another phrase after it, the shape + # that shifts the parser's quote pairing when the backslash reaches it. + pytest.param( + {"field": "content", "op": "in", "value": ["policy\\", "window\\"]}, + ["acme", "acme"], + id="backslash-phrases", + ), pytest.param( {"not": {"field": "org_id", "op": "eq", "value": "acme"}}, [], diff --git a/tests/integration/test_query.py b/tests/integration/test_query.py index 8516d2260..ebc1f3d02 100644 --- a/tests/integration/test_query.py +++ b/tests/integration/test_query.py @@ -468,6 +468,12 @@ def test_filters(index, query, sample_datetimes): t = Text("description") != 'high stress,"' search(query, index, t, 6) + # Values ending in a backslash, with a quote after each one. Left raw, the + # backslash makes the parser pair the first phrase's closing quote with the + # second's opening one, and the re-paired query silently matches nothing. + t = (Text("job") == "engineer\\") | (Text("job") == "doctor\\") + search(query, index, t, 4) + # Test empty filters t = Text("job") % "" search(query, index, t, 7) diff --git a/tests/unit/test_filter.py b/tests/unit/test_filter.py index 8377e9f43..7d98170ce 100644 --- a/tests/unit/test_filter.py +++ b/tests/unit/test_filter.py @@ -329,12 +329,13 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): ("__eq__", '"', '@text_field:(" ")'), ("__ne__", '""', '(-@text_field:" ")'), ("__eq__", " ", '@text_field:(" ")'), - # Everything else survives untouched, the backslash included: escaping is - # symmetric, so a document written with one indexes the joined term and - # only an equally escaped query finds it. Replacing any of these would ask - # for a term no document stored -- a silent zero-hit failure. These rows - # fail if a single extra character joins the pattern. - ("__eq__", "trailing\\", '@text_field:("trailing\\")'), + # A backslash before the closing quote moves where the parser ends the + # phrase, so it goes the same way as a quote. + ("__eq__", "trailing\\", '@text_field:("trailing ")'), + ("__ne__", "C:\\Users\\", '(-@text_field:"C: Users ")'), + # Everything else survives untouched. Replacing any of it would ask for a + # term no document stored -- a silent zero-hit failure. This row fails if + # a single extra character joins the pattern. ( "__eq__", "e-mail, 50% off (C++) @ user@x.com O'Brien 3.5", @@ -364,7 +365,8 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): "eq_quotes_only", "ne_quotes_only", "eq_whitespace_only", - "eq_backslash_untouched", + "eq_backslash_neutralized", + "ne_backslash_neutralized", "eq_punctuation_preserved", "like_raw_by_design", ], diff --git a/tests/unit/test_mcp/test_filters.py b/tests/unit/test_mcp/test_filters.py index 033d52fdd..6b15525b6 100644 --- a/tests/unit/test_mcp/test_filters.py +++ b/tests/unit/test_mcp/test_filters.py @@ -300,6 +300,16 @@ def test_merge_locked_filter_ands_a_multi_value_tag_in_caller_filter(): # Balanced parens, so only the phrase branch can refuse this: skipping to # end-of-string instead would swallow the injected union. ("unterminated phrase", '@content:"unterminated | @category:{secret}'), + # A backslash before a phrase's closing quote makes RediSearch pair that + # quote with a later one, even when the backslash is itself escaped, so + # this scan and the parser would disagree about what is phrase and what + # is syntax. Both templates, since each renders its own quote. + ("backslash in an eq phrase", '@content:("trailing\\")'), + ("backslash in a ne phrase", '(-@content:"C:\\Users\\")'), + ( + "escaped backslash before a phrase quote", + '@content:("a\\\\") | @category:{secret} @content:("b")', + ), ], ) def test_merge_locked_filter_refuses_a_caller_rendering_that_could_escape( @@ -338,9 +348,8 @@ def test_merge_locked_filter_refuses_a_caller_rendering_that_could_escape( "unbalanced bracket in a value", {"field": "content", "op": "eq", "value": "a[b"}, ), - # Reported by review: a value ending in a backslash sits immediately - # before the template's closing quote, and an escape-honouring phrase - # scan reads the pair as one and refuses the filter. + # The backstop refuses a backslash inside a phrase, so this passes only + # because `Text` replaces it before rendering. ( "value ending in a backslash", {"field": "content", "op": "eq", "value": "C:\\Users\\"}, @@ -408,12 +417,6 @@ def test_merge_locked_filter_returns_each_side_unchanged_when_the_other_is_absen # end. Unbounded it reads this as a union hidden in the range and # refuses, and it costs the whole remaining string on every `[`. ("pipe after a range span", "(@rating:[4 5] | @category:{sports})"), - # RediSearch closes a phrase at `\"` rather than reading it as an escape, - # so the phrase scan must not honour the escape either. Honouring it - # reads these as unterminated and refuses an ordinary value ending in a - # backslash. Both templates, since each renders its own quote. - ("trailing backslash on eq", '@content:("trailing\\")'), - ("trailing backslash on ne", '(-@content:"C:\\Users\\")'), ], ) def test_merge_locked_filter_accepts_a_legitimate_rendering(label, rendered): From aaea11bb3119ca0844e2618ed16b713cb0492c10 Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Tue, 13 Oct 2026 17:59:30 +0200 Subject: [PATCH 2/8] fix: drop backslashes from Text phrase values rather than spacing them The tokenizer drops a backslash into the term around it, so `C:\Users\bob` indexes `usersbob`. Replacing the backslash with a space asked for terms no document stored; deleting it matches what was indexed. A value of nothing but backslashes becomes a single space, since an empty phrase raises INDEXEMPTY. Behaviour change: `==`/`!=` no longer match text stored with a deliberate escape before a separator or another backslash, such as `foo\-bar`. Also tightens the backstop's refuse rows (a backslash mid-phrase, and an escaped one that hides a union from a quote-pairing scan), drops a tenant-injection case that tested recall rather than confinement, and de-duplicates the comments. --- docs/user_guide/02_complex_filtering.ipynb | 7 ++-- redisvl/mcp/filters.py | 2 +- redisvl/mcp/tools/search.py | 15 +++---- redisvl/query/filter.py | 41 +++++++++---------- .../test_mcp/test_claim_injection.py | 7 ---- tests/integration/test_query.py | 9 ++-- tests/unit/test_filter.py | 9 ++-- tests/unit/test_mcp/test_filters.py | 10 ++--- 8 files changed, 46 insertions(+), 54 deletions(-) diff --git a/docs/user_guide/02_complex_filtering.ipynb b/docs/user_guide/02_complex_filtering.ipynb index 1805b7d42..3dc2ff0ff 100644 --- a/docs/user_guide/02_complex_filtering.ipynb +++ b/docs/user_guide/02_complex_filtering.ipynb @@ -694,9 +694,10 @@ "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." + "`\\` inside it is insignificant rather than interpreted, which means text stored\n", + "with a deliberate escape, such as `foo\\-bar`, is not matched. The `%` operator\n", + "is the opposite: its value is a raw pattern, so pass it only patterns your own\n", + "code composes." ] }, { diff --git a/redisvl/mcp/filters.py b/redisvl/mcp/filters.py index 008270451..8c24097af 100644 --- a/redisvl/mcp/filters.py +++ b/redisvl/mcp/filters.py @@ -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` neutralizes its own eq/ne values (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. diff --git a/redisvl/mcp/tools/search.py b/redisvl/mcp/tools/search.py index ee4b22649..87c47f1bb 100644 --- a/redisvl/mcp/tools/search.py +++ b/redisvl/mcp/tools/search.py @@ -414,8 +414,8 @@ def _reject_escapable_filter(caller: FilterExpression) -> None: The quoted-phrase skip below assumes a rendering's quotes arrive in delimiting pairs with no backslash between them, which holds for every - value the DSL can render: ``==`` and ``!=`` quote the value and take any - quote or backslash it carried out first, and ``Tag`` and ``like`` values + value the DSL can render: ``==`` and ``!=`` quote the value after taking + out any quote or backslash it carried, and ``Tag`` and ``like`` values arrive with theirs escaped, outside any phrase. A rendering that breaks either assumption is refused, so the failure is loud rather than silent. """ @@ -447,12 +447,9 @@ def _reject_escapable_filter(caller: FilterExpression) -> None: # a `|` inside it is a separator rather than a union. Unlike the range # span below, the whole phrase can therefore be skipped. # - # That skip is sound only while this scan and RediSearch agree on - # where the phrase ends. A backslash anywhere before the closing - # quote breaks the agreement: the parser pairs that quote with a - # later one, even when the backslash is itself escaped. `Text` - # replaces backslashes in its phrases, so one here means a value - # reached the phrase raw. + # The skip holds only while this scan and the parser agree on where + # the phrase ends, which a backslash inside it breaks (see + # `redisvl.query.filter._phrase_value`), so refuse one. end = rendered.find('"', position + 1) if end == -1 or rendered.find("\\", position + 1, end) != -1: escaped = True @@ -520,7 +517,7 @@ 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 quotes and backslashes that decide where a + clause. ``Text`` takes out the quotes and backslashes that decide where a phrase ends, ``Tag`` escapes the braces that delimit a tag clause, numeric values are type-checked, and ``like`` patterns are escaped at the filter boundary. diff --git a/redisvl/query/filter.py b/redisvl/query/filter.py index 710f67c82..db72b6f83 100644 --- a/redisvl/query/filter.py +++ b/redisvl/query/filter.py @@ -701,29 +701,31 @@ def __str__(self) -> str: return self.OPERATOR_MAP[self._operator] % (self._field, self._value) -# Either character can move a phrase's closing quote: a `"` ends the phrase -# early, and a `\` anywhere before the closing quote makes the parser pair that -# quote with a later one, even when the backslash is itself escaped. -# -# Replaced rather than escaped, because escaping is symmetric: a backslash joins -# the next character 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. The cost is a document whose text holds a deliberate escape, such -# as `foo\-bar`: it indexed the joined term, which a phrase can no longer ask for. -_PHRASE_UNSAFE = re.compile(r'["\\]') +def _phrase_value(value: str) -> str: + """Return `value` with nothing in it that can move where its phrase ends. + + A `"` closes the phrase early, and a `\\` before the closing quote makes the + parser pair that quote with a later one, even when the backslash is itself + escaped. Neither can be escaped, since the escape is a backslash, so each + goes the way the tokenizer took it at index time: a quote separates terms, + and a backslash vanishes into the term around it (`C:\\Users\\bob` indexes + `usersbob`). + + A value left empty becomes a space, because `@f:("")` raises `INDEXEMPTY`. + """ + return value.replace("\\", "").replace('"', " ") or " " 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 ``"`` or - ``\\`` in the value becomes a space first, so the value cannot move - where that phrase ends. A value of nothing but those characters - 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 quoted phrase, with any ``\\`` + removed and any ``"`` replaced by a space. Text stored with a + deliberate escape, such as ``foo\\-bar``, is therefore not matched. A + value of nothing but those characters matches no document with ``==`` + and every document with ``!=``. ``%`` is the pattern operator and + interpolates its value untouched. """ OPERATORS: dict[FilterOperator, str] = { @@ -817,10 +819,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, diff --git a/tests/integration/test_mcp/test_claim_injection.py b/tests/integration/test_mcp/test_claim_injection.py index d466204f9..cf936cf25 100644 --- a/tests/integration/test_mcp/test_claim_injection.py +++ b/tests/integration/test_mcp/test_claim_injection.py @@ -216,13 +216,6 @@ async def test_a_pipe_in_the_claim_is_one_identifier_not_a_union( ["acme", "acme"], id="or-widening", ), - # Each phrase ends in a backslash with another phrase after it, the shape - # that shifts the parser's quote pairing when the backslash reaches it. - pytest.param( - {"field": "content", "op": "in", "value": ["policy\\", "window\\"]}, - ["acme", "acme"], - id="backslash-phrases", - ), pytest.param( {"not": {"field": "org_id", "op": "eq", "value": "acme"}}, [], diff --git a/tests/integration/test_query.py b/tests/integration/test_query.py index ebc1f3d02..976804cde 100644 --- a/tests/integration/test_query.py +++ b/tests/integration/test_query.py @@ -468,10 +468,11 @@ def test_filters(index, query, sample_datetimes): t = Text("description") != 'high stress,"' search(query, index, t, 6) - # Values ending in a backslash, with a quote after each one. Left raw, the - # backslash makes the parser pair the first phrase's closing quote with the - # second's opening one, and the re-paired query silently matches nothing. - t = (Text("job") == "engineer\\") | (Text("job") == "doctor\\") + # 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` must + # vanish rather than split the term, or that phrase matches nothing either. + t = (Text("job") == "engi\\neer\\") | (Text("job") == "doctor\\") search(query, index, t, 4) # Test empty filters diff --git a/tests/unit/test_filter.py b/tests/unit/test_filter.py index 7d98170ce..616d57a48 100644 --- a/tests/unit/test_filter.py +++ b/tests/unit/test_filter.py @@ -329,10 +329,10 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): ("__eq__", '"', '@text_field:(" ")'), ("__ne__", '""', '(-@text_field:" ")'), ("__eq__", " ", '@text_field:(" ")'), - # A backslash before the closing quote moves where the parser ends the - # phrase, so it goes the same way as a quote. - ("__eq__", "trailing\\", '@text_field:("trailing ")'), - ("__ne__", "C:\\Users\\", '(-@text_field:"C: Users ")'), + ("__eq__", "\\\\", '@text_field:(" ")'), + # A backslash vanishes into the term around it, as it did at index time. + ("__eq__", "trailing\\", '@text_field:("trailing")'), + ("__ne__", "C:\\Users\\bob", '(-@text_field:"C:Usersbob")'), # Everything else survives untouched. Replacing any of it would ask for a # term no document stored -- a silent zero-hit failure. This row fails if # a single extra character joins the pattern. @@ -365,6 +365,7 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): "eq_quotes_only", "ne_quotes_only", "eq_whitespace_only", + "eq_backslashes_only", "eq_backslash_neutralized", "ne_backslash_neutralized", "eq_punctuation_preserved", diff --git a/tests/unit/test_mcp/test_filters.py b/tests/unit/test_mcp/test_filters.py index 6b15525b6..c54d55d6b 100644 --- a/tests/unit/test_mcp/test_filters.py +++ b/tests/unit/test_mcp/test_filters.py @@ -300,15 +300,15 @@ def test_merge_locked_filter_ands_a_multi_value_tag_in_caller_filter(): # Balanced parens, so only the phrase branch can refuse this: skipping to # end-of-string instead would swallow the injected union. ("unterminated phrase", '@content:"unterminated | @category:{secret}'), - # A backslash before a phrase's closing quote makes RediSearch pair that - # quote with a later one, even when the backslash is itself escaped, so - # this scan and the parser would disagree about what is phrase and what - # is syntax. Both templates, since each renders its own quote. + # A backslash inside a phrase is refused wherever it sits. The last row + # is escaped, so a scan that trusted the quote after it would read the + # union as the inside of the second phrase. ("backslash in an eq phrase", '@content:("trailing\\")'), ("backslash in a ne phrase", '(-@content:"C:\\Users\\")'), + ("backslash mid-phrase", '@content:("a\\b")'), ( "escaped backslash before a phrase quote", - '@content:("a\\\\") | @category:{secret} @content:("b")', + '(@content:("a\\\\") | @content:(" | @category:{secret} "))', ), ], ) From 1e01d7efe0ed96da55b487278a502f46d320539a Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Tue, 13 Oct 2026 18:15:36 +0200 Subject: [PATCH 3/8] fix: render Text phrase backslashes the way the indexer read them Deleting every backslash lost documents the query parser could still reach. The indexer joins an escaped separator into its term (`foo\-bar` indexes `foo-bar`) and the parser does the same inside a phrase, so that pair now stays. A backslash before anything else is still dropped, since the indexer dropped it while the parser would keep it (`C:\Users\bob` indexes `usersbob`). A body ending in a backslash gets a trailing space, because a backslash right before the closing quote re-pairs it. The backstop now accepts exactly those shapes: inside a phrase, a backslash may only escape a character from the shared set, and may not sit right before the closing quote. Measured on redis:8.4 over 1,500 hostile values: the backstop accepts every rendering, none errors or re-pairs, and `==` finds its own document for 1,073 of 1,280 values, against 698 on main. The values main matched and this does not all hold an escaped quote, which cannot be kept. --- docs/concepts/mcp.md | 2 +- docs/user_guide/02_complex_filtering.ipynb | 9 ++-- redisvl/mcp/tools/search.py | 49 +++++++++++------ redisvl/query/filter.py | 61 ++++++++++++++++------ tests/unit/test_filter.py | 18 +++++-- tests/unit/test_mcp/test_filters.py | 26 +++++---- 6 files changed, 112 insertions(+), 53 deletions(-) diff --git a/docs/concepts/mcp.md b/docs/concepts/mcp.md index 2dafb4b6e..ac569e21a 100644 --- a/docs/concepts/mcp.md +++ b/docs/concepts/mcp.md @@ -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`. diff --git a/docs/user_guide/02_complex_filtering.ipynb b/docs/user_guide/02_complex_filtering.ipynb index 3dc2ff0ff..082846656 100644 --- a/docs/user_guide/02_complex_filtering.ipynb +++ b/docs/user_guide/02_complex_filtering.ipynb @@ -693,11 +693,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, which means text stored\n", - "with a deliberate escape, such as `foo\\-bar`, is not matched. The `%` operator\n", - "is the opposite: its value is a raw pattern, so pass it only patterns your own\n", - "code 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." ] }, { diff --git a/redisvl/mcp/tools/search.py b/redisvl/mcp/tools/search.py index 87c47f1bb..698817cc0 100644 --- a/redisvl/mcp/tools/search.py +++ b/redisvl/mcp/tools/search.py @@ -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." @@ -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. @@ -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 with no backslash between them, which holds for every - value the DSL can render: ``==`` and ``!=`` quote the value after taking - out any quote or backslash it carried, and ``Tag`` and ``like`` values - arrive with theirs escaped, outside any phrase. A rendering that breaks - either assumption is refused, 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 theirs 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 @@ -446,12 +468,10 @@ 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 skip holds only while this scan and the parser agree on where - # the phrase ends, which a backslash inside it breaks (see - # `redisvl.query.filter._phrase_value`), so refuse one. - end = rendered.find('"', position + 1) - if end == -1 or rendered.find("\\", position + 1, end) != -1: + # the phrase ends, so a phrase whose end is in doubt is refused. + end = _phrase_end(rendered, position) + if end is None: escaped = True break position = end + 1 @@ -517,10 +537,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`` takes out the quotes and backslashes that decide where a - phrase ends, ``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 diff --git a/redisvl/query/filter.py b/redisvl/query/filter.py index db72b6f83..7d07543c3 100644 --- a/redisvl/query/filter.py +++ b/redisvl/query/filter.py @@ -701,31 +701,60 @@ def __str__(self) -> str: return self.OPERATOR_MAP[self._operator] % (self._field, self._value) -def _phrase_value(value: str) -> str: - """Return `value` with nothing in it that can move where its phrase ends. +# 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 its +# escape matches nothing that was indexed. +_PHRASE_ESCAPABLE = frozenset(" !#$%&'()*+,-./:;<=>?@[\\]^`{|}~") - A `"` closes the phrase early, and a `\\` before the closing quote makes the - parser pair that quote with a later one, even when the backslash is itself - escaped. Neither can be escaped, since the escape is a backslash, so each - goes the way the tokenizer took it at index time: a quote separates terms, - and a backslash vanishes into the term around it (`C:\\Users\\bob` indexes - `usersbob`). - A value left empty becomes a space, because `@f:("")` raises `INDEXEMPTY`. +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 + just as the indexer did (`foo\\-bar` indexes `foo-bar`). Any other backslash + is dropped, since the indexer dropped it into the term around it while the + parser would keep it (`C:\\Users\\bob` indexes `usersbob`). A `"` becomes a + space, which is how the indexer separated terms at it. + + A body ending in a backslash makes the parser pair the closing quote with a + later one, so a space follows it. A body left empty becomes a space too: + `@f:("")` is an error on most fields and matches empty values on the rest. """ - return value.replace("\\", "").replace('"', " ") or " " + body = [] + position = 0 + while position < len(value): + character = value[position] + if character == "\\": + escaped = value[position + 1 : position + 2] + if escaped in _PHRASE_ESCAPABLE: + body.append(character + escaped) + position += 2 + continue + else: + body.append(" " if character == '"' else character) + position += 1 + + rendered = "".join(body) + if not rendered or 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, with any ``\\`` - removed and any ``"`` replaced by a space. Text stored with a - deliberate escape, such as ``foo\\-bar``, is therefore not matched. A - value of nothing but those characters matches no document with ``==`` - and every document with ``!=``. ``%`` 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. A value that + leaves no term, such as one of nothing but quotes, matches no document + with ``==`` and every document with ``!=``. ``%`` is the pattern + operator and interpolates its value untouched. """ OPERATORS: dict[FilterOperator, str] = { diff --git a/tests/unit/test_filter.py b/tests/unit/test_filter.py index 616d57a48..6e49c979e 100644 --- a/tests/unit/test_filter.py +++ b/tests/unit/test_filter.py @@ -329,10 +329,15 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): ("__eq__", '"', '@text_field:(" ")'), ("__ne__", '""', '(-@text_field:" ")'), ("__eq__", " ", '@text_field:(" ")'), - ("__eq__", "\\\\", '@text_field:(" ")'), - # A backslash vanishes into the term around it, as it did at index time. + ("__eq__", "\\", '@text_field:(" ")'), + # A backslash goes the way the indexer took it: dropped before a letter + # or the end, kept before a separator or another backslash. It never + # escapes a quote, and never sits right before the closing one. ("__eq__", "trailing\\", '@text_field:("trailing")'), ("__ne__", "C:\\Users\\bob", '(-@text_field:"C:Usersbob")'), + ("__eq__", "foo\\-bar", '@text_field:("foo\\-bar")'), + ("__eq__", 'say \\"hi', '@text_field:("say hi")'), + ("__eq__", "back\\\\", '@text_field:("back\\\\ ")'), # Everything else survives untouched. Replacing any of it would ask for a # term no document stored -- a silent zero-hit failure. This row fails if # a single extra character joins the pattern. @@ -365,9 +370,12 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): "eq_quotes_only", "ne_quotes_only", "eq_whitespace_only", - "eq_backslashes_only", - "eq_backslash_neutralized", - "ne_backslash_neutralized", + "eq_backslash_only", + "eq_backslash_dropped_at_end", + "ne_backslash_dropped_before_letter", + "eq_backslash_kept_before_separator", + "eq_escaped_quote_neutralized", + "eq_trailing_backslash_padded", "eq_punctuation_preserved", "like_raw_by_design", ], diff --git a/tests/unit/test_mcp/test_filters.py b/tests/unit/test_mcp/test_filters.py index c54d55d6b..3be124ccd 100644 --- a/tests/unit/test_mcp/test_filters.py +++ b/tests/unit/test_mcp/test_filters.py @@ -300,16 +300,18 @@ def test_merge_locked_filter_ands_a_multi_value_tag_in_caller_filter(): # Balanced parens, so only the phrase branch can refuse this: skipping to # end-of-string instead would swallow the injected union. ("unterminated phrase", '@content:"unterminated | @category:{secret}'), - # A backslash inside a phrase is refused wherever it sits. The last row - # is escaped, so a scan that trusted the quote after it would read the - # union as the inside of the second phrase. - ("backslash in an eq phrase", '@content:("trailing\\")'), - ("backslash in a ne phrase", '(-@content:"C:\\Users\\")'), - ("backslash mid-phrase", '@content:("a\\b")'), + # The phrase shapes `Text` never renders. In the first two the parser + # pairs the first phrase's closing quote with the second's opening one, + # so a scan that trusted it would read the union as phrase text. ( - "escaped backslash before a phrase quote", + "escaped quote", + '(@content:("a\\") | @content:(" | @category:{secret} "))', + ), + ( + "escaped backslash before the closing quote", '(@content:("a\\\\") | @content:(" | @category:{secret} "))', ), + ("backslash escaping a letter", '(-@content:"C:\\Users\\bob")'), ], ) def test_merge_locked_filter_refuses_a_caller_rendering_that_could_escape( @@ -348,11 +350,11 @@ def test_merge_locked_filter_refuses_a_caller_rendering_that_could_escape( "unbalanced bracket in a value", {"field": "content", "op": "eq", "value": "a[b"}, ), - # The backstop refuses a backslash inside a phrase, so this passes only - # because `Text` replaces it before rendering. + # Rendered raw, this value would be refused. It passes only because + # `Text` drops, keeps or spaces off each backslash as needed. ( - "value ending in a backslash", - {"field": "content", "op": "eq", "value": "C:\\Users\\"}, + "backslashes in a value", + {"field": "content", "op": "eq", "value": "C:\\Users foo\\-bar back\\\\"}, ), ( "compound with exclusive bound", @@ -417,6 +419,8 @@ def test_merge_locked_filter_returns_each_side_unchanged_when_the_other_is_absen # end. Unbounded it reads this as a union hidden in the range and # refuses, and it costs the whole remaining string on every `[`. ("pipe after a range span", "(@rating:[4 5] | @category:{sports})"), + # The escapes `Text` keeps, with a trailing one spaced off the quote. + ("escaped separators in a phrase", '@content:("foo\\-bar back\\\\ ")'), ], ) def test_merge_locked_filter_accepts_a_legitimate_rendering(label, rendered): From 8f7c0e5527b9e973bc4c46b219080e383b5640a1 Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Wed, 14 Oct 2026 12:00:47 +0200 Subject: [PATCH 4/8] fix: drop control characters and split bare `$` in Text phrases The indexer drops control characters from a term, along with a backslash escaping one, and drops an escaped tab; it splits terms at a bare `$`, which the query parser would read as a parameter. Phrases now do the same, so stored text holding any of them is matched. Dropping NUL also stops it truncating the query string. Tests: a live case per character class against its own small index, where a misread phrase finds a neighbouring document; the backstop's escaped-quote row now balances its quotes, so only refusing the escape catches it; a redundant accept row is removed. Docs name the two kinds of stored text no phrase can reach. --- redisvl/mcp/filters.py | 2 +- redisvl/mcp/tools/search.py | 5 +-- redisvl/query/filter.py | 61 ++++++++++++++++++++--------- tests/integration/test_query.py | 44 +++++++++++++++++++++ tests/unit/test_filter.py | 15 +++++-- tests/unit/test_mcp/test_filters.py | 8 ++-- 6 files changed, 104 insertions(+), 31 deletions(-) diff --git a/redisvl/mcp/filters.py b/redisvl/mcp/filters.py index 8c24097af..128a5195c 100644 --- a/redisvl/mcp/filters.py +++ b/redisvl/mcp/filters.py @@ -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_value` 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. diff --git a/redisvl/mcp/tools/search.py b/redisvl/mcp/tools/search.py index 698817cc0..28da099ec 100644 --- a/redisvl/mcp/tools/search.py +++ b/redisvl/mcp/tools/search.py @@ -437,7 +437,7 @@ def _reject_escapable_filter(caller: FilterExpression) -> None: 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 after `_phrase_value` has made its body safe, - and ``Tag`` and ``like`` values arrive with theirs escaped, outside any + 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. """ @@ -468,8 +468,7 @@ 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 skip holds only while this scan and the parser agree on where - # the phrase ends, so a phrase whose end is in doubt is refused. + # Refuse a phrase whose end is in doubt. end = _phrase_end(rendered, position) if end is None: escaped = True diff --git a/redisvl/query/filter.py b/redisvl/query/filter.py index 7d07543c3..f0ba7f2ab 100644 --- a/redisvl/query/filter.py +++ b/redisvl/query/filter.py @@ -704,38 +704,59 @@ def __str__(self) -> str: # 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 its -# escape matches nothing that was indexed. +# 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"} + 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 - just as the indexer did (`foo\\-bar` indexes `foo-bar`). Any other backslash - is dropped, since the indexer dropped it into the term around it while the - parser would keep it (`C:\\Users\\bob` indexes `usersbob`). A `"` becomes a - space, which is how the indexer separated terms at it. + 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, + and the parser would end the phrase at one and read a parameter at the + other. + + Two kinds of stored text stay out of reach. An escaped quote cannot be + carried, and the parser reads a run of escaped backslashes as one. A body ending in a backslash makes the parser pair the closing quote with a - later one, so a space follows it. A body left empty becomes a space too: - `@f:("")` is an error on most fields and matches empty values on the rest. + later one, so a space follows it. So does an empty body, since `@f:("")` + errors on a field without `INDEXEMPTY` and matches empty values on one with + it. (The membership tests rely on an empty slice being in neither set.) """ body = [] position = 0 while position < len(value): character = value[position] if character == "\\": - escaped = value[position + 1 : position + 2] - if escaped in _PHRASE_ESCAPABLE: - body.append(character + escaped) + 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 - else: - body.append(" " if character == '"' else character) + elif character in '"$': + body.append(" ") + elif character not in _PHRASE_DROPPED: + body.append(character) position += 1 rendered = "".join(body) @@ -751,10 +772,12 @@ class Text(FilterField): ``==`` 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. A value that - leaves no term, such as one of nothing but quotes, matches no document - with ``==`` and every document with ``!=``. ``%`` is the pattern - operator and interpolates its value untouched. + ``foo\\-bar`` each match a document holding that text. Stored text + with an escaped quote (``\\"``) or a run of escaped backslashes cannot + be matched this way. A value that leaves no term, such as one of + nothing but quotes, matches no document with ``==`` and every + document with ``!=``. ``%`` is the pattern operator and interpolates + its value untouched. """ OPERATORS: dict[FilterOperator, str] = { diff --git a/tests/integration/test_query.py b/tests/integration/test_query.py index 976804cde..88aea8f02 100644 --- a/tests/integration/test_query.py +++ b/tests/integration/test_query.py @@ -508,6 +508,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 `$`, which the parser would read as a parameter. + ("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}" diff --git a/tests/unit/test_filter.py b/tests/unit/test_filter.py index 6e49c979e..fb8e742c7 100644 --- a/tests/unit/test_filter.py +++ b/tests/unit/test_filter.py @@ -330,14 +330,19 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): ("__ne__", '""', '(-@text_field:" ")'), ("__eq__", " ", '@text_field:(" ")'), ("__eq__", "\\", '@text_field:(" ")'), - # A backslash goes the way the indexer took it: dropped before a letter - # or the end, kept before a separator or another backslash. It never - # escapes a quote, and never sits right before the closing one. + # Each character goes the way the indexer took it. A backslash is + # dropped before a letter or the end and kept before an escapable + # separator or another backslash; it never escapes a quote, and never + # sits right before the closing one. ("__eq__", "trailing\\", '@text_field:("trailing")'), ("__ne__", "C:\\Users\\bob", '(-@text_field:"C:Usersbob")'), ("__eq__", "foo\\-bar", '@text_field:("foo\\-bar")'), ("__eq__", 'say \\"hi', '@text_field:("say hi")'), ("__eq__", "back\\\\", '@text_field:("back\\\\ ")'), + # Control characters go, escaped or not, and so does an escaped tab. A + # bare `$` would start a parameter, so it separates terms as indexed. + ("__eq__", "a\nb\\\x01c\\\td\x00", '@text_field:("abcd")'), + ("__eq__", "a\tb $1 \\$2", '@text_field:("a\tb 1 \\$2")'), # Everything else survives untouched. Replacing any of it would ask for a # term no document stored -- a silent zero-hit failure. This row fails if # a single extra character joins the pattern. @@ -374,8 +379,10 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): "eq_backslash_dropped_at_end", "ne_backslash_dropped_before_letter", "eq_backslash_kept_before_separator", - "eq_escaped_quote_neutralized", + "eq_escaped_quote_split", "eq_trailing_backslash_padded", + "eq_control_characters_dropped", + "eq_tab_kept_and_dollar_split", "eq_punctuation_preserved", "like_raw_by_design", ], diff --git a/tests/unit/test_mcp/test_filters.py b/tests/unit/test_mcp/test_filters.py index 3be124ccd..7b808d245 100644 --- a/tests/unit/test_mcp/test_filters.py +++ b/tests/unit/test_mcp/test_filters.py @@ -302,10 +302,12 @@ def test_merge_locked_filter_ands_a_multi_value_tag_in_caller_filter(): ("unterminated phrase", '@content:"unterminated | @category:{secret}'), # The phrase shapes `Text` never renders. In the first two the parser # pairs the first phrase's closing quote with the second's opening one, - # so a scan that trusted it would read the union as phrase text. + # so a scan that trusted it would read the union as phrase text. The + # escaped quote is closed off by a second one, so the quotes balance and + # only refusing the escape itself catches it. ( "escaped quote", - '(@content:("a\\") | @content:(" | @category:{secret} "))', + '@content:("a\\") | @category:{secret} | @content:("b\\")', ), ( "escaped backslash before the closing quote", @@ -419,8 +421,6 @@ def test_merge_locked_filter_returns_each_side_unchanged_when_the_other_is_absen # end. Unbounded it reads this as a union hidden in the range and # refuses, and it costs the whole remaining string on every `[`. ("pipe after a range span", "(@rating:[4 5] | @category:{sports})"), - # The escapes `Text` keeps, with a trailing one spaced off the quote. - ("escaped separators in a phrase", '@content:("foo\\-bar back\\\\ ")'), ], ) def test_merge_locked_filter_accepts_a_legitimate_rendering(label, rendered): From d89d83e730ba5e39153787fe2c37417e9cc141fe Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Tue, 3 Nov 2026 10:12:38 +0100 Subject: [PATCH 5/8] docs: correct the reasons Text phrases split `$` and miss escaped backslashes Inside a quoted phrase the parser keeps `$` in the term rather than reading a parameter; the split exists because the indexer separates terms there. An escaped backslash before `_` is also out of reach, not only a run of them. --- redisvl/query/filter.py | 19 ++++++++++--------- tests/integration/test_query.py | 2 +- tests/unit/test_filter.py | 3 ++- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/redisvl/query/filter.py b/redisvl/query/filter.py index f0ba7f2ab..b12066914 100644 --- a/redisvl/query/filter.py +++ b/redisvl/query/filter.py @@ -731,11 +731,12 @@ def _phrase_value(value: str) -> str: - 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, - and the parser would end the phrase at one and read a parameter at the - other. + where the parser would end the phrase at a quote and keep a `$` inside + the term. - Two kinds of stored text stay out of reach. An escaped quote cannot be - carried, and the parser reads a run of escaped backslashes as one. + 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. So does an empty body, since `@f:("")` @@ -773,11 +774,11 @@ class Text(FilterField): 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 a run of escaped backslashes cannot - be matched this way. A value that leaves no term, such as one of - nothing but quotes, matches no document with ``==`` and every - document with ``!=``. ``%`` is the pattern operator and interpolates - its value untouched. + 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 quotes, + matches no document with ``==`` and every document with ``!=``. ``%`` + is the pattern operator and interpolates its value untouched. """ OPERATORS: dict[FilterOperator, str] = { diff --git a/tests/integration/test_query.py b/tests/integration/test_query.py index 88aea8f02..103227d20 100644 --- a/tests/integration/test_query.py +++ b/tests/integration/test_query.py @@ -535,7 +535,7 @@ def phrase_index(client, worker_id): ("C:\\Users\\bob", "C: Users bob"), # A control character, which the indexer drops. ("hello world\nnext", "hello world next"), - # A bare `$`, which the parser would read as a parameter. + # A bare `$`, where the indexer splits terms and the parser does not. ("price $100", "price100"), ], ) diff --git a/tests/unit/test_filter.py b/tests/unit/test_filter.py index fb8e742c7..941bfb757 100644 --- a/tests/unit/test_filter.py +++ b/tests/unit/test_filter.py @@ -340,7 +340,8 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): ("__eq__", 'say \\"hi', '@text_field:("say hi")'), ("__eq__", "back\\\\", '@text_field:("back\\\\ ")'), # Control characters go, escaped or not, and so does an escaped tab. A - # bare `$` would start a parameter, so it separates terms as indexed. + # bare `$` separates terms as the indexer did, though the parser would + # keep it inside one. ("__eq__", "a\nb\\\x01c\\\td\x00", '@text_field:("abcd")'), ("__eq__", "a\tb $1 \\$2", '@text_field:("a\tb 1 \\$2")'), # Everything else survives untouched. Replacing any of it would ask for a From e3227e7363e838a55d32a3abcd5b6b23d45588ed Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Tue, 3 Nov 2026 10:23:39 +0100 Subject: [PATCH 6/8] fix: refuse a Text phrase value that leaves no searchable term A value of nothing but separators (punctuation, whitespace, quotes, a bare `$`, control characters, a lone backslash) rendered a phrase that asked for no term, so `==` silently matched nothing and `!=` matched every document. `Text` now raises ValueError for it, and the MCP filter boundary reports it as INVALID_FILTER. Stopwords are not checked, since they depend on the index. Behaviour change: `Text("f") == '"'` and similar values, which used to match no document, now raise. Also adds a live case for a phrase ending in a kept escape pair followed by another phrase, the one shape where the trailing space matters to Redis. --- redisvl/mcp/filters.py | 8 +++++++- redisvl/query/filter.py | 30 ++++++++++++++++++++++------- tests/integration/test_query.py | 9 +++++++-- tests/unit/test_filter.py | 24 +++++++++++------------ tests/unit/test_mcp/test_filters.py | 10 ++++++++++ 5 files changed, 58 insertions(+), 23 deletions(-) diff --git a/redisvl/mcp/filters.py b/redisvl/mcp/filters.py index 128a5195c..cdff92d6c 100644 --- a/redisvl/mcp/filters.py +++ b/redisvl/mcp/filters.py @@ -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) diff --git a/redisvl/query/filter.py b/redisvl/query/filter.py index b12066914..5d102afad 100644 --- a/redisvl/query/filter.py +++ b/redisvl/query/filter.py @@ -716,6 +716,10 @@ def __str__(self) -> str: # 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. @@ -739,9 +743,13 @@ def _phrase_value(value: str) -> str: 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. So does an empty body, since `@f:("")` - errors on a field without `INDEXEMPTY` and matches empty values on one with - it. (The membership tests rely on an empty slice being in neither set.) + 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 @@ -761,7 +769,13 @@ def _phrase_value(value: str) -> str: position += 1 rendered = "".join(body) - if not rendered or rendered.endswith("\\"): + # 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 @@ -776,9 +790,11 @@ class Text(FilterField): ``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 quotes, - matches no document with ``==`` and every document with ``!=``. ``%`` - is the pattern operator and interpolates its value untouched. + 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. """ OPERATORS: dict[FilterOperator, str] = { diff --git a/tests/integration/test_query.py b/tests/integration/test_query.py index 103227d20..0de02819b 100644 --- a/tests/integration/test_query.py +++ b/tests/integration/test_query.py @@ -470,11 +470,16 @@ def test_filters(index, query, sample_datetimes): # 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` must - # vanish rather than split the term, or that phrase matches nothing either. + # 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) + # Test empty filters t = Text("job") % "" search(query, index, t, 7) diff --git a/tests/unit/test_filter.py b/tests/unit/test_filter.py index 941bfb757..9fb8335a7 100644 --- a/tests/unit/test_filter.py +++ b/tests/unit/test_filter.py @@ -321,15 +321,6 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): 'hello") | (@secret:{leaked} @v:"nothing', '(-@text_field:"hello ) | (@secret:{leaked} @v: nothing")', ), - # A value that neutralizes down to whitespace still renders as a phrase - # rather than collapsing to `*`. An empty phrase matches no document, so - # `==` fails closed; collapsing would invert that to matching every one, - # and `format_expression` drops a `*` operand, so it would also delete - # this clause from a surrounding AND. - ("__eq__", '"', '@text_field:(" ")'), - ("__ne__", '""', '(-@text_field:" ")'), - ("__eq__", " ", '@text_field:(" ")'), - ("__eq__", "\\", '@text_field:(" ")'), # Each character goes the way the indexer took it. A backslash is # dropped before a letter or the end and kept before an escapable # separator or another backslash; it never escapes a quote, and never @@ -337,6 +328,7 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): ("__eq__", "trailing\\", '@text_field:("trailing")'), ("__ne__", "C:\\Users\\bob", '(-@text_field:"C:Usersbob")'), ("__eq__", "foo\\-bar", '@text_field:("foo\\-bar")'), + ("__eq__", "\\-", '@text_field:("\\-")'), ("__eq__", 'say \\"hi', '@text_field:("say hi")'), ("__eq__", "back\\\\", '@text_field:("back\\\\ ")'), # Control characters go, escaped or not, and so does an escaped tab. A @@ -373,13 +365,10 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): "like_none", "eq_quote_neutralized", "ne_quote_neutralized", - "eq_quotes_only", - "ne_quotes_only", - "eq_whitespace_only", - "eq_backslash_only", "eq_backslash_dropped_at_end", "ne_backslash_dropped_before_letter", "eq_backslash_kept_before_separator", + "eq_kept_pair_alone_is_a_term", "eq_escaped_quote_split", "eq_trailing_backslash_padded", "eq_control_characters_dropped", @@ -393,6 +382,15 @@ def test_text_filter(operation, value, expected): assert str(txt_f) == expected +@pytest.mark.parametrize("operation", ["__eq__", "__ne__"]) +@pytest.mark.parametrize("value", ['""', " ", "\\", "$ -", "\t\x01"]) +def test_text_phrase_value_without_a_term_is_refused(operation, value): + # Rendered, each would ask for no term: `==` would match nothing and `!=` + # everything, so the filter is refused instead. + with pytest.raises(ValueError, match="no searchable term"): + getattr(Text("text_field"), operation)(value) + + def test_text_subclass_inherits_containment_for_a_new_quoted_operator(): """Listing only the raw operator means a new one is contained by default. diff --git a/tests/unit/test_mcp/test_filters.py b/tests/unit/test_mcp/test_filters.py index 7b808d245..b64576833 100644 --- a/tests/unit/test_mcp/test_filters.py +++ b/tests/unit/test_mcp/test_filters.py @@ -115,6 +115,16 @@ def test_parse_filter_rejects_empty_logical_array(): assert exc_info.value.code == MCPErrorCode.INVALID_FILTER +def test_parse_filter_rejects_a_text_value_without_a_term(): + # Through `in` as well, where a term-less item would silently match nothing. + with pytest.raises(RedisVLMCPError) as exc_info: + parse_filter( + {"field": "content", "op": "in", "value": ["ok", "..."]}, _schema() + ) + + assert exc_info.value.code == MCPErrorCode.INVALID_FILTER + + def test_parse_filter_rejects_malformed_payload(): with pytest.raises(RedisVLMCPError) as exc_info: parse_filter({"field": "category", "value": "science"}, _schema()) From 85be94a5b61b6f1e321ffe31b11d22e2b71871b2 Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Tue, 3 Nov 2026 10:28:48 +0100 Subject: [PATCH 7/8] docs: note that an empty Text value renders `*` rather than raising --- redisvl/query/filter.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/redisvl/query/filter.py b/redisvl/query/filter.py index 5d102afad..025f7f95d 100644 --- a/redisvl/query/filter.py +++ b/redisvl/query/filter.py @@ -793,8 +793,10 @@ class Text(FilterField): 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. + not checked, as they depend on the index. An empty or ``None`` value + is the exception: it renders ``*``, which matches every document and + drops out of a surrounding AND. ``%`` is the pattern operator and + interpolates its value untouched. """ OPERATORS: dict[FilterOperator, str] = { From 43cf8ff4667576320c80d41d12d3a970b919b5f0 Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Tue, 3 Nov 2026 10:34:48 +0100 Subject: [PATCH 8/8] refactor: refuse a term-less Text value before storing it Validating in `Text._set_value`, as `Num` does, means a refused value is never stored, so rendering a field never raises. Documents the ValueError on `__eq__` and `__ne__`, and trims the refusal test to one operator, since both share the check. --- redisvl/query/filter.py | 18 ++++++++++++++++++ tests/unit/test_filter.py | 12 +++++++----- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/redisvl/query/filter.py b/redisvl/query/filter.py index 025f7f95d..e62c8a070 100644 --- a/redisvl/query/filter.py +++ b/redisvl/query/filter.py @@ -817,6 +817,18 @@ class Text(FilterField): # opts out here. _RAW_VALUE_OPERATORS = frozenset({FilterOperator.LIKE}) + def _set_value( + self, + val: Any, + val_type: type | tuple[type, ...], + operator: FilterOperator, + ): + """Refuse a phrase value without a term before storing it, so that + rendering a stored value never raises.""" + if isinstance(val, str) and val and operator not in self._RAW_VALUE_OPERATORS: + _phrase_value(val) + super()._set_value(val, val_type, operator) + @check_operator_misuse def __eq__(self, other: str) -> "FilterExpression": """Create a Text equality filter expression. These expressions yield @@ -825,6 +837,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 @@ -844,6 +859,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 diff --git a/tests/unit/test_filter.py b/tests/unit/test_filter.py index 9fb8335a7..e961e9da0 100644 --- a/tests/unit/test_filter.py +++ b/tests/unit/test_filter.py @@ -382,13 +382,15 @@ def test_text_filter(operation, value, expected): assert str(txt_f) == expected -@pytest.mark.parametrize("operation", ["__eq__", "__ne__"]) @pytest.mark.parametrize("value", ['""', " ", "\\", "$ -", "\t\x01"]) -def test_text_phrase_value_without_a_term_is_refused(operation, value): - # Rendered, each would ask for no term: `==` would match nothing and `!=` - # everything, so the filter is refused instead. +def test_text_phrase_value_without_a_term_is_refused(value): + # Rendered, each would ask for no term, so `!=` would match every document. + field = Text("text_field") with pytest.raises(ValueError, match="no searchable term"): - getattr(Text("text_field"), operation)(value) + field != value + + # Refused before it is stored, so the field still renders. + assert str(field) == "*" def test_text_subclass_inherits_containment_for_a_new_quoted_operator():