Skip to content

Commit 7d16683

Browse files
fix(python): preserve Oracle filter semantics and test typing
1 parent 7bd97f8 commit 7d16683

6 files changed

Lines changed: 124 additions & 16 deletions

File tree

‎python/packages/oracle/README.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,11 @@ creates and deletes a unique test table.
118118
- Portable filters support scalar equality (including `NULL` and boolean
119119
distinctions), `in`/`not_in`, numeric ranges, `is_null`, `is_not_null`,
120120
`exists`, literal text `contains_text`/`starts_with`/`ends_with`, and
121-
AND/OR/NOT. Collection membership and nested filters are rejected.
122-
Ordered filters on integer fields reject non-integral float operands.
121+
AND/OR/NOT. Finite `Decimal` values are supported for exact numeric equality
122+
and membership; malformed UUID filter values compare as unequal.
123+
Collection membership and nested filters are rejected.
124+
Ordered filters on integer fields reject non-integral float operands;
125+
ordered `Decimal` operands are not supported.
123126
String comparison follows the configured Oracle collation. Input values
124127
are bound; identifiers are checked and quoted as individual names.
125128

‎python/packages/oracle/agent_framework_oracle/_vector_store.py‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -345,30 +345,40 @@ def _equality(self, field: VectorStoreField, value: Any) -> str:
345345
if value is None:
346346
return f"{column} IS NULL"
347347
kind = field.type_
348-
if kind in ("int", "float") and type(value) in (int, float):
348+
if kind in ("int", "float") and (type(value) in (int, float) or isinstance(value, Decimal)):
349349
if type(value) is float and not math.isfinite(value):
350350
raise ValueError("Numeric filter values must be finite.")
351+
if isinstance(value, Decimal) and not value.is_finite():
352+
raise ValueError("Numeric filter values must be finite.")
351353
if kind == "int":
352-
if type(value) is float:
353-
if not value.is_integer() or not -(2**63) <= value < 2**63:
354-
return "1=0"
355-
value = int(value)
356-
elif not -(2**63) <= value < 2**63:
354+
if not -(2**63) <= value < 2**63 or value != int(value):
357355
return "1=0"
358-
elif type(value) is int:
356+
adapted = int(value)
357+
else:
359358
try:
360-
numerator, denominator = float(value).as_integer_ratio()
361-
if numerator != value * denominator:
362-
return "1=0"
359+
adapted = float(value)
363360
except OverflowError:
364361
return "1=0"
365-
adapted = value if kind == "int" else float(value)
362+
if not math.isfinite(adapted):
363+
return "1=0"
364+
if isinstance(value, Decimal) and Decimal.from_float(adapted) != value:
365+
return "1=0"
366+
if type(value) is int:
367+
numerator, denominator = adapted.as_integer_ratio()
368+
if numerator != value * denominator:
369+
return "1=0"
370+
elif kind == "UUID":
371+
if not isinstance(value, UUID | str):
372+
return "1=0"
373+
try:
374+
adapted = _validate_scalar(field, value)
375+
except ValueError:
376+
return "1=0"
366377
elif (
367378
(kind == "bool" and type(value) is not bool)
368379
or (kind != "bool" and isinstance(value, bool))
369-
or (kind == "UUID" and not isinstance(value, UUID | str))
370380
or (kind == "str" and not isinstance(value, str))
371-
or (kind in ("int", "float") and type(value) not in (int, float))
381+
or (kind in ("int", "float") and type(value) not in (int, float, Decimal))
372382
):
373383
return "1=0"
374384
else:

‎python/packages/oracle/tests/oracle/conftest.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def mock_database(collection):
101101
cursor = FakeCursor()
102102
connection = MagicMock()
103103
connection.cursor.return_value = cursor
104-
writes = []
104+
writes: list[bool] = []
105105

106106
@asynccontextmanager
107107
async def acquire(*, write=False):

