From d72afd8cd42db62f24ec26e5524ba63903e643d8 Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Thu, 12 Nov 2026 11:36:31 +0100 Subject: [PATCH 1/3] fix(query)!: make empty Tag values fail closed instead of matching everything An empty collection passed to a Tag filter rendered `*`, and `*` is elided from every `&` and `|`, so `(Tag("tenant") == "acme") & (Tag("groups") == [])` rendered `@tenant:{acme}`. A permission-style filter built from an empty group list therefore searched everything the other clauses allowed. Follow how Redis treats empty values, which is never as "no constraint": - An empty collection (`[]`, `()`, `set()`, or one holding only `None`) selects no tag. `==` and `%` render a contradiction that matches nothing, which absorbs an `&` and drops out of a `|`. `!=` renders `*`, since excluding nothing excludes nothing. - `""` is a tag of its own and renders `@field:{""}` (DIALECT 2+, field needs INDEXEMPTY), instead of vanishing. Items that are falsy but real, such as 0, are kept rather than dropped. - `None` keeps meaning "no constraint" on every filter type. - `Text` refuses `""`: beside another clause the server reads `@f:("")` against the preceding clause's field, so the filter's meaning would depend on operand order. BREAKING CHANGE: `Tag(f) == []`, `== ""`, `% ""` and `Text(f) == ""` no longer mean "no constraint". Pass `None` for that. --- docs/concepts/mcp.md | 2 +- docs/user_guide/02_complex_filtering.ipynb | 19 ++- redisvl/extensions/router/semantic.py | 11 +- redisvl/query/filter.py | 143 ++++++++++++++++-- tests/integration/test_query.py | 88 ++++++++++- tests/unit/test_filter.py | 120 ++++++++++++--- .../test_mcp/test_auth_claim_injection.py | 6 +- tests/unit/test_semantic_router_queries.py | 2 +- 8 files changed, 328 insertions(+), 63 deletions(-) diff --git a/docs/concepts/mcp.md b/docs/concepts/mcp.md index bc82ea9c3..ab012e0ff 100644 --- a/docs/concepts/mcp.md +++ b/docs/concepts/mcp.md @@ -225,7 +225,7 @@ The claim must be a single, non-empty string. Anything else refuses the request | Claim value | Why it is refused | |---|---| | Absent, or the request has no token | There is no tenant to scope to. | -| `null` or `""` | An empty tag value would drop the tenant clause from the query entirely. | +| `null` or `""` | An empty tag value is not a tenant to scope to. | | A list, such as `["acme", "victim"]` | It would render as a union, `@org_id:{acme\|victim}`, which spans both tenants. | | An object, number or boolean | It is not a tenant identifier. | | Padded with whitespace | It cannot be a real tenant identifier, and refusing is safer than guessing which tenant was meant. | diff --git a/docs/user_guide/02_complex_filtering.ipynb b/docs/user_guide/02_complex_filtering.ipynb index 1805b7d42..803d421e5 100644 --- a/docs/user_guide/02_complex_filtering.ipynb +++ b/docs/user_guide/02_complex_filtering.ipynb @@ -389,11 +389,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "What about scenarios where you might want to dynamically generate a list of tags? Have no fear. RedisVL allows you to do this gracefully without having to check for the **empty case**. The **empty case** is when you attempt to run a Tag filter on a field with no defined values to match:\n", + "What about scenarios where you might want to dynamically generate a list of tags? Redis treats an empty set of tags as a set that selects nothing, and so does RedisVL, so a Tag filter built from an empty list **matches no documents**:\n", "\n", "`Tag(\"credit_score\") == []`\n", "\n", - "An empty filter like the one above will yield a `*` Redis query filter which implies the base case -- there is no filter here to use." + "This is deliberate. When the list holds permitted values, such as a user's groups, an empty list must not widen the query. Combined with other filters, an empty list still matches nothing: `(Tag(\"tenant\") == \"acme\") & (Tag(\"groups\") == [])` returns no documents, and `|` ignores it.\n", + "\n", + "To mean \"no constraint\", pass `None` instead, which yields a `*` Redis query filter -- there is no filter here to use. Use `!= []` to exclude nothing." ] }, { @@ -422,8 +424,8 @@ } ], "source": [ - "# gracefully fallback to \"*\" filter if empty case\n", - "empty_case = Tag(\"credit_score\") == []\n", + "# None means no constraint, and falls back to the \"*\" filter\n", + "empty_case = Tag(\"credit_score\") == None\n", "\n", "v.set_filter(empty_case)\n", "result_print(index.query(v))" @@ -892,8 +894,8 @@ } ], "source": [ - "# gracefully fallback to \"*\" filter if empty case\n", - "empty_case = Text(\"job\") % \"\"\n", + "# None means no constraint, and falls back to the \"*\" filter\n", + "empty_case = Text(\"job\") % None\n", "\n", "v.set_filter(empty_case)\n", "result_print(index.query(v))" @@ -1213,11 +1215,12 @@ "\n", "There are often situations where you may or may not want to use a filter in a\n", "given query. As shown above, filters will except the ``None`` type and revert\n", - "to a wildcard filter essentially returning all results.\n", + "to a wildcard filter essentially returning all results. An empty list is not\n", + "``None``: it means \"in the empty set\" and matches nothing.\n", "\n", "The same goes for filter combinations which enables rapid reuse of filters in\n", "requests with different parameters as shown below. This removes the need for\n", - "a number of \"if-then\" conditionals to test for the empty case.\n", + "a number of \"if-then\" conditionals to test for ``None``.\n", "\n" ] }, diff --git a/redisvl/extensions/router/semantic.py b/redisvl/extensions/router/semantic.py index 2f7c914e5..cfed1ec95 100644 --- a/redisvl/extensions/router/semantic.py +++ b/redisvl/extensions/router/semantic.py @@ -1108,11 +1108,12 @@ def _make_filter_queries(ids: list[str]) -> list[FilterQuery]: for id in ids: if not id: - # `Tag(...) == ""` renders as the match-all `*`, so an empty id - # would match every reference in the index. Callers take the - # first row of each query's results, which turns this into - # returning -- and, from delete_route_references, deleting -- an - # arbitrary reference the caller never named. + # `Tag(...) == None` renders as the match-all `*`, so an empty id + # would match every reference in the index, and `""` asks the + # server for an empty tag, which no reference carries. Callers + # take the first row of each query's results, which turns the + # first into returning -- and, from delete_route_references, + # deleting -- an arbitrary reference the caller never named. raise ValueError( "reference ids must be non-empty strings; received an empty id" ) diff --git a/redisvl/query/filter.py b/redisvl/query/filter.py index 616ef45ac..0888881dd 100644 --- a/redisvl/query/filter.py +++ b/redisvl/query/filter.py @@ -75,6 +75,18 @@ def _set_value( self._value = val self._operator = operator + def _matches_nothing(self) -> bool: + """Report whether this filter, as built, can match no document.""" + return False + + def _expression(self) -> "FilterExpression": + """Wrap this filter's rendering, remembering whether it matches nothing. + + ``FilterExpression`` composes by rendering, so the fact has to travel + beside the string: see ``FilterExpression._render``. + """ + return FilterExpression(str(self), _matches_nothing=self._matches_nothing()) + def is_missing(self) -> "FilterExpression": """Create a filter expression for documents missing this field. @@ -116,7 +128,25 @@ def wrapper(instance: Any, *args: list[Any], **kwargs: dict[str, Any]) -> Any: class Tag(FilterField): - """A Tag filter can be applied to Tag fields""" + """A Tag filter can be applied to Tag fields + + Note: + Empty values follow Redis, which has no empty tag set. ``None`` means + no constraint and renders ``*``. An empty collection (``[]``, ``()``, + ``set()``, or one holding only ``None``) selects no tag, so ``==`` and + ``%`` match no document, whatever it is combined with: an ``&`` with it + matches nothing, and a ``|`` ignores it. ``!=`` an empty collection + excludes nothing and renders ``*``. ``""`` is a tag of its own, + rendered ``@field:{""}``, which needs ``INDEXEMPTY`` on the field and + DIALECT 2 or later. + + .. code-block:: python + + from redisvl.query.filter import Tag + + allowed = (Tag("tenant") == "acme") & (Tag("groups") == user_groups) + # user_groups == [] -> matches no document + """ OPERATORS: dict[FilterOperator, str] = { FilterOperator.EQ: "==", @@ -141,23 +171,37 @@ class Tag(FilterField): escape_chars_re=re.compile(TokenEscaper.TAG_ESCAPED_CHARS) ) + # RediSearch has no empty tag set: `@f:{}` is a syntax error, and an empty + # collection of tags selects no tag at all. So it is rendered as a + # contradiction over this value, which no document can satisfy. The value + # is arbitrary; only the contradiction matters. + _NO_MATCH_TAG = "redisvl_no_match" + def _set_tag_value( - self, other: list[str] | set[str] | str, operator: FilterOperator + self, other: list[str] | set[str] | str | None, operator: FilterOperator ): + # `None` alone means "no constraint". Anything else is a value: an empty + # collection selects no tag, and `""` is the tag RediSearch stores for + # an empty string, as `@f:{""}` (DIALECT 2+, and `INDEXEMPTY` on the + # field) matches it. if isinstance(other, (list, set, tuple)): try: - # "if val" clause removes non-truthy values from list - other = [str(val) for val in other if val] + other = [str(val) for val in other if val is not None] except ValueError: raise ValueError("All tags within collection must be strings") - # above to catch the "" case - elif not other: - other = [] elif isinstance(other, str): other = [other] self._set_value(other, self.SUPPORTED_VAL_TYPES, operator) + def _matches_nothing(self) -> bool: + # `!=` an empty collection excludes nothing, so it keeps every document. + return ( + self._value is not None + and not self._value + and self._operator != FilterOperator.NE + ) + @check_operator_misuse def __eq__(self, other: list[str] | str) -> "FilterExpression": """Create a Tag equality filter expression. @@ -172,7 +216,7 @@ def __eq__(self, other: list[str] | str) -> "FilterExpression": f = Tag("brand") == "nike" """ self._set_tag_value(other, FilterOperator.EQ) - return FilterExpression(str(self)) + return self._expression() @check_operator_misuse def __ne__(self, other: list[str] | str) -> "FilterExpression": @@ -188,7 +232,7 @@ def __ne__(self, other: list[str] | str) -> "FilterExpression": """ self._set_tag_value(other, FilterOperator.NE) - return FilterExpression(str(self)) + return self._expression() def __mod__(self, other: list[str] | str) -> "FilterExpression": """Create a Tag wildcard filter expression for pattern matching. @@ -216,21 +260,33 @@ def __mod__(self, other: list[str] | str) -> "FilterExpression": """ self._set_tag_value(other, FilterOperator.LIKE) - return FilterExpression(str(self)) + return self._expression() @property def _formatted_tag_value(self) -> str: # For LIKE operator, preserve wildcards (*) in the pattern preserve_wildcards = self._operator == FilterOperator.LIKE + # An empty tag has no characters to escape, and RediSearch spells it + # as a quoted empty string. return "|".join( - [self.escaper.escape(tag, preserve_wildcards) for tag in self._value] + [ + self.escaper.escape(tag, preserve_wildcards) if tag else '""' + for tag in self._value + ] ) def __str__(self) -> str: """Return the Redis Query string for the Tag filter""" - if not self._value: + if self._value is None: return "*" + if not self._value: + if self._operator == FilterOperator.NE: + return "*" + return "(@{0}:{{{1}}} -@{0}:{{{1}}})".format( + self._field, self._NO_MATCH_TAG + ) + return self.OPERATOR_MAP[self._operator] % ( self._field, self._formatted_tag_value, @@ -744,6 +800,26 @@ 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, + ): + if isinstance(val, str) and not val: + # `@f:("")` is how RediSearch asks for an empty string, but beside + # another clause the server reads it against that clause's field + # and rejects it for lacking `INDEXEMPTY` (measured on 8.4: + # `@t:{a} @x:("")` fails with `x` indexed empty, `@x:("") @t:{a}` + # does not). Rendering it would make a filter's meaning depend on + # operand order, so it is refused. `None` is how to ask for no + # constraint, and `is_missing()` finds an absent field. + raise ValueError( + f"{self.__class__.__name__} value must be a non-empty string; " + "pass None for no constraint" + ) + 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 @@ -812,7 +888,7 @@ def __mod__(self, other: str) -> "FilterExpression": def __str__(self) -> str: """Return the Redis Query string for the Text filter""" - if not self._value: + if self._value is None: return "*" value = self._value @@ -862,6 +938,12 @@ class FilterExpression: filter_expression=f, ) + Note: + A filter that can match no document, such as ``Tag("g") == []``, keeps + that meaning when combined: it absorbs an ``&`` and drops out of a + ``|``. ``*`` (from ``None``) is elided from both, and is the only + value that means "no constraint". + Note: Filter expressions are typically not called directly. Instead they are built by combining filter statements using the & and | operators. @@ -874,8 +956,10 @@ def __init__( operator: FilterOperator | None = None, left: "FilterExpression | None" = None, right: "FilterExpression | None" = None, + _matches_nothing: bool = False, ): self._filter = _filter + self._none = _matches_nothing self._operator = operator self._left = left self._right = right @@ -897,7 +981,16 @@ def format_expression(left, right, operator_str) -> str: return _left return f"({_left}{operator_str}{_right})" - def __str__(self) -> str: + def _render(self) -> tuple[str, bool]: + """Render this expression, and report whether it can match no document. + + A filter that matches nothing has to survive composition as what it is. + ``*`` can be elided from either operator, since it constrains nothing. + An empty filter cannot: elided from an ``&`` it would widen the query, + which is the failure this exists to prevent. So it absorbs an ``&`` and + drops out of a ``|``, as the empty set does, and ``*`` is still + elided around it. + """ # top level check that allows recursive calls to __str__ if not self._filter and not self._operator: raise ValueError("Improperly initialized FilterExpression") @@ -911,13 +1004,31 @@ def __str__(self) -> str: "Improper combination of filters. Both left and right should be type FilterExpression" ) + left, left_none = self._left._render() + right, right_none = self._right._render() + if self._operator == FilterOperator.AND: + if left_none: + return left, True + if right_none: + return right, True + elif left_none and right_none: + return left, True + elif left_none: + # `*` is elided against anything, which leaves the empty side. + return (left, True) if right == "*" else (right, False) + elif right_none: + return (right, True) if left == "*" else (left, False) + operator_str = " | " if self._operator == FilterOperator.OR else " " - return self.format_expression(self._left, self._right, operator_str) + return self.format_expression(left, right, operator_str), False # check that base case, the filter is set if not self._filter: raise ValueError("Improperly initialized FilterExpression") - return self._filter + return self._filter, self._none + + def __str__(self) -> str: + return self._render()[0] def is_match_all_filter(filter_expression: str | FilterExpression | None) -> bool: diff --git a/tests/integration/test_query.py b/tests/integration/test_query.py index 8516d2260..ce58407d7 100644 --- a/tests/integration/test_query.py +++ b/tests/integration/test_query.py @@ -334,6 +334,57 @@ def test_count_query(index, sample_data): assert results == 4 +def test_empty_tag_list_matches_nothing_when_combined(index, sample_data): + """An empty list must narrow a query, however it is combined or queried.""" + empty = Tag("credit_score") == [] + high = Tag("credit_score") == "high" + adult = Num("age") >= 18 + fields = ["user", "credit_score", "age"] + + def users(expression): + return { + doc["user"] + for doc in index.query( + FilterQuery(filter_expression=expression, return_fields=fields) + ) + } + + assert users(empty) == set() + # The failing case: an empty list beside a real clause used to be dropped. + assert users(high & empty) == set() + assert users(adult & empty) == set() + assert users(empty & high & adult) == set() + assert users((high & adult) & empty) == set() + # OR keeps the other side, as the union with the empty set does. + assert users(high | empty) == users(high) != set() + assert users(empty | high) == users(high) + # Not in the empty set is every document. + assert users((Tag("credit_score") != []) & high) == users(high) + # `None` stays "no constraint". + assert users(high & (Tag("credit_score") == None)) == users(high) + + assert index.query(CountQuery(high & empty)) == 0 + assert index.query(CountQuery(empty)) == 0 + assert index.query(CountQuery(high | empty)) == index.query(CountQuery(high)) + + for expression in (empty, high & empty): + vector_query = VectorQuery( + vector=[0.1, 0.1, 0.5], + vector_field_name="user_embedding", + return_fields=fields, + filter_expression=expression, + ) + assert index.query(vector_query) == [] + range_query = VectorRangeQuery( + vector=[0.1, 0.1, 0.5], + vector_field_name="user_embedding", + return_fields=fields, + distance_threshold=10, + filter_expression=expression, + ) + assert index.query(range_query) == [] + + def search( query, index, @@ -416,8 +467,12 @@ def test_filters(index, query, sample_datetimes): t = Tag("credit_score") == ["high", "low"] search(query, index, t, 6) - # Empty tag filter + # Empty tag filter: an empty set of tags selects no document t = Tag("credit_score") == [] + search(query, index, t, 0) + + # `None` is the way to ask for no constraint + t = Tag("credit_score") == None search(query, index, t, 7) # Simple Numeric Filter @@ -468,8 +523,8 @@ def test_filters(index, query, sample_datetimes): t = Text("description") != 'high stress,"' search(query, index, t, 6) - # Test empty filters - t = Text("job") % "" + # `None` is no constraint; an empty string is refused (see the unit tests) + t = Text("job") % None search(query, index, t, 7) # Timestamps @@ -674,17 +729,17 @@ def test_no_content_query_returns_ids(index, sample_data): def test_sort_filter_query(index, sorted_filter_query): - t = Text("job") % "" + t = Text("job") % None search(sorted_filter_query, index, t, 7, sort=True) def test_sort_vector_query(index, sorted_vector_query): - t = Text("job") % "" + t = Text("job") % None search(sorted_vector_query, index, t, 7, sort=True) def test_sort_range_query(index, sorted_range_query): - t = Text("job") % "" + t = Text("job") % None search(sorted_range_query, index, t, 7, sort=True) @@ -1171,6 +1226,23 @@ def missing_fields_index(worker_id, client): missing_index.delete(drop=True) +def test_empty_string_tag_matches_the_empty_value_only(missing_fields_index): + """`""` is a tag value of its own, as `INDEXEMPTY` makes it on the server.""" + missing_index, prefix = missing_fields_index + + def ids(expression): + query = FilterQuery(filter_expression=expression, return_fields=["id"]) + return {result["id"] for result in missing_index.query(query)} + + assert ids(Tag("category") == "") == {f"{prefix}:empty_strings"} + assert ids(Tag("category") == [""]) == {f"{prefix}:empty_strings"} + assert f"{prefix}:empty_strings" not in ids(Tag("category") != "") + assert f"{prefix}:complete" in ids(Tag("category") != "") + assert ids((Tag("category") == "") & (Num("price") > 1000)) == set() + # An empty list still selects nothing, and is not the empty-string tag. + assert ids(Tag("category") == []) == set() + + def test_basic_missing_field_queries(missing_fields_index): """ Test the fundamental is_missing() functionality across all supported field types. @@ -1365,7 +1437,7 @@ def test_complex_missing_field_combinations(missing_fields_index): # Find documents complete enough for display (have both title AND category) display_ready_documents = FilterQuery( - filter_expression=(Text("title") != "") & (Tag("category") != ""), + filter_expression=Tag("category") != "", return_fields=["id", "title", "category"], ) results = missing_index.query(display_ready_documents) @@ -1408,7 +1480,7 @@ def test_data_quality_completeness_analysis(missing_fields_index): # Identify records ready for public display (quality threshold check) display_ready = FilterQuery( - filter_expression=Text("title") != "", + filter_expression=Tag("category") != "", return_fields=["id", "title", "description"], ) results = missing_index.query(display_ready) diff --git a/tests/unit/test_filter.py b/tests/unit/test_filter.py index 8377e9f43..19af8af2f 100644 --- a/tests/unit/test_filter.py +++ b/tests/unit/test_filter.py @@ -75,6 +75,9 @@ def test_tag_filter_varied(operation, tags, expected): assert str(tf) == expected +NO_MATCH = "(@tag_field:{redisvl_no_match} -@tag_field:{redisvl_no_match})" + + @pytest.mark.parametrize( "pattern,expected", [ @@ -88,9 +91,10 @@ def test_tag_filter_varied(operation, tags, expected): ("hello w*", "@tag_field:{hello\\ w*}"), # Multiple wildcards in same pattern ("*test*", "@tag_field:{*test*}"), - # Empty pattern returns wildcard match-all - ("", "*"), - ([], "*"), + # `None` is no constraint; an empty collection selects no tag, so it + # matches nothing; `""` is the empty tag RediSearch stores. + ("", '@tag_field:{""}'), + ([], NO_MATCH), (None, "*"), # Pattern with special characters ("cat$*", "@tag_field:{cat\\$*}"), @@ -175,22 +179,40 @@ def test_tag_wildcard_combined_with_exact_match(): "operation, value, expected", [ ("__eq__", None, "*"), - ("__eq__", [], "*"), - ("__eq__", "", "*"), - ("__eq__", [None], "*"), + ("__eq__", [], NO_MATCH), + ("__eq__", (), NO_MATCH), + ("__eq__", set(), NO_MATCH), + ("__eq__", "", '@tag_field:{""}'), + ("__eq__", [""], '@tag_field:{""}'), + ("__eq__", ["", "tag"], '@tag_field:{""|tag}'), + ("__eq__", [None], NO_MATCH), + ("__eq__", [0], "@tag_field:{0}"), + ("__mod__", [], NO_MATCH), ("__eq__", [None, "tag"], "@tag_field:{tag}"), - # Tag.__str__ short-circuits to "*" before consulting OPERATOR_MAP, so - # one falsy row covers every falsy value on the negated operator too. + # Not in the empty set is every document, so `!=` an empty collection + # constrains nothing, while `!= ""` excludes the empty tag. ("__ne__", None, "*"), + ("__ne__", [], "*"), + ("__ne__", [None], "*"), + ("__ne__", "", '(-@tag_field:{""})'), ("__ne__", [None, "tag"], "(-@tag_field:{tag})"), ], ids=[ "none", "empty_list", + "empty_tuple", + "empty_set", "empty_string", + "list_with_empty_string", + "empty_string_and_tag", "list_with_none", + "list_with_zero", + "like_empty_list", "list_with_none_and_tag", "ne_none", + "ne_empty_list", + "ne_list_with_none", + "ne_empty_string", "ne_list_with_none_and_tag", ], ) @@ -300,14 +322,11 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): [ ("__eq__", "text", '@text_field:("text")'), ("__ne__", "text", '(-@text_field:"text")'), - ("__eq__", "", "*"), - ("__ne__", "", "*"), ("__eq__", None, "*"), ("__ne__", None, "*"), ("__mod__", "text", "@text_field:(text)"), ("__mod__", "tex*", "@text_field:(tex*)"), ("__mod__", "%text%", "@text_field:(%text%)"), - ("__mod__", "", "*"), ("__mod__", None, "*"), # The quote is the only character that can terminate a quoted value, so # it goes and everything it carried stays inside the phrase. @@ -350,14 +369,11 @@ def test_numeric_refuses_an_unrenderable_value(call, expected_error): ids=[ "eq", "ne", - "eq-empty", - "ne-empty", "eq-none", "ne-none", "like", "like_wildcard", "like_full", - "like_empty", "like_none", "eq_quote_neutralized", "ne_quote_neutralized", @@ -615,14 +631,34 @@ def test_filters_combination(): combined = tf1 | tf2 assert str(combined) == "(@tag_field:{tag1|tag2} | @tag_field:{tag3})" + # An empty collection matches nothing: it absorbs an AND and drops out of + # an OR, as the empty set does. Eliding it from the AND would widen the query. tf1 = Tag("tag_field") == [] - assert str(tf1) == "*" - assert str(tf1 & tf2) == str(tf2) + assert str(tf1) == NO_MATCH + assert str(tf1 & tf2) == NO_MATCH + assert str(tf2 & tf1) == NO_MATCH assert str(tf1 | tf2) == str(tf2) + assert str(tf2 | tf1) == str(tf2) + assert str(tf1 & tf1) == NO_MATCH + assert str(tf1 | tf1) == NO_MATCH + + # Nesting does not lose it: the AND is absorbed wherever it sits. + other = Tag("other") == "x" + assert str((tf2 & other) & tf1) == NO_MATCH + assert str((tf2 | other) & tf1) == NO_MATCH + assert str((tf1 & tf2) | other) == str(other) + + # `None` is no constraint, and is elided around a match-nothing filter + # rather than widening it. + assert str(tf1 & (Tag("tag_field") == None)) == NO_MATCH + assert str(tf1 | (Tag("tag_field") == None)) == NO_MATCH + + # `!=` an empty collection excludes nothing, so it is elided like `None`. + assert str((Tag("tag_field") != []) & tf2) == str(tf2) # test combining filters with None values and empty strings tf1 = Tag("tag_field") == None - tf2 = Tag("tag_field") == "" + tf2 = Tag("tag_field") == None assert str(tf1 & tf2) == "*" tf1 = Tag("tag_field") == None @@ -637,7 +673,7 @@ def test_filters_combination(): tf2 = Tag("tag_field") != None assert str(tf1 & tf2) == "*" - tf1 = Tag("tag_field") == "" + tf1 = Tag("tag_field") == None tf2 = Tag("tag_field") == "tag" tf3 = Tag("tag_field") == ["tag1", "tag2"] assert str(tf1 & tf2 & tf3) == str(tf2 & tf3) @@ -1101,8 +1137,12 @@ def test_render_filter_with_filter_expression_inputs(): """ assert render_filter(Tag("category") == "tech") == "@category:{tech}" - # An empty filter renders as "*", which means "no filtering". - assert render_filter(Tag("category") == []) is None + # `None` renders as "*", which means "no filtering"; an empty collection + # is a filter that matches nothing, and is kept. + assert render_filter(Tag("category") == None) is None + assert render_filter(Tag("category") == []) == ( + "(@category:{redisvl_no_match} -@category:{redisvl_no_match})" + ) field = Tag("category") before = str(field) @@ -1139,10 +1179,48 @@ def test_intersect_with_filter(filter_expression, expected): # The reason this helper exists rather than a bare `str(expr) != "*"` at # each call site: an un-initialized FilterExpression raises on render. pytest.param(FilterExpression(), True, id="uninitialized-raises"), - pytest.param(Tag("t") == "", True, id="empty-tag-renders-wildcard"), + pytest.param(Tag("t") == None, True, id="none-tag-renders-wildcard"), + pytest.param(Tag("t") == [], False, id="empty-list-is-not-match-all"), pytest.param(Tag("t") == "acme", False, id="tag-equality"), pytest.param("@t:{acme}", False, id="rendered-string"), ], ) def test_is_match_all_filter(filter_expression, expected): assert is_match_all_filter(filter_expression) is expected + + +@pytest.mark.parametrize("operation", ["__eq__", "__ne__", "__mod__"]) +def test_text_refuses_an_empty_string(operation): + # `@f:("")` beside another clause is read against that clause's field and + # rejected by the server, so an empty string would give a filter whose + # meaning depends on operand order. `None` is how to ask for no constraint. + with pytest.raises(ValueError, match="non-empty"): + getattr(Text("text_field"), operation)("") + + +@pytest.mark.parametrize("operation", ["__eq__", "__ne__", "__mod__"]) +def test_text_still_treats_none_as_no_constraint(operation): + assert str(getattr(Text("text_field"), operation)(None)) == "*" + + +@pytest.mark.parametrize("empty", [[], (), set()], ids=["list", "tuple", "set"]) +def test_text_and_num_still_refuse_a_collection(empty): + # Already fail-closed: only Tag takes a collection. + with pytest.raises(TypeError): + Text("t") == empty + with pytest.raises(TypeError): + Num("n") == empty + + +def test_an_empty_tag_filter_matches_nothing_inside_a_permission_filter(): + tenant = Tag("tenant") == "acme" + groups: list[str] = [] + assert str(tenant & (Tag("groups") == groups)) == ( + "(@groups:{redisvl_no_match} -@groups:{redisvl_no_match})" + ) + assert str(Tag("groups") == groups) == str(Tag("groups") % groups) + # The field object itself renders the same once built. + field = Tag("groups") + field == groups + assert str(field) == "(@groups:{redisvl_no_match} -@groups:{redisvl_no_match})" + assert is_match_all_filter(tenant & (Tag("groups") == groups)) is False diff --git a/tests/unit/test_mcp/test_auth_claim_injection.py b/tests/unit/test_mcp/test_auth_claim_injection.py index 1523427c2..9dd25ea9f 100644 --- a/tests/unit/test_mcp/test_auth_claim_injection.py +++ b/tests/unit/test_mcp/test_auth_claim_injection.py @@ -178,13 +178,13 @@ def test_no_entries_refuses_rather_than_matching_everything(monkeypatch): def test_an_injected_clause_cannot_be_elided_by_the_intersection(monkeypatch): - # `Tag(f) == ""` renders as the match-all `*`, and an intersection drops a + # `Tag(f) == None` renders as the match-all `*`, and an intersection drops a # `*` operand -- so `locked & injected` would render as `locked` alone with # the tenant clause silently gone. The guard therefore runs on the injected # clause by itself, before any combination. from redisvl.query.filter import Tag - injected = Tag("org_id") == "" + injected = Tag("org_id") == None locked = Tag("status") == "resolved" assert str(locked & injected) == str(locked) @@ -204,7 +204,7 @@ def test_a_clause_that_renders_match_all_is_refused_even_so(monkeypatch): """ monkeypatch.setattr( "redisvl.mcp.auth.resolve_injected_claim", - lambda claim, *, tool_name: "", + lambda claim, *, tool_name: None, ) with pytest.raises(RedisVLMCPError) as exc: build_injected_filter([_Spec("org_id", "org_id")], tool_name="search_kb") diff --git a/tests/unit/test_semantic_router_queries.py b/tests/unit/test_semantic_router_queries.py index 4eb4938c7..643617718 100644 --- a/tests/unit/test_semantic_router_queries.py +++ b/tests/unit/test_semantic_router_queries.py @@ -17,7 +17,7 @@ def test_reference_id_query_is_scoped_to_the_id(): @pytest.mark.parametrize("empty", ["", None], ids=["empty_string", "none"]) def test_empty_reference_id_is_rejected_rather_than_matching_everything(empty): - # `Tag("reference_id") == ""` renders as `*`. Callers read the first row of + # `Tag("reference_id") == None` renders as `*`. Callers read the first row of # each query's results, so a match-all here returns -- and, from # delete_route_references, deletes -- a reference nobody named. with pytest.raises(ValueError, match="non-empty"): From 3510da8418a2eee2fe4b8075be2f5d8d97bdf002 Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Thu, 12 Nov 2026 11:43:49 +0100 Subject: [PATCH 2/3] refactor(query): let the no-match clause carry the empty-tag semantics Drop the private flag threaded through FilterExpression. The contradiction clause already matches nothing wherever it sits, so it narrows an AND and adds nothing to an OR without any special composition, and operands keep rendering verbatim. Review follow-ups: tighten tests that could pass vacuously, and correct the docs on what INDEXEMPTY does and does not guarantee. --- docs/concepts/mcp.md | 3 +- docs/user_guide/02_complex_filtering.ipynb | 4 +- redisvl/query/filter.py | 104 ++++++--------------- tests/integration/test_query.py | 24 ++--- tests/unit/test_filter.py | 57 +++++------ 5 files changed, 66 insertions(+), 126 deletions(-) diff --git a/docs/concepts/mcp.md b/docs/concepts/mcp.md index ab012e0ff..4b75f2af9 100644 --- a/docs/concepts/mcp.md +++ b/docs/concepts/mcp.md @@ -225,7 +225,8 @@ The claim must be a single, non-empty string. Anything else refuses the request | Claim value | Why it is refused | |---|---| | Absent, or the request has no token | There is no tenant to scope to. | -| `null` or `""` | An empty tag value is not a tenant to scope to. | +| `null` | It renders as `*`, which would drop the tenant clause from the query entirely. | +| `""` | An empty tag value is not a tenant to scope to. | | A list, such as `["acme", "victim"]` | It would render as a union, `@org_id:{acme\|victim}`, which spans both tenants. | | An object, number or boolean | It is not a tenant identifier. | | Padded with whitespace | It cannot be a real tenant identifier, and refusing is safer than guessing which tenant was meant. | diff --git a/docs/user_guide/02_complex_filtering.ipynb b/docs/user_guide/02_complex_filtering.ipynb index 803d421e5..bfa8340ef 100644 --- a/docs/user_guide/02_complex_filtering.ipynb +++ b/docs/user_guide/02_complex_filtering.ipynb @@ -389,11 +389,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "What about scenarios where you might want to dynamically generate a list of tags? Redis treats an empty set of tags as a set that selects nothing, and so does RedisVL, so a Tag filter built from an empty list **matches no documents**:\n", + "What about scenarios where you might want to dynamically generate a list of tags? Redis has no syntax for an empty set of tags, so RedisVL treats one as selecting nothing: a Tag filter built from an empty list **matches no documents**:\n", "\n", "`Tag(\"credit_score\") == []`\n", "\n", - "This is deliberate. When the list holds permitted values, such as a user's groups, an empty list must not widen the query. Combined with other filters, an empty list still matches nothing: `(Tag(\"tenant\") == \"acme\") & (Tag(\"groups\") == [])` returns no documents, and `|` ignores it.\n", + "This is deliberate. When the list holds permitted values, such as a user's groups, an empty list must not widen the query. Combined with other filters, an empty list still matches nothing: `(Tag(\"tenant\") == \"acme\") & (Tag(\"groups\") == [])` returns no documents, and in a `|` it adds nothing to the other side's matches.\n", "\n", "To mean \"no constraint\", pass `None` instead, which yields a `*` Redis query filter -- there is no filter here to use. Use `!= []` to exclude nothing." ] diff --git a/redisvl/query/filter.py b/redisvl/query/filter.py index 0888881dd..2bf2a5112 100644 --- a/redisvl/query/filter.py +++ b/redisvl/query/filter.py @@ -75,18 +75,6 @@ def _set_value( self._value = val self._operator = operator - def _matches_nothing(self) -> bool: - """Report whether this filter, as built, can match no document.""" - return False - - def _expression(self) -> "FilterExpression": - """Wrap this filter's rendering, remembering whether it matches nothing. - - ``FilterExpression`` composes by rendering, so the fact has to travel - beside the string: see ``FilterExpression._render``. - """ - return FilterExpression(str(self), _matches_nothing=self._matches_nothing()) - def is_missing(self) -> "FilterExpression": """Create a filter expression for documents missing this field. @@ -131,14 +119,16 @@ class Tag(FilterField): """A Tag filter can be applied to Tag fields Note: - Empty values follow Redis, which has no empty tag set. ``None`` means - no constraint and renders ``*``. An empty collection (``[]``, ``()``, - ``set()``, or one holding only ``None``) selects no tag, so ``==`` and - ``%`` match no document, whatever it is combined with: an ``&`` with it - matches nothing, and a ``|`` ignores it. ``!=`` an empty collection - excludes nothing and renders ``*``. ``""`` is a tag of its own, - rendered ``@field:{""}``, which needs ``INDEXEMPTY`` on the field and - DIALECT 2 or later. + Empty values follow Redis, which has no syntax for an empty set of + tags. ``None`` means no constraint and renders ``*``. An empty + collection (``[]``, ``()``, ``set()``, or one holding only ``None``) + selects no tag, so ``==`` and ``%`` match no document: ``&`` with it + matches nothing, and ``|`` leaves the other side's matches unchanged. + ``!=`` an empty collection excludes nothing and renders ``*``. ``""`` is + a tag of its own, rendered ``@field:{""}``. That needs DIALECT 2 or + later and ``INDEXEMPTY`` on the field; without ``INDEXEMPTY`` the + server rejects it in some query positions and silently returns results + in others, so do not use it on such a field. .. code-block:: python @@ -194,14 +184,6 @@ def _set_tag_value( self._set_value(other, self.SUPPORTED_VAL_TYPES, operator) - def _matches_nothing(self) -> bool: - # `!=` an empty collection excludes nothing, so it keeps every document. - return ( - self._value is not None - and not self._value - and self._operator != FilterOperator.NE - ) - @check_operator_misuse def __eq__(self, other: list[str] | str) -> "FilterExpression": """Create a Tag equality filter expression. @@ -216,7 +198,7 @@ def __eq__(self, other: list[str] | str) -> "FilterExpression": f = Tag("brand") == "nike" """ self._set_tag_value(other, FilterOperator.EQ) - return self._expression() + return FilterExpression(str(self)) @check_operator_misuse def __ne__(self, other: list[str] | str) -> "FilterExpression": @@ -232,7 +214,7 @@ def __ne__(self, other: list[str] | str) -> "FilterExpression": """ self._set_tag_value(other, FilterOperator.NE) - return self._expression() + return FilterExpression(str(self)) def __mod__(self, other: list[str] | str) -> "FilterExpression": """Create a Tag wildcard filter expression for pattern matching. @@ -260,7 +242,7 @@ def __mod__(self, other: list[str] | str) -> "FilterExpression": """ self._set_tag_value(other, FilterOperator.LIKE) - return self._expression() + return FilterExpression(str(self)) @property def _formatted_tag_value(self) -> str: @@ -780,6 +762,8 @@ class Text(FilterField): therefore becomes an empty phrase, which ``==`` matches no document against. ``%`` is the pattern operator and interpolates its value untouched. + + An empty string raises ``ValueError``; pass ``None`` for no constraint. """ OPERATORS: dict[FilterOperator, str] = { @@ -807,13 +791,13 @@ def _set_value( operator: FilterOperator, ): if isinstance(val, str) and not val: - # `@f:("")` is how RediSearch asks for an empty string, but beside - # another clause the server reads it against that clause's field - # and rejects it for lacking `INDEXEMPTY` (measured on 8.4: - # `@t:{a} @x:("")` fails with `x` indexed empty, `@x:("") @t:{a}` - # does not). Rendering it would make a filter's meaning depend on - # operand order, so it is refused. `None` is how to ask for no - # constraint, and `is_missing()` finds an absent field. + # `@f:("")` is how RediSearch asks for an empty string, but after a + # TAG clause the server checks it against that tag field's + # `INDEXEMPTY` instead of this field's (measured on 8.4: `@t:{a} + # @x:("")` fails with `x` indexed empty, `@x:("") @t:{a}` does not). + # Rendering it would make a filter's meaning depend on operand + # order, so it is refused. `None` is how to ask for no constraint, + # and `is_missing()` finds an absent field. raise ValueError( f"{self.__class__.__name__} value must be a non-empty string; " "pass None for no constraint" @@ -939,10 +923,11 @@ class FilterExpression: ) Note: - A filter that can match no document, such as ``Tag("g") == []``, keeps - that meaning when combined: it absorbs an ``&`` and drops out of a - ``|``. ``*`` (from ``None``) is elided from both, and is the only - value that means "no constraint". + A filter that can match no document, such as ``Tag("g") == []``, is + rendered as a clause that matches nothing, so it narrows an ``&`` and + adds nothing to a ``|``. ``*`` (from ``None``, or ``!=`` an empty + collection) constrains nothing and is elided from both operators, which + means ``None | empty`` matches nothing. Note: Filter expressions are typically not called directly. Instead they are @@ -956,10 +941,8 @@ def __init__( operator: FilterOperator | None = None, left: "FilterExpression | None" = None, right: "FilterExpression | None" = None, - _matches_nothing: bool = False, ): self._filter = _filter - self._none = _matches_nothing self._operator = operator self._left = left self._right = right @@ -981,16 +964,7 @@ def format_expression(left, right, operator_str) -> str: return _left return f"({_left}{operator_str}{_right})" - def _render(self) -> tuple[str, bool]: - """Render this expression, and report whether it can match no document. - - A filter that matches nothing has to survive composition as what it is. - ``*`` can be elided from either operator, since it constrains nothing. - An empty filter cannot: elided from an ``&`` it would widen the query, - which is the failure this exists to prevent. So it absorbs an ``&`` and - drops out of a ``|``, as the empty set does, and ``*`` is still - elided around it. - """ + def __str__(self) -> str: # top level check that allows recursive calls to __str__ if not self._filter and not self._operator: raise ValueError("Improperly initialized FilterExpression") @@ -1004,31 +978,13 @@ def _render(self) -> tuple[str, bool]: "Improper combination of filters. Both left and right should be type FilterExpression" ) - left, left_none = self._left._render() - right, right_none = self._right._render() - if self._operator == FilterOperator.AND: - if left_none: - return left, True - if right_none: - return right, True - elif left_none and right_none: - return left, True - elif left_none: - # `*` is elided against anything, which leaves the empty side. - return (left, True) if right == "*" else (right, False) - elif right_none: - return (right, True) if left == "*" else (left, False) - operator_str = " | " if self._operator == FilterOperator.OR else " " - return self.format_expression(left, right, operator_str), False + return self.format_expression(self._left, self._right, operator_str) # check that base case, the filter is set if not self._filter: raise ValueError("Improperly initialized FilterExpression") - return self._filter, self._none - - def __str__(self) -> str: - return self._render()[0] + return self._filter def is_match_all_filter(filter_expression: str | FilterExpression | None) -> bool: diff --git a/tests/integration/test_query.py b/tests/integration/test_query.py index ce58407d7..a8e770bc4 100644 --- a/tests/integration/test_query.py +++ b/tests/integration/test_query.py @@ -353,7 +353,6 @@ def users(expression): # The failing case: an empty list beside a real clause used to be dropped. assert users(high & empty) == set() assert users(adult & empty) == set() - assert users(empty & high & adult) == set() assert users((high & adult) & empty) == set() # OR keeps the other side, as the union with the empty set does. assert users(high | empty) == users(high) != set() @@ -363,7 +362,6 @@ def users(expression): # `None` stays "no constraint". assert users(high & (Tag("credit_score") == None)) == users(high) - assert index.query(CountQuery(high & empty)) == 0 assert index.query(CountQuery(empty)) == 0 assert index.query(CountQuery(high | empty)) == index.query(CountQuery(high)) @@ -1238,7 +1236,7 @@ def ids(expression): assert ids(Tag("category") == [""]) == {f"{prefix}:empty_strings"} assert f"{prefix}:empty_strings" not in ids(Tag("category") != "") assert f"{prefix}:complete" in ids(Tag("category") != "") - assert ids((Tag("category") == "") & (Num("price") > 1000)) == set() + assert ids((Tag("category") == "") & (Num("price") < 100)) == set() # An empty list still selects nothing, and is not the empty-string tag. assert ids(Tag("category") == []) == set() @@ -1435,13 +1433,15 @@ def test_complex_missing_field_combinations(missing_fields_index): assert len(results) == 1 assert results[0]["id"] == f"{prefix}:mostly_missing" - # Find documents complete enough for display (have both title AND category) - display_ready_documents = FilterQuery( + # Exclude documents whose category is the empty string. `!=` is a negation, + # so documents that lack the field entirely are kept. + non_empty_category = FilterQuery( filter_expression=Tag("category") != "", - return_fields=["id", "title", "category"], + return_fields=["id"], ) - results = missing_index.query(display_ready_documents) - assert len(results) >= 2 # Should find complete and zero_price documents + results = missing_index.query(non_empty_category) + assert f"{prefix}:empty_strings" not in {result["id"] for result in results} + assert f"{prefix}:complete" in {result["id"] for result in results} def test_data_quality_completeness_analysis(missing_fields_index): @@ -1478,14 +1478,6 @@ def test_data_quality_completeness_analysis(missing_fields_index): completion_rate > 0.3 ) # At least 30% of docs should be complete with test data - # Identify records ready for public display (quality threshold check) - display_ready = FilterQuery( - filter_expression=Tag("category") != "", - return_fields=["id", "title", "description"], - ) - results = missing_index.query(display_ready) - assert len(results) >= 1 # Should have at least some displayable documents - def test_missing_fields_workflow_filtering(missing_fields_index): """ diff --git a/tests/unit/test_filter.py b/tests/unit/test_filter.py index 19af8af2f..0aac2f9bb 100644 --- a/tests/unit/test_filter.py +++ b/tests/unit/test_filter.py @@ -631,32 +631,34 @@ def test_filters_combination(): combined = tf1 | tf2 assert str(combined) == "(@tag_field:{tag1|tag2} | @tag_field:{tag3})" - # An empty collection matches nothing: it absorbs an AND and drops out of - # an OR, as the empty set does. Eliding it from the AND would widen the query. + # An empty collection is a clause that matches nothing, so it stays in an + # AND, where it narrows to nothing, and adds nothing to an OR. Eliding it + # from the AND, as `*` is, would widen the query. tf1 = Tag("tag_field") == [] assert str(tf1) == NO_MATCH - assert str(tf1 & tf2) == NO_MATCH - assert str(tf2 & tf1) == NO_MATCH - assert str(tf1 | tf2) == str(tf2) - assert str(tf2 | tf1) == str(tf2) - assert str(tf1 & tf1) == NO_MATCH - assert str(tf1 | tf1) == NO_MATCH - - # Nesting does not lose it: the AND is absorbed wherever it sits. + assert str(tf1 & tf2) == f"({NO_MATCH} @tag_field:{{tag3}})" + assert str(tf2 & tf1) == f"(@tag_field:{{tag3}} {NO_MATCH})" + assert str(tf1 | tf2) == f"({NO_MATCH} | @tag_field:{{tag3}})" + + # Nesting does not lose it. other = Tag("other") == "x" - assert str((tf2 & other) & tf1) == NO_MATCH - assert str((tf2 | other) & tf1) == NO_MATCH - assert str((tf1 & tf2) | other) == str(other) + assert NO_MATCH in str((tf2 & other) & tf1) + assert NO_MATCH in str((tf2 | other) & tf1) - # `None` is no constraint, and is elided around a match-nothing filter - # rather than widening it. + # `None` is no constraint and is elided from either operator, so beside a + # match-nothing filter it leaves that filter, in either order. assert str(tf1 & (Tag("tag_field") == None)) == NO_MATCH + assert str((Tag("tag_field") == None) & tf1) == NO_MATCH assert str(tf1 | (Tag("tag_field") == None)) == NO_MATCH + assert str((Tag("tag_field") == None) | tf1) == NO_MATCH # `!=` an empty collection excludes nothing, so it is elided like `None`. assert str((Tag("tag_field") != []) & tf2) == str(tf2) - # test combining filters with None values and empty strings + # `""` is a tag of its own and is kept inside an AND. + assert str((Tag("tag_field") == "") & tf2) == '(@tag_field:{""} @tag_field:{tag3})' + + # test combining filters with None values tf1 = Tag("tag_field") == None tf2 = Tag("tag_field") == None assert str(tf1 & tf2) == "*" @@ -1198,29 +1200,18 @@ def test_text_refuses_an_empty_string(operation): getattr(Text("text_field"), operation)("") -@pytest.mark.parametrize("operation", ["__eq__", "__ne__", "__mod__"]) -def test_text_still_treats_none_as_no_constraint(operation): - assert str(getattr(Text("text_field"), operation)(None)) == "*" - - -@pytest.mark.parametrize("empty", [[], (), set()], ids=["list", "tuple", "set"]) -def test_text_and_num_still_refuse_a_collection(empty): - # Already fail-closed: only Tag takes a collection. - with pytest.raises(TypeError): - Text("t") == empty +def test_text_still_refuses_a_collection(): with pytest.raises(TypeError): - Num("n") == empty + Text("t") == [] -def test_an_empty_tag_filter_matches_nothing_inside_a_permission_filter(): +def test_an_empty_tag_list_narrows_a_permission_filter(): tenant = Tag("tenant") == "acme" groups: list[str] = [] - assert str(tenant & (Tag("groups") == groups)) == ( - "(@groups:{redisvl_no_match} -@groups:{redisvl_no_match})" - ) - assert str(Tag("groups") == groups) == str(Tag("groups") % groups) + permission = tenant & (Tag("groups") == groups) + assert "(@groups:{redisvl_no_match} -@groups:{redisvl_no_match})" in str(permission) + assert is_match_all_filter(permission) is False # The field object itself renders the same once built. field = Tag("groups") field == groups assert str(field) == "(@groups:{redisvl_no_match} -@groups:{redisvl_no_match})" - assert is_match_all_filter(tenant & (Tag("groups") == groups)) is False From 9c58c13994a373aec78d1b649d59409ce558ca1d Mon Sep 17 00:00:00 2001 From: Vishal Bala Date: Thu, 12 Nov 2026 11:54:04 +0100 Subject: [PATCH 3/3] test(query): tighten empty-filter tests and correct related docs Pin that Text refuses a collection in its type check, make the empty-tag AND test match a real document, and drop assertions that duplicate others. Remove a comment that repeated the Tag docstring, say why Tag renders an empty string while Text refuses one, and stop describing an empty Tag list as match-all in render_filter and the bulk-operation guard docs. --- docs/concepts/search-and-indexing.md | 2 +- redisvl/extensions/router/semantic.py | 12 ++++++------ redisvl/query/filter.py | 13 +++++-------- tests/integration/test_query.py | 14 +++----------- tests/unit/test_filter.py | 18 +----------------- 5 files changed, 16 insertions(+), 43 deletions(-) diff --git a/docs/concepts/search-and-indexing.md b/docs/concepts/search-and-indexing.md index 5cab8733b..f19c94f3b 100644 --- a/docs/concepts/search-and-indexing.md +++ b/docs/concepts/search-and-indexing.md @@ -126,7 +126,7 @@ Both methods share the same safety-oriented options and return a `BulkResult`: - The return value carries `matched` (documents matching the filter), `processed` (documents actually affected), `completed` (False if a delete stopped early—at its runaway backstop, or on a batch it could not remove; always True for update), and `dry_run`. Read the fields explicitly—`result.processed`, `result.completed`, etc. - `dry_run=True` reports how many documents *would* be affected—via a count query—without changing anything. -- A match-all filter (empty, `"*"`, or `None`) is refused unless you pass `allow_all=True`; use `clear()` when you intentionally want to empty the index. This guard catches the canonical match-all forms only—it is a convenience backstop, not a security control. +- A match-all filter (an empty string, `"*"`, `None`, or a filter that renders as `*`, such as `Tag(f) == None`) is refused unless you pass `allow_all=True`; use `clear()` when you intentionally want to empty the index. This guard catches the canonical match-all forms only—it is a convenience backstop, not a security control. - `on_progress(processed, matched)` is called after each write batch for observability on large operations (it runs synchronously—don't pass a coroutine—and raising from it aborts the run). Note `update_by_filter` resolves all matching keys before it writes, so progress callbacks begin only once the write phase starts. `batch_size` tunes how many documents are processed per round-trip. The related `drop_documents()` and `drop_keys()` helpers delete by document ID or full Redis key and batch large inputs. On Redis Cluster, `drop_keys()` unlinks per-key so it works across hash slots, while `drop_documents()` requires the target keys to share a hash tag and raises `ValueError` otherwise. Unlinking per-key also means a failure on one key is logged rather than raised, so one bad key does not abort the batch—but the returned count can then come back lower than the number of keys you passed with no exception to catch. The count alone cannot tell that apart from a key that simply did not exist. diff --git a/redisvl/extensions/router/semantic.py b/redisvl/extensions/router/semantic.py index cfed1ec95..bbece17a3 100644 --- a/redisvl/extensions/router/semantic.py +++ b/redisvl/extensions/router/semantic.py @@ -1108,12 +1108,12 @@ def _make_filter_queries(ids: list[str]) -> list[FilterQuery]: for id in ids: if not id: - # `Tag(...) == None` renders as the match-all `*`, so an empty id - # would match every reference in the index, and `""` asks the - # server for an empty tag, which no reference carries. Callers - # take the first row of each query's results, which turns the - # first into returning -- and, from delete_route_references, - # deleting -- an arbitrary reference the caller never named. + # `None` renders as the match-all `*` and would match every + # reference; `""` renders `@reference_id:{""}`, which this index + # cannot answer reliably without `INDEXEMPTY`. Callers take the + # first row of each query's results, so a match-all returns -- + # and, from delete_route_references, deletes -- an arbitrary + # reference the caller never named. raise ValueError( "reference ids must be non-empty strings; received an empty id" ) diff --git a/redisvl/query/filter.py b/redisvl/query/filter.py index 2bf2a5112..c175f2e84 100644 --- a/redisvl/query/filter.py +++ b/redisvl/query/filter.py @@ -128,7 +128,9 @@ class Tag(FilterField): a tag of its own, rendered ``@field:{""}``. That needs DIALECT 2 or later and ``INDEXEMPTY`` on the field; without ``INDEXEMPTY`` the server rejects it in some query positions and silently returns results - in others, so do not use it on such a field. + in others, so do not use it on such a field. ``Text`` refuses ``""`` + because its server-side failure happens even on a correctly indexed + field; this one only on a field indexed without ``INDEXEMPTY``. .. code-block:: python @@ -170,10 +172,6 @@ class Tag(FilterField): def _set_tag_value( self, other: list[str] | set[str] | str | None, operator: FilterOperator ): - # `None` alone means "no constraint". Anything else is a value: an empty - # collection selects no tag, and `""` is the tag RediSearch stores for - # an empty string, as `@f:{""}` (DIALECT 2+, and `INDEXEMPTY` on the - # field) matches it. if isinstance(other, (list, set, tuple)): try: other = [str(val) for val in other if val is not None] @@ -926,8 +924,7 @@ class FilterExpression: A filter that can match no document, such as ``Tag("g") == []``, is rendered as a clause that matches nothing, so it narrows an ``&`` and adds nothing to a ``|``. ``*`` (from ``None``, or ``!=`` an empty - collection) constrains nothing and is elided from both operators, which - means ``None | empty`` matches nothing. + collection) constrains nothing and is elided from both operators. Note: Filter expressions are typically not called directly. Instead they are @@ -1015,7 +1012,7 @@ def is_match_all_filter(filter_expression: str | FilterExpression | None) -> boo def render_filter(filter_expression: str | FilterExpression | None) -> str | None: """Render a filter expression, or None when it selects every document. - A ``None``, empty, or wildcard (``*``) filter contributes no clause to a + A ``None``, empty-string, or wildcard (``*``) filter contributes no clause to a query: ``*`` is only valid as an entire query, never as one operand of an intersection. diff --git a/tests/integration/test_query.py b/tests/integration/test_query.py index a8e770bc4..f2b5e66f9 100644 --- a/tests/integration/test_query.py +++ b/tests/integration/test_query.py @@ -1236,7 +1236,9 @@ def ids(expression): assert ids(Tag("category") == [""]) == {f"{prefix}:empty_strings"} assert f"{prefix}:empty_strings" not in ids(Tag("category") != "") assert f"{prefix}:complete" in ids(Tag("category") != "") - assert ids((Tag("category") == "") & (Num("price") < 100)) == set() + assert ids((Tag("category") == "") & (Num("price") > 100)) == { + f"{prefix}:empty_strings" + } # An empty list still selects nothing, and is not the empty-string tag. assert ids(Tag("category") == []) == set() @@ -1433,16 +1435,6 @@ def test_complex_missing_field_combinations(missing_fields_index): assert len(results) == 1 assert results[0]["id"] == f"{prefix}:mostly_missing" - # Exclude documents whose category is the empty string. `!=` is a negation, - # so documents that lack the field entirely are kept. - non_empty_category = FilterQuery( - filter_expression=Tag("category") != "", - return_fields=["id"], - ) - results = missing_index.query(non_empty_category) - assert f"{prefix}:empty_strings" not in {result["id"] for result in results} - assert f"{prefix}:complete" in {result["id"] for result in results} - def test_data_quality_completeness_analysis(missing_fields_index): """ diff --git a/tests/unit/test_filter.py b/tests/unit/test_filter.py index 0aac2f9bb..db6fc5d35 100644 --- a/tests/unit/test_filter.py +++ b/tests/unit/test_filter.py @@ -180,8 +180,6 @@ def test_tag_wildcard_combined_with_exact_match(): [ ("__eq__", None, "*"), ("__eq__", [], NO_MATCH), - ("__eq__", (), NO_MATCH), - ("__eq__", set(), NO_MATCH), ("__eq__", "", '@tag_field:{""}'), ("__eq__", [""], '@tag_field:{""}'), ("__eq__", ["", "tag"], '@tag_field:{""|tag}'), @@ -200,8 +198,6 @@ def test_tag_wildcard_combined_with_exact_match(): ids=[ "none", "empty_list", - "empty_tuple", - "empty_set", "empty_string", "list_with_empty_string", "empty_string_and_tag", @@ -1201,17 +1197,5 @@ def test_text_refuses_an_empty_string(operation): def test_text_still_refuses_a_collection(): - with pytest.raises(TypeError): + with pytest.raises(TypeError, match="must be of type"): Text("t") == [] - - -def test_an_empty_tag_list_narrows_a_permission_filter(): - tenant = Tag("tenant") == "acme" - groups: list[str] = [] - permission = tenant & (Tag("groups") == groups) - assert "(@groups:{redisvl_no_match} -@groups:{redisvl_no_match})" in str(permission) - assert is_match_all_filter(permission) is False - # The field object itself renders the same once built. - field = Tag("groups") - field == groups - assert str(field) == "(@groups:{redisvl_no_match} -@groups:{redisvl_no_match})"