diff --git a/docs/concepts/mcp.md b/docs/concepts/mcp.md index 2dafb4b6..b5199adc 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 would drop the tenant clause from the query entirely. | +| `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/concepts/search-and-indexing.md b/docs/concepts/search-and-indexing.md index 613d9a5f..045fc4cc 100644 --- a/docs/concepts/search-and-indexing.md +++ b/docs/concepts/search-and-indexing.md @@ -135,7 +135,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/docs/user_guide/02_complex_filtering.ipynb b/docs/user_guide/02_complex_filtering.ipynb index 1805b7d4..bfa8340e 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 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", - "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 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." ] }, { @@ -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 3a5a8bf0..044826dd 100644 --- a/redisvl/extensions/router/semantic.py +++ b/redisvl/extensions/router/semantic.py @@ -1093,11 +1093,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. + # `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 6411bd56..e2d345fc 100644 --- a/redisvl/query/filter.py +++ b/redisvl/query/filter.py @@ -116,7 +116,29 @@ 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 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. ``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 + + 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,18 +163,20 @@ 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 ): 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] @@ -222,15 +246,27 @@ def __mod__(self, other: list[str] | str) -> "FilterExpression": 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, @@ -724,6 +760,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] = { @@ -744,6 +782,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 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" + ) + 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 +870,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 +920,12 @@ class FilterExpression: filter_expression=f, ) + Note: + 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. + Note: Filter expressions are typically not called directly. Instead they are built by combining filter statements using the & and | operators. @@ -948,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 8516d226..f2b5e66f 100644 --- a/tests/integration/test_query.py +++ b/tests/integration/test_query.py @@ -334,6 +334,55 @@ 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((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(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 +465,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 +521,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 +727,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 +1224,25 @@ 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") > 100)) == { + f"{prefix}:empty_strings" + } + # 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. @@ -1363,14 +1435,6 @@ 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( - filter_expression=(Text("title") != "") & (Tag("category") != ""), - return_fields=["id", "title", "category"], - ) - results = missing_index.query(display_ready_documents) - assert len(results) >= 2 # Should find complete and zero_price documents - def test_data_quality_completeness_analysis(missing_fields_index): """ @@ -1406,14 +1470,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=Text("title") != "", - 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 8377e9f4..db6fc5d3 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,36 @@ def test_tag_wildcard_combined_with_exact_match(): "operation, value, expected", [ ("__eq__", None, "*"), - ("__eq__", [], "*"), - ("__eq__", "", "*"), - ("__eq__", [None], "*"), + ("__eq__", [], 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_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 +318,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 +365,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 +627,36 @@ def test_filters_combination(): combined = tf1 | tf2 assert str(combined) == "(@tag_field:{tag1|tag2} | @tag_field:{tag3})" + # 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) == "*" - assert str(tf1 & tf2) == str(tf2) - assert str(tf1 | tf2) == str(tf2) - - # test combining filters with None values and empty strings + assert str(tf1) == NO_MATCH + 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 NO_MATCH in str((tf2 & other) & tf1) + assert NO_MATCH in str((tf2 | other) & tf1) + + # `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) + + # `""` 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") == "" + tf2 = Tag("tag_field") == None assert str(tf1 & tf2) == "*" tf1 = Tag("tag_field") == None @@ -637,7 +671,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 +1135,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 +1177,25 @@ 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)("") + + +def test_text_still_refuses_a_collection(): + with pytest.raises(TypeError, match="must be of type"): + Text("t") == [] diff --git a/tests/unit/test_mcp/test_auth_claim_injection.py b/tests/unit/test_mcp/test_auth_claim_injection.py index 1523427c..9dd25ea9 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 4eb4938c..64361771 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"):