‎python/packages/oracle/tests/oracle/test_collection.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,15 @@ async def test_retrieval_projects_vectors_only_when_requested(collection, mock_d
265265
assert '"dense vector"' in cursor.execute.call_args.args[0]
266266

267267

268+
async def test_get_applies_decimal_equality_after_core_filter_validation(collection, mock_database):
269+
_, cursor, _, _ = mock_database
270+
cursor.fetchall.return_value = [("one", "text", 2, 1)]
271+
assert (await collection.get(filter=Filter("number", "eq", Decimal("2"))))[0]["number"] == 2
272+
statement, binds = cursor.execute.call_args.args
273+
assert '"number" = :f0' in statement
274+
assert binds["f0"] == 2
275+
276+
268277
async def test_key_lookup_preserves_order_duplicates_and_chunks(collection, mock_database):
269278
_, cursor, _, _ = mock_database
270279
cursor.fetchall.side_effect = [
@@ -329,6 +338,19 @@ async def test_search_filter_threshold_and_paging_execute_in_database(collection
329338
cursor.setinputsizes.assert_called_once_with(query_vector=oracledb.DB_TYPE_VECTOR)
330339

331340

341+
async def test_search_applies_invalid_uuid_as_non_equal_after_core_filter_validation(definition_factory, mock_database):
342+
_, cursor, _, acquire = mock_database
343+
collection = OracleCollection(
344+
dict, definition=definition_factory(key_type="UUID"), dsn="unused", user="user", password="pass"
345+
)
346+
with patch.object(collection._client, "connection", side_effect=acquire.side_effect):
347+
results = await collection.search(vector=[1, 0, 0], filter=Filter("id", "in", ["not-a-uuid"]))
348+
assert [item async for item in results] == []
349+
statement, binds = cursor.execute.call_args.args
350+
assert '"doc""id" IS NOT NULL AND (1=0)' in statement
351+
assert set(binds) == {"query_vector", "top", "skip"}
352+
353+
332354
@pytest.mark.parametrize(
333355
"metric,cutoff,score_expression",
334356
[

‎python/packages/oracle/tests/oracle/test_filters.py‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
from __future__ import annotations
44

5+
from decimal import Decimal
6+
from uuid import UUID
7+
58
import pytest
69
from agent_framework import Filter, FilterGroup
710

@@ -55,6 +58,66 @@ def test_numeric_equality_does_not_coerce_invalid_values(collection, value):
5558
assert sql == "(NOT (1=0))" and binds == {}
5659

5760

61+
@pytest.mark.parametrize(
62+
("field", "value", "expected_bind"),
63+
[
64+
("number", Decimal("2"), 2),
65+
("number", Decimal("2.0"), 2),
66+
("number", Decimal("9223372036854775807"), 2**63 - 1),
67+
("number", Decimal("2.5"), None),
68+
("number", Decimal("9223372036854775808"), None),
69+
("text", Decimal("0.5"), 0.5),
70+
("text", Decimal("0.1"), None),
71+
("text", Decimal("1e1000"), None),
72+
],
73+
)
74+
def test_decimal_equality_uses_exact_numeric_comparison(definition_factory, field, value, expected_bind):
75+
compiler = _FilterCompiler(definition_factory(data_type="float"))
76+
for operator in ("eq", "ne"):
77+
sql, binds = compiler.compile(Filter(field, operator, value))
78+
if expected_bind is None:
79+
assert sql == ("1=0" if operator == "eq" else "(NOT (1=0))")
80+
assert binds == {}
81+
else:
82+
assert f'"{field if field == "number" else "body text"}" = :f0' in sql
83+
assert binds == {"f0": expected_bind}
84+
85+
86+
def test_decimal_membership_and_nonfinite_values(collection):
87+
sql, binds = collection._prepare_filter(Filter("number", "in", [Decimal("2"), Decimal("2.5")]))
88+
assert '"number" = :f0' in sql
89+
assert binds == {"f0": 2}
90+
sql, binds = collection._prepare_filter(Filter("number", "not_in", [Decimal("2.5")]))
91+
assert sql == '("number" IS NOT NULL AND (NOT ((1=0))))'
92+
assert binds == {}
93+
with pytest.raises(ValueError, match="finite"):
94+
collection._prepare_filter(Filter("number", "eq", Decimal("NaN")))
95+
96+
97+
@pytest.mark.parametrize(
98+
("operator", "value", "expected_sql"),
99+
[
100+
("eq", "not-a-uuid", "1=0"),
101+
("ne", "not-a-uuid", "(NOT (1=0))"),
102+
("in", ["not-a-uuid"], '("doc""id" IS NOT NULL AND (1=0))'),
103+
("not_in", ["not-a-uuid"], '("doc""id" IS NOT NULL AND (NOT ((1=0))))'),
104+
],
105+
)
106+
def test_malformed_uuid_filter_is_non_equal(definition_factory, operator, value, expected_sql):
107+
compiler = _FilterCompiler(definition_factory(key_type="UUID"))
108+
sql, binds = compiler.compile(Filter("id", operator, value))
109+
assert sql == expected_sql
110+
assert binds == {}
111+
112+
113+
def test_valid_uuid_filter_values_remain_bound(definition_factory):
114+
compiler = _FilterCompiler(definition_factory(key_type="UUID"))
115+
valid = UUID(int=2)
116+
sql, binds = compiler.compile(Filter("id", "in", ["malformed", valid]))
117+
assert '"doc""id" = :f0' in sql
118+
assert binds == {"f0": str(valid)}
119+
120+
58121
def test_boolean_equality_does_not_coerce_numbers(collection):
59122
sql, binds = collection._prepare_filter(Filter("flag", "eq", True))
60123
assert '"flag" = :f0' in sql and binds == {"f0": 1}

‎python/packages/oracle/tests/oracle/test_settings.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,16 @@ async def test_owned_pool_is_lazy_and_closed_once():
153153
await store._client._get_client()
154154

155155

156+
async def test_owned_pool_uses_driver_factory_without_connecting():
157+
store = OracleStore(dsn="localhost:1521/unused", user="unused", password="unused")
158+
try:
159+
pool = await store._client._get_client()
160+
assert isinstance(pool, oracledb.AsyncConnectionPool)
161+
assert await store._client._get_client() is pool
162+
finally:
163+
await store.close()
164+
165+
156166
async def test_pooled_writes_commit_or_rollback_but_borrowed_connection_does_not():
157167
connection = MagicMock(spec=oracledb.AsyncConnection)
158168
connection.commit = AsyncMock()

0 commit comments

Comments
 (0)