massengine 1.1.4__tar.gz → 1.2.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {massengine-1.1.4 → massengine-1.2.1}/PKG-INFO +19 -8
- {massengine-1.1.4 → massengine-1.2.1}/README.md +16 -5
- {massengine-1.1.4 → massengine-1.2.1}/massengine/client.py +214 -27
- {massengine-1.1.4 → massengine-1.2.1}/pyproject.toml +3 -3
- {massengine-1.1.4 → massengine-1.2.1}/tests/test_client.py +215 -13
- {massengine-1.1.4 → massengine-1.2.1}/.gitignore +0 -0
- {massengine-1.1.4 → massengine-1.2.1}/LICENSE +0 -0
- {massengine-1.1.4 → massengine-1.2.1}/massengine/__init__.py +0 -0
- {massengine-1.1.4 → massengine-1.2.1}/massengine/py.typed +0 -0
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: massengine
|
|
3
|
-
Version: 1.1
|
|
4
|
-
Summary: Official Python SDK for the MassEngine filtered vector search database.
|
|
3
|
+
Version: 1.2.1
|
|
4
|
+
Summary: Official Python SDK for the MassEngine filtered vector and hybrid search database.
|
|
5
5
|
Project-URL: Homepage, https://massengine.com
|
|
6
6
|
Project-URL: Documentation, https://massengine.com/docs
|
|
7
7
|
Project-URL: Repository, https://github.com/massengine-dev/massengine-python
|
|
8
8
|
Author-email: MassEngine <dev@massengine.com>
|
|
9
9
|
License-Expression: Apache-2.0
|
|
10
10
|
License-File: LICENSE
|
|
11
|
-
Keywords: embeddings,massengine,rag,vector-database,vector-search
|
|
11
|
+
Keywords: bm25,embeddings,hybrid-search,massengine,rag,vector-database,vector-search
|
|
12
12
|
Classifier: Development Status :: 5 - Production/Stable
|
|
13
13
|
Classifier: Intended Audience :: Developers
|
|
14
14
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -24,7 +24,7 @@ Description-Content-Type: text/markdown
|
|
|
24
24
|
|
|
25
25
|
# MassEngine Python SDK (`massengine`)
|
|
26
26
|
|
|
27
|
-
Official zero-dependency Python client for [MassEngine](https://massengine.com) — the sub-5ms filtered vector search database.
|
|
27
|
+
Official zero-dependency Python client for [MassEngine](https://massengine.com) — the sub-5ms filtered vector and hybrid search database.
|
|
28
28
|
|
|
29
29
|
## Installation
|
|
30
30
|
|
|
@@ -56,7 +56,7 @@ client.ingest(
|
|
|
56
56
|
],
|
|
57
57
|
)
|
|
58
58
|
|
|
59
|
-
# 2. Dense vector search with rich metadata filter operators
|
|
59
|
+
# 2. Dense vector search with rich metadata filter operators ($eq/$ne/$in/$nin/$gt/$gte/$lt/$lte/$contains + $and/$or/$nor)
|
|
60
60
|
res = client.search(
|
|
61
61
|
"acme-prod",
|
|
62
62
|
vector=[0.12, -0.44, 0.88, 0.05],
|
|
@@ -66,18 +66,29 @@ res = client.search(
|
|
|
66
66
|
"department": {"$in": ["security", "legal"]},
|
|
67
67
|
"clearance": {"$gte": 2},
|
|
68
68
|
"tags": {"$contains": "soc2"},
|
|
69
|
+
"$nor": [{"status": "archived"}],
|
|
69
70
|
},
|
|
70
71
|
)
|
|
71
72
|
print(res["hits"])
|
|
72
73
|
|
|
73
|
-
# 3.
|
|
74
|
+
# 3. Hybrid search (dense + BM25 lexical + sparse vectors with weighted RRF)
|
|
75
|
+
hybrid = client.search(
|
|
76
|
+
"acme-prod",
|
|
77
|
+
vector=[0.12, -0.44, 0.88, 0.05],
|
|
78
|
+
query_text="soc2 security policy",
|
|
79
|
+
hybrid_alpha=0.6,
|
|
80
|
+
k=10,
|
|
81
|
+
)
|
|
82
|
+
print(hybrid["hits"])
|
|
83
|
+
|
|
84
|
+
# 4. In-place metadata patching without re-embedding
|
|
74
85
|
client.patch_doc(
|
|
75
86
|
"acme-prod",
|
|
76
87
|
"docs/2026/policy-1",
|
|
77
88
|
metadata={"clearance": 4, "reviewed": True},
|
|
78
89
|
)
|
|
79
90
|
|
|
80
|
-
#
|
|
91
|
+
# 5. Inspect tenant quota & billable usage
|
|
81
92
|
usage = client.get_tenant_usage("acme-prod")
|
|
82
93
|
print(usage)
|
|
83
94
|
```
|
|
@@ -87,7 +98,7 @@ print(usage)
|
|
|
87
98
|
Create isolated databases within a tenant and scope operations using `database=` (pass `tenant=""` when authenticating with a tenant-scoped `mk_...` key):
|
|
88
99
|
|
|
89
100
|
```python
|
|
90
|
-
client.create_database("", "analytics", data_type="int8")
|
|
101
|
+
client.create_database("", "analytics", data_type="int8", ttl_days=30, time_bucket_days=1, append_only=True)
|
|
91
102
|
|
|
92
103
|
client.ingest(
|
|
93
104
|
"",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# MassEngine Python SDK (`massengine`)
|
|
2
2
|
|
|
3
|
-
Official zero-dependency Python client for [MassEngine](https://massengine.com) — the sub-5ms filtered vector search database.
|
|
3
|
+
Official zero-dependency Python client for [MassEngine](https://massengine.com) — the sub-5ms filtered vector and hybrid search database.
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
@@ -32,7 +32,7 @@ client.ingest(
|
|
|
32
32
|
],
|
|
33
33
|
)
|
|
34
34
|
|
|
35
|
-
# 2. Dense vector search with rich metadata filter operators
|
|
35
|
+
# 2. Dense vector search with rich metadata filter operators ($eq/$ne/$in/$nin/$gt/$gte/$lt/$lte/$contains + $and/$or/$nor)
|
|
36
36
|
res = client.search(
|
|
37
37
|
"acme-prod",
|
|
38
38
|
vector=[0.12, -0.44, 0.88, 0.05],
|
|
@@ -42,18 +42,29 @@ res = client.search(
|
|
|
42
42
|
"department": {"$in": ["security", "legal"]},
|
|
43
43
|
"clearance": {"$gte": 2},
|
|
44
44
|
"tags": {"$contains": "soc2"},
|
|
45
|
+
"$nor": [{"status": "archived"}],
|
|
45
46
|
},
|
|
46
47
|
)
|
|
47
48
|
print(res["hits"])
|
|
48
49
|
|
|
49
|
-
# 3.
|
|
50
|
+
# 3. Hybrid search (dense + BM25 lexical + sparse vectors with weighted RRF)
|
|
51
|
+
hybrid = client.search(
|
|
52
|
+
"acme-prod",
|
|
53
|
+
vector=[0.12, -0.44, 0.88, 0.05],
|
|
54
|
+
query_text="soc2 security policy",
|
|
55
|
+
hybrid_alpha=0.6,
|
|
56
|
+
k=10,
|
|
57
|
+
)
|
|
58
|
+
print(hybrid["hits"])
|
|
59
|
+
|
|
60
|
+
# 4. In-place metadata patching without re-embedding
|
|
50
61
|
client.patch_doc(
|
|
51
62
|
"acme-prod",
|
|
52
63
|
"docs/2026/policy-1",
|
|
53
64
|
metadata={"clearance": 4, "reviewed": True},
|
|
54
65
|
)
|
|
55
66
|
|
|
56
|
-
#
|
|
67
|
+
# 5. Inspect tenant quota & billable usage
|
|
57
68
|
usage = client.get_tenant_usage("acme-prod")
|
|
58
69
|
print(usage)
|
|
59
70
|
```
|
|
@@ -63,7 +74,7 @@ print(usage)
|
|
|
63
74
|
Create isolated databases within a tenant and scope operations using `database=` (pass `tenant=""` when authenticating with a tenant-scoped `mk_...` key):
|
|
64
75
|
|
|
65
76
|
```python
|
|
66
|
-
client.create_database("", "analytics", data_type="int8")
|
|
77
|
+
client.create_database("", "analytics", data_type="int8", ttl_days=30, time_bucket_days=1, append_only=True)
|
|
67
78
|
|
|
68
79
|
client.ingest(
|
|
69
80
|
"",
|
|
@@ -4,17 +4,19 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
from dataclasses import dataclass
|
|
6
6
|
import json
|
|
7
|
+
import math
|
|
7
8
|
import ssl
|
|
8
|
-
from typing import Any, Dict, Iterable, List, Optional, Sequence, Union
|
|
9
|
+
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union
|
|
9
10
|
import urllib.error
|
|
10
11
|
import urllib.parse
|
|
11
12
|
import urllib.request
|
|
12
13
|
|
|
13
|
-
SDK_VERSION = "1.1
|
|
14
|
+
SDK_VERSION = "1.2.1"
|
|
14
15
|
USER_AGENT = f"massengine-python/{SDK_VERSION}"
|
|
15
16
|
DEFAULT_MAX_RESPONSE_BYTES = 64 * 1024 * 1024 # 64 MiB
|
|
16
17
|
MAX_ERROR_RESPONSE_BYTES = 65536 # 64 KiB
|
|
17
18
|
_MAX_LINE_READ_CHUNK = 4 * 1024 * 1024
|
|
19
|
+
_MAX_SPARSE_TERMS = 65536
|
|
18
20
|
|
|
19
21
|
|
|
20
22
|
class MassEngineError(Exception):
|
|
@@ -64,18 +66,78 @@ def _escape_doc_id(doc_id: str) -> str:
|
|
|
64
66
|
return "/".join(_validate_segment(part) for part in parts)
|
|
65
67
|
|
|
66
68
|
|
|
67
|
-
def
|
|
69
|
+
def _validate_finite_float_seq(vector: Any, label: str = "vector") -> List[float]:
|
|
68
70
|
if vector is None or isinstance(vector, (str, bytes, bytearray)):
|
|
69
|
-
raise ValueError("
|
|
71
|
+
raise ValueError(f"{label} must be a sequence of finite numbers")
|
|
70
72
|
try:
|
|
71
|
-
|
|
73
|
+
raw = list(vector)
|
|
72
74
|
except TypeError:
|
|
73
|
-
raise ValueError("
|
|
75
|
+
raise ValueError(f"{label} must be a sequence of finite numbers") from None
|
|
76
|
+
out: List[float] = []
|
|
77
|
+
for v in raw:
|
|
78
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(float(v)):
|
|
79
|
+
raise ValueError(f"{label} must contain only finite numbers")
|
|
80
|
+
out.append(float(v))
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _validate_vector(vector: Any) -> List[float]:
|
|
85
|
+
vals = _validate_finite_float_seq(vector, "vector")
|
|
74
86
|
if len(vals) == 0:
|
|
75
87
|
raise ValueError("vector must be a non-empty sequence of numbers")
|
|
76
88
|
return vals
|
|
77
89
|
|
|
78
90
|
|
|
91
|
+
def _validate_optional_vector(vector: Any) -> List[float]:
|
|
92
|
+
if vector is None:
|
|
93
|
+
return []
|
|
94
|
+
return _validate_finite_float_seq(vector, "vector")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _validate_sparse(
|
|
98
|
+
sparse_indices: Any,
|
|
99
|
+
sparse_values: Any,
|
|
100
|
+
) -> Optional[Tuple[List[int], List[float]]]:
|
|
101
|
+
if sparse_indices is None and sparse_values is None:
|
|
102
|
+
return None
|
|
103
|
+
if sparse_indices is None or sparse_values is None:
|
|
104
|
+
raise ValueError("sparse_indices and sparse_values must both be provided with equal length")
|
|
105
|
+
if isinstance(sparse_indices, (str, bytes, bytearray)):
|
|
106
|
+
raise ValueError("sparse_indices must be a sequence of uint32 integers")
|
|
107
|
+
try:
|
|
108
|
+
raw_idx = list(sparse_indices)
|
|
109
|
+
except TypeError:
|
|
110
|
+
raise ValueError("sparse_indices must be a sequence of uint32 integers") from None
|
|
111
|
+
vals = _validate_finite_float_seq(sparse_values, "sparse_values")
|
|
112
|
+
if len(raw_idx) != len(vals):
|
|
113
|
+
raise ValueError("sparse_indices and sparse_values must have equal length")
|
|
114
|
+
if len(raw_idx) > _MAX_SPARSE_TERMS:
|
|
115
|
+
raise ValueError(f"sparse vector exceeds maximum of {_MAX_SPARSE_TERMS} terms")
|
|
116
|
+
if len(raw_idx) == 0:
|
|
117
|
+
return None
|
|
118
|
+
idx_out: List[int] = []
|
|
119
|
+
for idx in raw_idx:
|
|
120
|
+
if isinstance(idx, bool) or not isinstance(idx, int) or idx < 0 or idx > 0xFFFFFFFF:
|
|
121
|
+
raise ValueError("sparse_indices must contain integers in [0, 4294967295]")
|
|
122
|
+
idx_out.append(idx)
|
|
123
|
+
return idx_out, vals
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _validate_hybrid_alpha(alpha: Any) -> float:
|
|
127
|
+
if isinstance(alpha, bool) or not isinstance(alpha, (int, float)) or not math.isfinite(float(alpha)):
|
|
128
|
+
raise ValueError("hybrid_alpha must be a finite number between 0.0 and 1.0")
|
|
129
|
+
val = float(alpha)
|
|
130
|
+
if val < 0.0 or val > 1.0:
|
|
131
|
+
raise ValueError("hybrid_alpha must be between 0.0 and 1.0")
|
|
132
|
+
return val
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _validate_min_score(val: Any) -> float:
|
|
136
|
+
if isinstance(val, bool) or not isinstance(val, (int, float)) or not math.isfinite(float(val)):
|
|
137
|
+
raise ValueError("min_score must be a finite number")
|
|
138
|
+
return float(val)
|
|
139
|
+
|
|
140
|
+
|
|
79
141
|
def _extract_error_message(raw_text: str) -> str:
|
|
80
142
|
msg = raw_text.strip()
|
|
81
143
|
try:
|
|
@@ -87,23 +149,50 @@ def _extract_error_message(raw_text: str) -> str:
|
|
|
87
149
|
return msg
|
|
88
150
|
|
|
89
151
|
|
|
152
|
+
def _validate_doc_id_int(val: Any) -> int:
|
|
153
|
+
if isinstance(val, bool) or not isinstance(val, int) or val < 0 or val > 0xFFFFFFFFFFFFFFFF:
|
|
154
|
+
raise ValueError("doc_id must be a uint64 integer")
|
|
155
|
+
return val
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _validate_effort(val: Any) -> int:
|
|
159
|
+
if isinstance(val, bool) or not isinstance(val, int) or val < 1 or val > 100:
|
|
160
|
+
raise ValueError("effort must be an integer between 1 and 100")
|
|
161
|
+
return val
|
|
162
|
+
|
|
163
|
+
|
|
90
164
|
@dataclass
|
|
91
165
|
class Doc:
|
|
92
|
-
"""Represents a
|
|
166
|
+
"""Represents a document for ingestion or export."""
|
|
93
167
|
|
|
94
|
-
id: str
|
|
95
|
-
vector: Sequence[float]
|
|
168
|
+
id: str = ""
|
|
169
|
+
vector: Sequence[float] = ()
|
|
170
|
+
doc_id: Optional[int] = None
|
|
96
171
|
date: Optional[int] = None
|
|
97
172
|
category: Optional[int] = None
|
|
173
|
+
no_ttl: bool = False
|
|
98
174
|
metadata: Optional[Dict[str, Any]] = None
|
|
99
175
|
database: Optional[str] = None
|
|
176
|
+
sparse_indices: Optional[Sequence[int]] = None
|
|
177
|
+
sparse_values: Optional[Sequence[float]] = None
|
|
100
178
|
|
|
101
179
|
def to_dict(self) -> Dict[str, Any]:
|
|
102
|
-
|
|
180
|
+
if self.id == "" and self.doc_id is None:
|
|
181
|
+
raise ValueError("document requires a non-empty id or integer doc_id")
|
|
182
|
+
if self.id != "":
|
|
183
|
+
_escape_doc_id(self.id)
|
|
184
|
+
vec = _validate_vector(self.vector)
|
|
185
|
+
sparse = _validate_sparse(self.sparse_indices, self.sparse_values)
|
|
103
186
|
out: Dict[str, Any] = {
|
|
104
|
-
"
|
|
105
|
-
"vector": list(self.vector),
|
|
187
|
+
"vector": vec,
|
|
106
188
|
}
|
|
189
|
+
if self.id != "":
|
|
190
|
+
out["id"] = self.id
|
|
191
|
+
if self.doc_id is not None:
|
|
192
|
+
out["doc_id"] = _validate_doc_id_int(self.doc_id)
|
|
193
|
+
if sparse is not None:
|
|
194
|
+
out["sparse_indices"] = sparse[0]
|
|
195
|
+
out["sparse_values"] = sparse[1]
|
|
107
196
|
if self.database:
|
|
108
197
|
_validate_identifier(self.database, "database")
|
|
109
198
|
out["database"] = self.database
|
|
@@ -111,6 +200,8 @@ class Doc:
|
|
|
111
200
|
out["date"] = int(self.date)
|
|
112
201
|
if self.category is not None:
|
|
113
202
|
out["category"] = int(self.category)
|
|
203
|
+
if self.no_ttl:
|
|
204
|
+
out["no_ttl"] = True
|
|
114
205
|
if self.metadata is not None:
|
|
115
206
|
out["metadata"] = self.metadata
|
|
116
207
|
return out
|
|
@@ -118,28 +209,53 @@ class Doc:
|
|
|
118
209
|
|
|
119
210
|
@dataclass
|
|
120
211
|
class SearchRequest:
|
|
121
|
-
"""Specifies a
|
|
212
|
+
"""Specifies a dense vector, BM25 lexical, sparse vector, or hybrid search query."""
|
|
122
213
|
|
|
123
214
|
tenant: str = ""
|
|
124
215
|
k: int = 10
|
|
125
|
-
vector: Sequence[float] =
|
|
216
|
+
vector: Optional[Sequence[float]] = None
|
|
217
|
+
query_text: Optional[str] = None
|
|
218
|
+
hybrid_alpha: Optional[float] = None
|
|
219
|
+
sparse_indices: Optional[Sequence[int]] = None
|
|
220
|
+
sparse_values: Optional[Sequence[float]] = None
|
|
126
221
|
database: str = ""
|
|
127
222
|
metadata_filter: Optional[Dict[str, Any]] = None
|
|
128
223
|
offset: int = 0
|
|
129
224
|
min_score: Optional[float] = None
|
|
225
|
+
effort: Optional[int] = None
|
|
130
226
|
rerank_pool: Optional[int] = None
|
|
131
227
|
nprobe: Optional[int] = None
|
|
228
|
+
skip_meta: bool = False
|
|
132
229
|
min_date: Optional[int] = None
|
|
133
230
|
max_date: Optional[int] = None
|
|
134
231
|
category: Optional[int] = None
|
|
135
232
|
categories: Optional[Sequence[int]] = None
|
|
233
|
+
min_doc_id: Optional[int] = None
|
|
234
|
+
max_doc_id: Optional[int] = None
|
|
136
235
|
|
|
137
236
|
def to_dict(self) -> Dict[str, Any]:
|
|
138
|
-
vec =
|
|
237
|
+
vec = _validate_optional_vector(self.vector)
|
|
238
|
+
sparse = _validate_sparse(self.sparse_indices, self.sparse_values)
|
|
239
|
+
q_text = ""
|
|
240
|
+
if self.query_text is not None:
|
|
241
|
+
if not isinstance(self.query_text, str):
|
|
242
|
+
raise ValueError("query_text must be a string")
|
|
243
|
+
q_text = self.query_text.strip()
|
|
244
|
+
if len(vec) == 0 and q_text == "" and sparse is None:
|
|
245
|
+
raise ValueError("search requires a non-empty vector, query_text, or sparse_indices")
|
|
246
|
+
|
|
139
247
|
out: Dict[str, Any] = {
|
|
140
|
-
"vector": vec,
|
|
141
248
|
"k": int(self.k),
|
|
142
249
|
}
|
|
250
|
+
if len(vec) > 0:
|
|
251
|
+
out["vector"] = vec
|
|
252
|
+
if q_text != "":
|
|
253
|
+
out["query_text"] = self.query_text
|
|
254
|
+
if self.hybrid_alpha is not None:
|
|
255
|
+
out["hybrid_alpha"] = _validate_hybrid_alpha(self.hybrid_alpha)
|
|
256
|
+
if sparse is not None:
|
|
257
|
+
out["sparse_indices"] = sparse[0]
|
|
258
|
+
out["sparse_values"] = sparse[1]
|
|
143
259
|
if self.tenant != "":
|
|
144
260
|
_validate_identifier(self.tenant, "tenant")
|
|
145
261
|
out["tenant"] = self.tenant
|
|
@@ -151,11 +267,15 @@ class SearchRequest:
|
|
|
151
267
|
if self.offset:
|
|
152
268
|
out["offset"] = int(self.offset)
|
|
153
269
|
if self.min_score is not None:
|
|
154
|
-
out["min_score"] =
|
|
270
|
+
out["min_score"] = _validate_min_score(self.min_score)
|
|
271
|
+
if self.effort is not None:
|
|
272
|
+
out["effort"] = _validate_effort(self.effort)
|
|
155
273
|
if self.rerank_pool:
|
|
156
274
|
out["rerank_pool"] = int(self.rerank_pool)
|
|
157
275
|
if self.nprobe:
|
|
158
276
|
out["nprobe"] = int(self.nprobe)
|
|
277
|
+
if self.skip_meta:
|
|
278
|
+
out["skip_meta"] = True
|
|
159
279
|
if self.min_date is not None:
|
|
160
280
|
out["min_date"] = int(self.min_date)
|
|
161
281
|
if self.max_date is not None:
|
|
@@ -164,6 +284,10 @@ class SearchRequest:
|
|
|
164
284
|
out["category"] = int(self.category)
|
|
165
285
|
if self.categories:
|
|
166
286
|
out["categories"] = [int(c) for c in self.categories]
|
|
287
|
+
if self.min_doc_id is not None:
|
|
288
|
+
out["min_doc_id"] = int(self.min_doc_id)
|
|
289
|
+
if self.max_doc_id is not None:
|
|
290
|
+
out["max_doc_id"] = int(self.max_doc_id)
|
|
167
291
|
return out
|
|
168
292
|
|
|
169
293
|
|
|
@@ -194,14 +318,14 @@ class MassEngineClient:
|
|
|
194
318
|
|
|
195
319
|
def __init__(
|
|
196
320
|
self,
|
|
197
|
-
base_url: str = "http://localhost:
|
|
321
|
+
base_url: str = "http://localhost:8080",
|
|
198
322
|
api_key: Optional[str] = None,
|
|
199
323
|
timeout: float = 30.0,
|
|
200
324
|
max_response_bytes: int = DEFAULT_MAX_RESPONSE_BYTES,
|
|
201
325
|
) -> None:
|
|
202
326
|
self.base_url = self._validate_base_url(base_url)
|
|
203
327
|
self._api_key = self._validate_api_key(api_key)
|
|
204
|
-
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or timeout <= 0:
|
|
328
|
+
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not math.isfinite(float(timeout)) or timeout <= 0:
|
|
205
329
|
raise ValueError("timeout must be a positive number")
|
|
206
330
|
if isinstance(max_response_bytes, bool) or not isinstance(max_response_bytes, int) or max_response_bytes <= 0:
|
|
207
331
|
raise ValueError("max_response_bytes must be a positive integer")
|
|
@@ -287,7 +411,7 @@ class MassEngineClient:
|
|
|
287
411
|
data: Optional[bytes] = None
|
|
288
412
|
content_type: Optional[str] = None
|
|
289
413
|
if body is not None:
|
|
290
|
-
data = json.dumps(body).encode("utf-8")
|
|
414
|
+
data = json.dumps(body, allow_nan=False).encode("utf-8")
|
|
291
415
|
content_type = "application/json"
|
|
292
416
|
|
|
293
417
|
req = urllib.request.Request(
|
|
@@ -354,7 +478,18 @@ class MassEngineClient:
|
|
|
354
478
|
return d.to_dict()
|
|
355
479
|
if not isinstance(d, dict):
|
|
356
480
|
raise ValueError("document must be a Doc or dict")
|
|
357
|
-
|
|
481
|
+
raw_id = d.get("id")
|
|
482
|
+
raw_doc_id = d.get("doc_id")
|
|
483
|
+
if (raw_id is None or raw_id == "") and raw_doc_id is None:
|
|
484
|
+
raise ValueError("document requires a non-empty id or integer doc_id")
|
|
485
|
+
if raw_id is not None and raw_id != "":
|
|
486
|
+
cls._esc_doc_id(raw_id) # type: ignore[arg-type]
|
|
487
|
+
if raw_doc_id is not None:
|
|
488
|
+
_validate_doc_id_int(raw_doc_id)
|
|
489
|
+
if "vector" in d:
|
|
490
|
+
_validate_vector(d.get("vector"))
|
|
491
|
+
if "sparse_indices" in d or "sparse_values" in d:
|
|
492
|
+
_validate_sparse(d.get("sparse_indices"), d.get("sparse_values"))
|
|
358
493
|
if d.get("database"):
|
|
359
494
|
cls._esc_database(d["database"])
|
|
360
495
|
return d
|
|
@@ -380,34 +515,50 @@ class MassEngineClient:
|
|
|
380
515
|
self,
|
|
381
516
|
tenant: str = "",
|
|
382
517
|
*,
|
|
383
|
-
vector: Sequence[float],
|
|
518
|
+
vector: Optional[Sequence[float]] = None,
|
|
519
|
+
query_text: Optional[str] = None,
|
|
520
|
+
hybrid_alpha: Optional[float] = None,
|
|
521
|
+
sparse_indices: Optional[Sequence[int]] = None,
|
|
522
|
+
sparse_values: Optional[Sequence[float]] = None,
|
|
384
523
|
database: str = "",
|
|
385
524
|
k: int = 10,
|
|
386
525
|
metadata_filter: Optional[Dict[str, Any]] = None,
|
|
387
526
|
offset: int = 0,
|
|
388
527
|
min_score: Optional[float] = None,
|
|
528
|
+
effort: Optional[int] = None,
|
|
389
529
|
rerank_pool: Optional[int] = None,
|
|
390
530
|
nprobe: Optional[int] = None,
|
|
531
|
+
skip_meta: bool = False,
|
|
391
532
|
min_date: Optional[int] = None,
|
|
392
533
|
max_date: Optional[int] = None,
|
|
393
534
|
category: Optional[int] = None,
|
|
394
535
|
categories: Optional[Sequence[int]] = None,
|
|
536
|
+
min_doc_id: Optional[int] = None,
|
|
537
|
+
max_doc_id: Optional[int] = None,
|
|
395
538
|
) -> Dict[str, Any]:
|
|
396
|
-
"""Executes a dense vector
|
|
539
|
+
"""Executes a dense vector, BM25 lexical, sparse vector, or hybrid search query."""
|
|
397
540
|
sr = SearchRequest(
|
|
398
541
|
tenant=tenant,
|
|
399
542
|
k=k,
|
|
400
543
|
vector=vector,
|
|
544
|
+
query_text=query_text,
|
|
545
|
+
hybrid_alpha=hybrid_alpha,
|
|
546
|
+
sparse_indices=sparse_indices,
|
|
547
|
+
sparse_values=sparse_values,
|
|
401
548
|
database=database,
|
|
402
549
|
metadata_filter=metadata_filter,
|
|
403
550
|
offset=offset,
|
|
404
551
|
min_score=min_score,
|
|
552
|
+
effort=effort,
|
|
405
553
|
rerank_pool=rerank_pool,
|
|
406
554
|
nprobe=nprobe,
|
|
555
|
+
skip_meta=skip_meta,
|
|
407
556
|
min_date=min_date,
|
|
408
557
|
max_date=max_date,
|
|
409
558
|
category=category,
|
|
410
559
|
categories=categories,
|
|
560
|
+
min_doc_id=min_doc_id,
|
|
561
|
+
max_doc_id=max_doc_id,
|
|
411
562
|
)
|
|
412
563
|
return self._request_json("POST", "/v1/search", sr.to_dict())
|
|
413
564
|
|
|
@@ -418,7 +569,7 @@ class MassEngineClient:
|
|
|
418
569
|
tenant: str = "",
|
|
419
570
|
database: str = "",
|
|
420
571
|
) -> Dict[str, Any]:
|
|
421
|
-
"""Executes multiple dense
|
|
572
|
+
"""Executes multiple dense, lexical, sparse, or hybrid search queries in a single round-trip."""
|
|
422
573
|
if not queries:
|
|
423
574
|
raise ValueError("queries must be non-empty")
|
|
424
575
|
esc_tenant = self._validate_optional_tenant(tenant)
|
|
@@ -428,9 +579,30 @@ class MassEngineClient:
|
|
|
428
579
|
if isinstance(q, SearchRequest):
|
|
429
580
|
serialized.append(q.to_dict())
|
|
430
581
|
elif isinstance(q, dict):
|
|
431
|
-
vec = _validate_vector(q.get("vector"))
|
|
432
582
|
q_copy = dict(q)
|
|
433
|
-
q_copy
|
|
583
|
+
vec = _validate_optional_vector(q_copy.get("vector"))
|
|
584
|
+
sparse = _validate_sparse(q_copy.get("sparse_indices"), q_copy.get("sparse_values"))
|
|
585
|
+
q_text_raw = q_copy.get("query_text")
|
|
586
|
+
q_text = ""
|
|
587
|
+
if q_text_raw is not None:
|
|
588
|
+
if not isinstance(q_text_raw, str):
|
|
589
|
+
raise ValueError("query_text must be a string")
|
|
590
|
+
q_text = q_text_raw.strip()
|
|
591
|
+
if len(vec) == 0 and q_text == "" and sparse is None:
|
|
592
|
+
raise ValueError("search requires a non-empty vector, query_text, or sparse_indices")
|
|
593
|
+
if len(vec) > 0:
|
|
594
|
+
q_copy["vector"] = vec
|
|
595
|
+
else:
|
|
596
|
+
q_copy.pop("vector", None)
|
|
597
|
+
if sparse is not None:
|
|
598
|
+
q_copy["sparse_indices"] = sparse[0]
|
|
599
|
+
q_copy["sparse_values"] = sparse[1]
|
|
600
|
+
if q_copy.get("hybrid_alpha") is not None:
|
|
601
|
+
q_copy["hybrid_alpha"] = _validate_hybrid_alpha(q_copy["hybrid_alpha"])
|
|
602
|
+
if q_copy.get("min_score") is not None:
|
|
603
|
+
q_copy["min_score"] = _validate_min_score(q_copy["min_score"])
|
|
604
|
+
if q_copy.get("effort") is not None:
|
|
605
|
+
q_copy["effort"] = _validate_effort(q_copy["effort"])
|
|
434
606
|
if q_copy.get("tenant"):
|
|
435
607
|
self._esc_tenant(q_copy["tenant"])
|
|
436
608
|
if q_copy.get("database"):
|
|
@@ -511,12 +683,18 @@ class MassEngineClient:
|
|
|
511
683
|
docs: Iterable[Union[Doc, Dict[str, Any]]],
|
|
512
684
|
*,
|
|
513
685
|
database: str = "",
|
|
686
|
+
batch_size: int = 0,
|
|
514
687
|
) -> int:
|
|
515
688
|
"""Streams a collection of documents into `tenant` via NDJSON."""
|
|
516
689
|
esc_tenant = self._validate_optional_tenant(tenant)
|
|
690
|
+
if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size < 0 or batch_size > 4096:
|
|
691
|
+
raise ValueError("batch_size must be between 1 and 4096")
|
|
517
692
|
base_path = "/v1/import" if esc_tenant == "" else f"/v1/tenants/{esc_tenant}/import"
|
|
518
693
|
path = self._append_db_query(base_path, database)
|
|
519
|
-
|
|
694
|
+
if batch_size > 0:
|
|
695
|
+
sep = "&" if "?" in path else "?"
|
|
696
|
+
path = f"{path}{sep}batch_size={batch_size}"
|
|
697
|
+
lines = [json.dumps(self._serialize_doc(d), allow_nan=False) for d in docs]
|
|
520
698
|
payload = ("\n".join(lines) + "\n").encode("utf-8")
|
|
521
699
|
req = urllib.request.Request(
|
|
522
700
|
url=f"{self.base_url}{path}",
|
|
@@ -599,6 +777,9 @@ class MassEngineClient:
|
|
|
599
777
|
rf: int = 0,
|
|
600
778
|
data_type: str = "",
|
|
601
779
|
mode: str = "",
|
|
780
|
+
ttl_days: int = 0,
|
|
781
|
+
time_bucket_days: int = 0,
|
|
782
|
+
append_only: bool = False,
|
|
602
783
|
) -> Dict[str, Any]:
|
|
603
784
|
"""Creates or updates a named database under `tenant` (or the bound `mk_...` key's tenant)."""
|
|
604
785
|
esc_tenant = self._validate_optional_tenant(tenant)
|
|
@@ -613,6 +794,12 @@ class MassEngineClient:
|
|
|
613
794
|
body["data_type"] = data_type
|
|
614
795
|
if mode:
|
|
615
796
|
body["mode"] = mode
|
|
797
|
+
if ttl_days > 0:
|
|
798
|
+
body["ttl_days"] = int(ttl_days)
|
|
799
|
+
if time_bucket_days > 0:
|
|
800
|
+
body["time_bucket_days"] = int(time_bucket_days)
|
|
801
|
+
if append_only:
|
|
802
|
+
body["append_only"] = True
|
|
616
803
|
resp = self._request_json("POST", path, body)
|
|
617
804
|
if isinstance(resp, dict) and isinstance(resp.get("database"), dict):
|
|
618
805
|
db_obj = dict(resp["database"])
|
|
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "massengine"
|
|
7
|
-
version = "1.1
|
|
8
|
-
description = "Official Python SDK for the MassEngine filtered vector search database."
|
|
7
|
+
version = "1.2.1"
|
|
8
|
+
description = "Official Python SDK for the MassEngine filtered vector and hybrid search database."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "Apache-2.0"
|
|
11
11
|
license-files = ["LICENSE"]
|
|
@@ -13,7 +13,7 @@ requires-python = ">=3.9"
|
|
|
13
13
|
authors = [
|
|
14
14
|
{ name = "MassEngine", email = "dev@massengine.com" }
|
|
15
15
|
]
|
|
16
|
-
keywords = ["vector-database", "vector-search", "rag", "embeddings", "massengine"]
|
|
16
|
+
keywords = ["vector-database", "vector-search", "hybrid-search", "bm25", "rag", "embeddings", "massengine"]
|
|
17
17
|
classifiers = [
|
|
18
18
|
"Development Status :: 5 - Production/Stable",
|
|
19
19
|
"Intended Audience :: Developers",
|
|
@@ -61,6 +61,26 @@ class _MockGatewayHandler(BaseHTTPRequestHandler):
|
|
|
61
61
|
self.end_headers()
|
|
62
62
|
elif p == "/v1/tenants/oversized":
|
|
63
63
|
self._send(200, {"tenant": "oversized", "pad": "x" * 2048})
|
|
64
|
+
elif p == "/v1/usage":
|
|
65
|
+
self._send(
|
|
66
|
+
200,
|
|
67
|
+
{
|
|
68
|
+
"tenants": [{"tenant": "acme", "plan": "pro", "live_docs": 2}],
|
|
69
|
+
"total_live_docs": 2,
|
|
70
|
+
"total_live_bytes": 4096,
|
|
71
|
+
"total_read_units": 4,
|
|
72
|
+
"total_write_units": 3,
|
|
73
|
+
},
|
|
74
|
+
)
|
|
75
|
+
elif p == "/v1/tenants":
|
|
76
|
+
self._send(200, {"tenants": [{"tenant": "acme", "doc_count": 2, "byte_count": 4096}]})
|
|
77
|
+
elif p.endswith("/quota"):
|
|
78
|
+
self._send(200, {"tenant": "acme", "quota": {"plan": "pro", "max_docs": 100, "max_bytes": 4096}})
|
|
79
|
+
elif p == "/v1/tenants/acme":
|
|
80
|
+
resp_obj = {"tenant": "acme", "doc_count": 2, "byte_count": 4096}
|
|
81
|
+
if qs.get("database"):
|
|
82
|
+
resp_obj["database"] = qs["database"][0]
|
|
83
|
+
self._send(200, resp_obj)
|
|
64
84
|
elif p.endswith("/usage"):
|
|
65
85
|
self._send(200, {"tenant": "acme", "plan": "pro", "live_docs": 2, "read_units": 4, "write_units": 3})
|
|
66
86
|
elif p == "/v1/export" or p.endswith("/export"):
|
|
@@ -142,8 +162,12 @@ class _MockGatewayHandler(BaseHTTPRequestHandler):
|
|
|
142
162
|
self.end_headers()
|
|
143
163
|
return
|
|
144
164
|
if p == "/v1/flush":
|
|
145
|
-
|
|
165
|
+
if _MockGatewayHandler.recorded_bodies and len(_MockGatewayHandler.recorded_bodies) > 0:
|
|
166
|
+
pass
|
|
167
|
+
time.sleep(0.08)
|
|
146
168
|
self._send(200, {"flushed": True})
|
|
169
|
+
elif p == "/v1/compact":
|
|
170
|
+
self._send(200, {"compacted": True})
|
|
147
171
|
elif p.endswith("/keys"):
|
|
148
172
|
self._send(200, {"tenant": "acme", "key": "mk_test_key_123"})
|
|
149
173
|
elif p == "/v1/databases" or p.endswith("/databases"):
|
|
@@ -254,10 +278,10 @@ class TestMassEngineClient(unittest.TestCase):
|
|
|
254
278
|
_MockGatewayHandler.get_db_405 = False
|
|
255
279
|
|
|
256
280
|
def test_sdk_lifecycle_and_user_agent(self) -> None:
|
|
257
|
-
self.assertEqual(massengine.__version__, "1.1
|
|
281
|
+
self.assertEqual(massengine.__version__, "1.2.1")
|
|
258
282
|
admin = MassEngineClient(base_url=self.base_url, api_key=" admin-key ")
|
|
259
283
|
self.assertEqual(admin.health()["status"], "ok")
|
|
260
|
-
self.assertEqual(_MockGatewayHandler.last_user_agent, "massengine-python/1.1
|
|
284
|
+
self.assertEqual(_MockGatewayHandler.last_user_agent, "massengine-python/1.2.1")
|
|
261
285
|
r_ok = admin.ready()
|
|
262
286
|
self.assertTrue(r_ok["ready"])
|
|
263
287
|
self.assertEqual(r_ok["unavailable_shards"], [])
|
|
@@ -316,20 +340,89 @@ class TestMassEngineClient(unittest.TestCase):
|
|
|
316
340
|
revoked_client.get_doc("acme", "py-1")
|
|
317
341
|
self.assertEqual(ctx.exception.status_code, 401)
|
|
318
342
|
|
|
319
|
-
def
|
|
343
|
+
def test_hybrid_lexical_sparse_search_and_validation(self) -> None:
|
|
320
344
|
client = MassEngineClient(base_url=self.base_url, api_key="mk_valid")
|
|
321
|
-
|
|
322
|
-
SearchRequest(tenant="acme", vector=[1.0, 0.0], query_text="removed") # type: ignore[call-arg]
|
|
323
|
-
with self.assertRaises(TypeError):
|
|
324
|
-
SearchRequest(tenant="acme", vector=[1.0, 0.0], hybrid_alpha=0.5) # type: ignore[call-arg]
|
|
325
|
-
with self.assertRaises(TypeError):
|
|
326
|
-
client.search("acme", vector=[1.0, 0.0], query_text="removed") # type: ignore[call-arg]
|
|
327
|
-
with self.assertRaises(TypeError):
|
|
328
|
-
client.search("acme", vector=[1.0, 0.0], hybrid_alpha=0.5) # type: ignore[call-arg]
|
|
345
|
+
_MockGatewayHandler.recorded_bodies.clear()
|
|
329
346
|
|
|
347
|
+
# 1. Ingest with sparse_indices + sparse_values
|
|
348
|
+
ing = client.ingest(
|
|
349
|
+
"acme",
|
|
350
|
+
[
|
|
351
|
+
Doc(
|
|
352
|
+
id="py-hybrid-1",
|
|
353
|
+
vector=[1.0, 0.0],
|
|
354
|
+
sparse_indices=[10, 42],
|
|
355
|
+
sparse_values=[1.5, 0.75],
|
|
356
|
+
metadata={"title": "distributed consensus"},
|
|
357
|
+
)
|
|
358
|
+
],
|
|
359
|
+
)
|
|
360
|
+
self.assertEqual(ing["ingested"], 1)
|
|
361
|
+
ing_payload = json.loads(_MockGatewayHandler.recorded_bodies[-1])
|
|
362
|
+
self.assertEqual(ing_payload["docs"][0]["sparse_indices"], [10, 42])
|
|
363
|
+
self.assertEqual(ing_payload["docs"][0]["sparse_values"], [1.5, 0.75])
|
|
364
|
+
|
|
365
|
+
# 2. Pure BM25 lexical search (vector omitted)
|
|
366
|
+
sr_bm25 = client.search("acme", query_text="distributed consensus", k=5)
|
|
367
|
+
self.assertEqual(len(sr_bm25["hits"]), 1)
|
|
368
|
+
bm25_body = json.loads(_MockGatewayHandler.recorded_bodies[-1])
|
|
369
|
+
self.assertNotIn("vector", bm25_body)
|
|
370
|
+
self.assertEqual(bm25_body["query_text"], "distributed consensus")
|
|
371
|
+
|
|
372
|
+
# 3. Pure sparse vector search (vector omitted)
|
|
373
|
+
sr_sparse = client.search("acme", sparse_indices=[10, 42], sparse_values=[1.0, 0.5], k=5)
|
|
374
|
+
self.assertEqual(len(sr_sparse["hits"]), 1)
|
|
375
|
+
sparse_body = json.loads(_MockGatewayHandler.recorded_bodies[-1])
|
|
376
|
+
self.assertNotIn("vector", sparse_body)
|
|
377
|
+
self.assertEqual(sparse_body["sparse_indices"], [10, 42])
|
|
378
|
+
|
|
379
|
+
# 4. Hybrid dense + BM25 + sparse RRF with hybrid_alpha & skip_meta
|
|
380
|
+
sr_hybrid = client.search(
|
|
381
|
+
"acme",
|
|
382
|
+
vector=[1.0, 0.0],
|
|
383
|
+
query_text="consensus",
|
|
384
|
+
hybrid_alpha=0.65,
|
|
385
|
+
sparse_indices=[10],
|
|
386
|
+
sparse_values=[0.8],
|
|
387
|
+
skip_meta=True,
|
|
388
|
+
k=10,
|
|
389
|
+
)
|
|
390
|
+
self.assertEqual(len(sr_hybrid["hits"]), 1)
|
|
391
|
+
hybrid_body = json.loads(_MockGatewayHandler.recorded_bodies[-1])
|
|
392
|
+
self.assertEqual(hybrid_body["hybrid_alpha"], 0.65)
|
|
393
|
+
self.assertTrue(hybrid_body["skip_meta"])
|
|
394
|
+
|
|
395
|
+
# 5. Batch search with SearchRequest & dict hybrid/BM25/sparse queries
|
|
396
|
+
bs = client.batch_search(
|
|
397
|
+
[
|
|
398
|
+
SearchRequest(tenant="acme", query_text="consensus", k=3),
|
|
399
|
+
{"tenant": "acme", "sparse_indices": [42], "sparse_values": [1.25], "k": 3},
|
|
400
|
+
]
|
|
401
|
+
)
|
|
402
|
+
self.assertEqual(len(bs["results"]), 2)
|
|
403
|
+
|
|
404
|
+
# 6. Client-side validation rejects empty or malformed queries without contacting server
|
|
330
405
|
before_count = len(_MockGatewayHandler.recorded_paths)
|
|
406
|
+
with self.assertRaises(ValueError):
|
|
407
|
+
client.search("acme")
|
|
331
408
|
with self.assertRaises(ValueError):
|
|
332
409
|
client.search("acme", vector=[])
|
|
410
|
+
with self.assertRaises(ValueError):
|
|
411
|
+
client.search("acme", query_text=" ")
|
|
412
|
+
with self.assertRaises(ValueError):
|
|
413
|
+
client.search("acme", vector=[1.0, 0.0], hybrid_alpha=-0.1)
|
|
414
|
+
with self.assertRaises(ValueError):
|
|
415
|
+
client.search("acme", vector=[1.0, 0.0], hybrid_alpha=1.5)
|
|
416
|
+
with self.assertRaises(ValueError):
|
|
417
|
+
client.search("acme", vector=[1.0, 0.0], hybrid_alpha=float("nan"))
|
|
418
|
+
with self.assertRaises(ValueError):
|
|
419
|
+
client.search("acme", sparse_indices=[1, 2], sparse_values=[0.5])
|
|
420
|
+
with self.assertRaises(ValueError):
|
|
421
|
+
client.search("acme", sparse_indices=[-1], sparse_values=[0.5])
|
|
422
|
+
with self.assertRaises(ValueError):
|
|
423
|
+
client.search("acme", sparse_indices=[1], sparse_values=[float("inf")])
|
|
424
|
+
with self.assertRaises(ValueError):
|
|
425
|
+
client.ingest("acme", [Doc(id="bad", vector=[1.0, 0.0], sparse_indices=[1], sparse_values=[0.5, 0.6])])
|
|
333
426
|
with self.assertRaises(ValueError):
|
|
334
427
|
client.batch_search([])
|
|
335
428
|
with self.assertRaises(ValueError):
|
|
@@ -454,12 +547,19 @@ class TestMassEngineClient(unittest.TestCase):
|
|
|
454
547
|
self.assertEqual(dbs[0]["database"], "analytics")
|
|
455
548
|
|
|
456
549
|
_MockGatewayHandler.get_db_405 = False
|
|
550
|
+
before_direct = len(_MockGatewayHandler.recorded_paths)
|
|
457
551
|
got_db = client.get_database(tenant, "analytics")
|
|
458
552
|
self.assertEqual(got_db["database"], "analytics")
|
|
553
|
+
self.assertEqual(len(_MockGatewayHandler.recorded_paths) - before_direct, 1)
|
|
459
554
|
|
|
460
555
|
_MockGatewayHandler.get_db_405 = True
|
|
556
|
+
before_fb = len(_MockGatewayHandler.recorded_paths)
|
|
461
557
|
got_fb = client.get_database(tenant, "analytics")
|
|
462
558
|
self.assertEqual(got_fb["database"], "analytics")
|
|
559
|
+
self.assertEqual(len(_MockGatewayHandler.recorded_paths) - before_fb, 2)
|
|
560
|
+
with self.assertRaises(MassEngineError) as miss_ctx:
|
|
561
|
+
client.get_database(tenant, "nonexistent")
|
|
562
|
+
self.assertEqual(miss_ctx.exception.status_code, 404)
|
|
463
563
|
|
|
464
564
|
deleted = client.delete_database(tenant, "analytics")
|
|
465
565
|
self.assertEqual(deleted, 2)
|
|
@@ -539,10 +639,112 @@ class TestMassEngineClient(unittest.TestCase):
|
|
|
539
639
|
tiny_export_client.export_tenant("acme")
|
|
540
640
|
self.assertIn("max_response_bytes", str(ctx2.exception))
|
|
541
641
|
|
|
542
|
-
fast_client = MassEngineClient(base_url=self.base_url, timeout=0.
|
|
642
|
+
fast_client = MassEngineClient(base_url=self.base_url, timeout=0.02)
|
|
543
643
|
with self.assertRaises((TimeoutError, socket.timeout, OSError)):
|
|
544
644
|
fast_client.flush()
|
|
545
645
|
|
|
646
|
+
def test_min_score_nan_timeout_and_strict_json_validation(self) -> None:
|
|
647
|
+
client = MassEngineClient(base_url=self.base_url, api_key="mk_valid")
|
|
648
|
+
_MockGatewayHandler.recorded_paths.clear()
|
|
649
|
+
_MockGatewayHandler.recorded_bodies.clear()
|
|
650
|
+
|
|
651
|
+
# Finite min_score (including 0.0 and negative) succeeds
|
|
652
|
+
self.assertEqual(SearchRequest(vector=[1.0, 0.0], min_score=0.0).to_dict()["min_score"], 0.0)
|
|
653
|
+
client.search("acme", vector=[1.0, 0.0], min_score=-0.25)
|
|
654
|
+
self.assertEqual(json.loads(_MockGatewayHandler.recorded_bodies[-1])["min_score"], -0.25)
|
|
655
|
+
client.batch_search([{"tenant": "acme", "vector": [1.0, 0.0], "min_score": 0.0}])
|
|
656
|
+
|
|
657
|
+
before = len(_MockGatewayHandler.recorded_paths)
|
|
658
|
+
for bad_ms in (float("nan"), float("inf"), float("-inf"), True, "0.5"):
|
|
659
|
+
with self.assertRaises(ValueError):
|
|
660
|
+
SearchRequest(vector=[1.0, 0.0], min_score=bad_ms).to_dict() # type: ignore[arg-type]
|
|
661
|
+
with self.assertRaises(ValueError):
|
|
662
|
+
client.search("acme", vector=[1.0, 0.0], min_score=bad_ms) # type: ignore[arg-type]
|
|
663
|
+
with self.assertRaises(ValueError):
|
|
664
|
+
client.batch_search([{"tenant": "acme", "vector": [1.0, 0.0], "min_score": bad_ms}])
|
|
665
|
+
|
|
666
|
+
for bad_to in (float("nan"), float("inf"), float("-inf"), -1.0, True):
|
|
667
|
+
with self.assertRaises(ValueError):
|
|
668
|
+
MassEngineClient(base_url=self.base_url, timeout=bad_to) # type: ignore[arg-type]
|
|
669
|
+
|
|
670
|
+
# Non-finite float in metadata must be rejected instead of producing invalid NaN JSON
|
|
671
|
+
with self.assertRaises(ValueError):
|
|
672
|
+
client.ingest("acme", [Doc(id="nan-meta", vector=[1.0, 0.0], metadata={"bad": float("nan")})])
|
|
673
|
+
with self.assertRaises(ValueError):
|
|
674
|
+
client.import_tenant("acme", [Doc(id="inf-meta", vector=[1.0, 0.0], metadata={"bad": float("inf")})])
|
|
675
|
+
self.assertEqual(len(_MockGatewayHandler.recorded_paths), before)
|
|
676
|
+
|
|
677
|
+
def test_admin_and_tenant_management_endpoints(self) -> None:
|
|
678
|
+
admin = MassEngineClient(base_url=self.base_url, api_key="meadm_test")
|
|
679
|
+
usage = admin.list_usage()
|
|
680
|
+
self.assertEqual(usage["total_live_docs"], 2)
|
|
681
|
+
|
|
682
|
+
tenants = admin.list_tenants()
|
|
683
|
+
self.assertEqual(len(tenants), 1)
|
|
684
|
+
self.assertEqual(tenants[0]["tenant"], "acme")
|
|
685
|
+
|
|
686
|
+
t_info = admin.get_tenant("acme", database="analytics")
|
|
687
|
+
self.assertEqual(t_info["database"], "analytics")
|
|
688
|
+
|
|
689
|
+
quota = admin.get_tenant_quota("acme")
|
|
690
|
+
self.assertEqual(quota["plan"], "pro")
|
|
691
|
+
|
|
692
|
+
rev = admin.revoke_tenant_key("acme", "mk_old")
|
|
693
|
+
self.assertTrue(rev["revoked"])
|
|
694
|
+
|
|
695
|
+
self.assertTrue(admin.flush()["flushed"])
|
|
696
|
+
self.assertTrue(admin.compact()["compacted"])
|
|
697
|
+
self.assertEqual(admin.delete_tenant("acme"), 2)
|
|
698
|
+
|
|
699
|
+
def test_api_parity_v121(self) -> None:
|
|
700
|
+
default_client = MassEngineClient()
|
|
701
|
+
self.assertEqual(default_client.base_url, "http://localhost:8080")
|
|
702
|
+
self.assertEqual(massengine.__version__, "1.2.1")
|
|
703
|
+
|
|
704
|
+
# Database creation with ttl_days, time_bucket_days, append_only
|
|
705
|
+
client = MassEngineClient(base_url=self.base_url, api_key="meadm_test")
|
|
706
|
+
_MockGatewayHandler.recorded_bodies.clear()
|
|
707
|
+
_MockGatewayHandler.recorded_paths.clear()
|
|
708
|
+
client.create_database(
|
|
709
|
+
"acme",
|
|
710
|
+
"events",
|
|
711
|
+
data_type="int8",
|
|
712
|
+
ttl_days=30,
|
|
713
|
+
time_bucket_days=1,
|
|
714
|
+
append_only=True,
|
|
715
|
+
)
|
|
716
|
+
db_body = json.loads(_MockGatewayHandler.recorded_bodies[-1])
|
|
717
|
+
self.assertEqual(db_body["ttl_days"], 30)
|
|
718
|
+
self.assertEqual(db_body["time_bucket_days"], 1)
|
|
719
|
+
self.assertTrue(db_body["append_only"])
|
|
720
|
+
|
|
721
|
+
# Doc with doc_id (without string id) and no_ttl + batch_size on import_tenant
|
|
722
|
+
imported = client.import_tenant(
|
|
723
|
+
"acme",
|
|
724
|
+
[
|
|
725
|
+
Doc(doc_id=42, vector=[1.0, 0.0], no_ttl=True),
|
|
726
|
+
{"id": "str-doc", "vector": [0.0, 1.0], "no_ttl": True},
|
|
727
|
+
],
|
|
728
|
+
database="events",
|
|
729
|
+
batch_size=500,
|
|
730
|
+
)
|
|
731
|
+
self.assertEqual(imported, 2)
|
|
732
|
+
self.assertIn("database=events", _MockGatewayHandler.recorded_paths[-1])
|
|
733
|
+
self.assertIn("batch_size=500", _MockGatewayHandler.recorded_paths[-1])
|
|
734
|
+
|
|
735
|
+
with self.assertRaises(ValueError):
|
|
736
|
+
Doc(vector=[1.0, 0.0]).to_dict()
|
|
737
|
+
with self.assertRaises(ValueError):
|
|
738
|
+
client.import_tenant("acme", [Doc(id="x", vector=[1.0, 0.0])], batch_size=5000)
|
|
739
|
+
|
|
740
|
+
# Effort validation in SearchRequest / search / batch_search
|
|
741
|
+
client.search("acme", vector=[1.0, 0.0], k=5, effort=50)
|
|
742
|
+
self.assertEqual(json.loads(_MockGatewayHandler.recorded_bodies[-1])["effort"], 50)
|
|
743
|
+
with self.assertRaises(ValueError):
|
|
744
|
+
client.search("acme", vector=[1.0, 0.0], k=5, effort=101)
|
|
745
|
+
with self.assertRaises(ValueError):
|
|
746
|
+
client.batch_search([{"tenant": "acme", "vector": [1.0, 0.0], "effort": 0}])
|
|
747
|
+
|
|
546
748
|
|
|
547
749
|
if __name__ == "__main__":
|
|
548
750
|
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|