massengine 1.2.0__tar.gz → 1.2.3__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.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.5
1
+ Metadata-Version: 2.4
2
2
  Name: massengine
3
- Version: 1.2.0
3
+ Version: 1.2.3
4
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
@@ -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,6 +66,7 @@ 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"])
@@ -97,7 +98,7 @@ print(usage)
97
98
  Create isolated databases within a tenant and scope operations using `database=` (pass `tenant=""` when authenticating with a tenant-scoped `mk_...` key):
98
99
 
99
100
  ```python
100
- 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)
101
102
 
102
103
  client.ingest(
103
104
  "",
@@ -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,6 +42,7 @@ 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"])
@@ -73,7 +74,7 @@ print(usage)
73
74
  Create isolated databases within a tenant and scope operations using `database=` (pass `tenant=""` when authenticating with a tenant-scoped `mk_...` key):
74
75
 
75
76
  ```python
76
- 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)
77
78
 
78
79
  client.ingest(
79
80
  "",
@@ -11,12 +11,16 @@ import urllib.error
11
11
  import urllib.parse
12
12
  import urllib.request
13
13
 
14
- SDK_VERSION = "1.2.0"
14
+ SDK_VERSION = "1.2.3"
15
15
  USER_AGENT = f"massengine-python/{SDK_VERSION}"
16
16
  DEFAULT_MAX_RESPONSE_BYTES = 64 * 1024 * 1024 # 64 MiB
17
17
  MAX_ERROR_RESPONSE_BYTES = 65536 # 64 KiB
18
18
  _MAX_LINE_READ_CHUNK = 4 * 1024 * 1024
19
19
  _MAX_SPARSE_TERMS = 65536
20
+ _MAX_DOC_ID = (1 << 43) - 2
21
+ _MAX_COORD_ABS = 1e15
22
+ _MAX_BATCH_SEARCH_SIZE = 4096
23
+ _MAX_BATCH_GET_SIZE = 1000
20
24
 
21
25
 
22
26
  class MassEngineError(Exception):
@@ -75,8 +79,8 @@ def _validate_finite_float_seq(vector: Any, label: str = "vector") -> List[float
75
79
  raise ValueError(f"{label} must be a sequence of finite numbers") from None
76
80
  out: List[float] = []
77
81
  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")
82
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(float(v)) or abs(float(v)) > _MAX_COORD_ABS:
83
+ raise ValueError(f"{label} must contain only finite numbers within bounds")
80
84
  out.append(float(v))
81
85
  return out
82
86
 
@@ -132,6 +136,12 @@ def _validate_hybrid_alpha(alpha: Any) -> float:
132
136
  return val
133
137
 
134
138
 
139
+ def _validate_min_score(val: Any) -> float:
140
+ if isinstance(val, bool) or not isinstance(val, (int, float)) or not math.isfinite(float(val)):
141
+ raise ValueError("min_score must be a finite number")
142
+ return float(val)
143
+
144
+
135
145
  def _extract_error_message(raw_text: str) -> str:
136
146
  msg = raw_text.strip()
137
147
  try:
@@ -143,27 +153,70 @@ def _extract_error_message(raw_text: str) -> str:
143
153
  return msg
144
154
 
145
155
 
156
+ def _check_int(val: Any, label: str, lo: int, hi: Optional[int] = None) -> int:
157
+ if isinstance(val, bool) or not isinstance(val, int) or val < lo or (hi is not None and val > hi):
158
+ bound_desc = f"[{lo}, {hi}]" if hi is not None else f">= {lo}"
159
+ raise ValueError(f"{label} must be an integer in {bound_desc}")
160
+ return val
161
+
162
+
163
+ def _check_bool(val: Any, label: str) -> bool:
164
+ if not isinstance(val, bool):
165
+ raise ValueError(f"{label} must be a bool")
166
+ return val
167
+
168
+
169
+ def _validate_uint16_seq(vals: Any, label: str) -> List[int]:
170
+ if isinstance(vals, (str, bytes, bytearray)):
171
+ raise ValueError(f"{label} must be a sequence of uint16 integers")
172
+ try:
173
+ items = list(vals)
174
+ except TypeError:
175
+ raise ValueError(f"{label} must be a sequence of uint16 integers") from None
176
+ return [_check_int(item, label, 0, 65535) for item in items]
177
+
178
+
179
+ def _validate_doc_id_int(val: Any) -> int:
180
+ if isinstance(val, bool) or not isinstance(val, int) or val < 0 or val > _MAX_DOC_ID:
181
+ raise ValueError(f"doc_id must be an integer in [0, {_MAX_DOC_ID}]")
182
+ return val
183
+
184
+
185
+ def _validate_effort(val: Any) -> int:
186
+ if isinstance(val, bool) or not isinstance(val, int) or val < 1 or val > 100:
187
+ raise ValueError("effort must be an integer between 1 and 100")
188
+ return val
189
+
190
+
146
191
  @dataclass
147
192
  class Doc:
148
193
  """Represents a document for ingestion or export."""
149
194
 
150
- id: str
151
- vector: Sequence[float]
195
+ id: str = ""
196
+ vector: Sequence[float] = ()
197
+ doc_id: Optional[int] = None
152
198
  date: Optional[int] = None
153
199
  category: Optional[int] = None
200
+ no_ttl: bool = False
154
201
  metadata: Optional[Dict[str, Any]] = None
155
202
  database: Optional[str] = None
156
203
  sparse_indices: Optional[Sequence[int]] = None
157
204
  sparse_values: Optional[Sequence[float]] = None
158
205
 
159
206
  def to_dict(self) -> Dict[str, Any]:
160
- _escape_doc_id(self.id)
207
+ if self.id == "" and self.doc_id is None:
208
+ raise ValueError("document requires a non-empty id or integer doc_id")
209
+ if self.id != "":
210
+ _escape_doc_id(self.id)
161
211
  vec = _validate_vector(self.vector)
162
212
  sparse = _validate_sparse(self.sparse_indices, self.sparse_values)
163
213
  out: Dict[str, Any] = {
164
- "id": self.id,
165
214
  "vector": vec,
166
215
  }
216
+ if self.id != "":
217
+ out["id"] = self.id
218
+ if self.doc_id is not None:
219
+ out["doc_id"] = _validate_doc_id_int(self.doc_id)
167
220
  if sparse is not None:
168
221
  out["sparse_indices"] = sparse[0]
169
222
  out["sparse_values"] = sparse[1]
@@ -171,9 +224,11 @@ class Doc:
171
224
  _validate_identifier(self.database, "database")
172
225
  out["database"] = self.database
173
226
  if self.date is not None:
174
- out["date"] = int(self.date)
227
+ out["date"] = _check_int(self.date, "date", 0, 65535)
175
228
  if self.category is not None:
176
- out["category"] = int(self.category)
229
+ out["category"] = _check_int(self.category, "category", 0, 65535)
230
+ if _check_bool(self.no_ttl, "no_ttl"):
231
+ out["no_ttl"] = True
177
232
  if self.metadata is not None:
178
233
  out["metadata"] = self.metadata
179
234
  return out
@@ -194,6 +249,7 @@ class SearchRequest:
194
249
  metadata_filter: Optional[Dict[str, Any]] = None
195
250
  offset: int = 0
196
251
  min_score: Optional[float] = None
252
+ effort: Optional[int] = None
197
253
  rerank_pool: Optional[int] = None
198
254
  nprobe: Optional[int] = None
199
255
  skip_meta: bool = False
@@ -216,7 +272,7 @@ class SearchRequest:
216
272
  raise ValueError("search requires a non-empty vector, query_text, or sparse_indices")
217
273
 
218
274
  out: Dict[str, Any] = {
219
- "k": int(self.k),
275
+ "k": _check_int(self.k, "k", 1, 1000),
220
276
  }
221
277
  if len(vec) > 0:
222
278
  out["vector"] = vec
@@ -235,28 +291,37 @@ class SearchRequest:
235
291
  out["database"] = self.database
236
292
  if self.metadata_filter is not None:
237
293
  out["metadata_filter"] = self.metadata_filter
238
- if self.offset:
239
- out["offset"] = int(self.offset)
294
+ offset_val = _check_int(self.offset, "offset", 0, 10000)
295
+ if offset_val > 0:
296
+ out["offset"] = offset_val
240
297
  if self.min_score is not None:
241
- out["min_score"] = float(self.min_score)
242
- if self.rerank_pool:
243
- out["rerank_pool"] = int(self.rerank_pool)
244
- if self.nprobe:
245
- out["nprobe"] = int(self.nprobe)
246
- if self.skip_meta:
298
+ out["min_score"] = _validate_min_score(self.min_score)
299
+ if self.effort is not None:
300
+ out["effort"] = _validate_effort(self.effort)
301
+ if self.rerank_pool is not None:
302
+ rp_val = _check_int(self.rerank_pool, "rerank_pool", 0)
303
+ if rp_val > 0:
304
+ out["rerank_pool"] = rp_val
305
+ if self.nprobe is not None:
306
+ np_val = _check_int(self.nprobe, "nprobe", 0)
307
+ if np_val > 0:
308
+ out["nprobe"] = np_val
309
+ if _check_bool(self.skip_meta, "skip_meta"):
247
310
  out["skip_meta"] = True
248
311
  if self.min_date is not None:
249
- out["min_date"] = int(self.min_date)
312
+ out["min_date"] = _check_int(self.min_date, "min_date", 0, 65535)
250
313
  if self.max_date is not None:
251
- out["max_date"] = int(self.max_date)
314
+ out["max_date"] = _check_int(self.max_date, "max_date", 0, 65535)
252
315
  if self.category is not None:
253
- out["category"] = int(self.category)
254
- if self.categories:
255
- out["categories"] = [int(c) for c in self.categories]
316
+ out["category"] = _check_int(self.category, "category", 0, 65535)
317
+ if self.categories is not None:
318
+ cats = _validate_uint16_seq(self.categories, "categories")
319
+ if cats:
320
+ out["categories"] = cats
256
321
  if self.min_doc_id is not None:
257
- out["min_doc_id"] = int(self.min_doc_id)
322
+ out["min_doc_id"] = _check_int(self.min_doc_id, "min_doc_id", 0, _MAX_DOC_ID)
258
323
  if self.max_doc_id is not None:
259
- out["max_doc_id"] = int(self.max_doc_id)
324
+ out["max_doc_id"] = _check_int(self.max_doc_id, "max_doc_id", 0, _MAX_DOC_ID)
260
325
  return out
261
326
 
262
327
 
@@ -272,13 +337,15 @@ class TenantQuota:
272
337
  suspended: bool = False
273
338
 
274
339
  def to_dict(self) -> Dict[str, Any]:
340
+ if isinstance(self.max_qps, bool) or not isinstance(self.max_qps, (int, float)) or not math.isfinite(float(self.max_qps)) or float(self.max_qps) < 0:
341
+ raise ValueError("max_qps must be a finite non-negative number")
275
342
  return {
276
343
  "plan": self.plan,
277
- "max_docs": int(self.max_docs),
278
- "max_bytes": int(self.max_bytes),
344
+ "max_docs": _check_int(self.max_docs, "max_docs", 0, 0xFFFFFFFFFFFFFFFF),
345
+ "max_bytes": _check_int(self.max_bytes, "max_bytes", 0, 0xFFFFFFFFFFFFFFFF),
279
346
  "max_qps": float(self.max_qps),
280
- "burst": int(self.burst),
281
- "suspended": bool(self.suspended),
347
+ "burst": _check_int(self.burst, "burst", 0, 0xFFFFFFFFFFFFFFFF),
348
+ "suspended": _check_bool(self.suspended, "suspended"),
282
349
  }
283
350
 
284
351
 
@@ -287,14 +354,14 @@ class MassEngineClient:
287
354
 
288
355
  def __init__(
289
356
  self,
290
- base_url: str = "http://localhost:8081",
357
+ base_url: str = "http://localhost:8080",
291
358
  api_key: Optional[str] = None,
292
359
  timeout: float = 30.0,
293
360
  max_response_bytes: int = DEFAULT_MAX_RESPONSE_BYTES,
294
361
  ) -> None:
295
362
  self.base_url = self._validate_base_url(base_url)
296
363
  self._api_key = self._validate_api_key(api_key)
297
- if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or timeout <= 0:
364
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not math.isfinite(float(timeout)) or timeout <= 0:
298
365
  raise ValueError("timeout must be a positive number")
299
366
  if isinstance(max_response_bytes, bool) or not isinstance(max_response_bytes, int) or max_response_bytes <= 0:
300
367
  raise ValueError("max_response_bytes must be a positive integer")
@@ -317,18 +384,21 @@ class MassEngineClient:
317
384
  if not isinstance(base_url, str) or not base_url.strip():
318
385
  raise ValueError("base_url must be a valid http or https URL")
319
386
  cleaned = base_url.strip().rstrip("/")
320
- if any(ord(ch) <= 0x20 or ord(ch) == 0x7F for ch in cleaned):
387
+ if any(ord(ch) <= 0x20 or ord(ch) == 0x7F or ch in ("?", "#", "\\") for ch in cleaned):
321
388
  raise ValueError("base_url contains invalid characters")
322
389
  parsed = urllib.parse.urlsplit(cleaned)
323
390
  if (
324
391
  parsed.scheme not in ("http", "https")
325
392
  or not parsed.netloc
393
+ or not parsed.hostname
326
394
  or parsed.username is not None
327
395
  or parsed.password is not None
328
396
  or parsed.query
329
397
  or parsed.fragment
330
398
  ):
331
399
  raise ValueError("base_url must use http or https scheme with a valid host")
400
+ if any(seg in (".", "..") for seg in parsed.path.split("/")):
401
+ raise ValueError("base_url must not contain dot path segments")
332
402
  return cleaned
333
403
 
334
404
  @staticmethod
@@ -380,7 +450,7 @@ class MassEngineClient:
380
450
  data: Optional[bytes] = None
381
451
  content_type: Optional[str] = None
382
452
  if body is not None:
383
- data = json.dumps(body).encode("utf-8")
453
+ data = json.dumps(body, allow_nan=False).encode("utf-8")
384
454
  content_type = "application/json"
385
455
 
386
456
  req = urllib.request.Request(
@@ -447,14 +517,32 @@ class MassEngineClient:
447
517
  return d.to_dict()
448
518
  if not isinstance(d, dict):
449
519
  raise ValueError("document must be a Doc or dict")
450
- cls._esc_doc_id(d.get("id")) # type: ignore[arg-type]
451
- if "vector" in d:
452
- _validate_vector(d.get("vector"))
520
+ raw_id = d.get("id")
521
+ raw_doc_id = d.get("doc_id")
522
+ if (raw_id is None or raw_id == "") and raw_doc_id is None:
523
+ raise ValueError("document requires a non-empty id or integer doc_id")
524
+ if raw_id is not None and raw_id != "":
525
+ cls._esc_doc_id(raw_id) # type: ignore[arg-type]
526
+ if raw_doc_id is not None:
527
+ _validate_doc_id_int(raw_doc_id)
528
+ if "vector" not in d:
529
+ raise ValueError("document requires a non-empty vector")
530
+ out = dict(d)
531
+ out["vector"] = _validate_vector(d.get("vector"))
453
532
  if "sparse_indices" in d or "sparse_values" in d:
454
- _validate_sparse(d.get("sparse_indices"), d.get("sparse_values"))
533
+ sparse = _validate_sparse(d.get("sparse_indices"), d.get("sparse_values"))
534
+ if sparse is not None:
535
+ out["sparse_indices"] = sparse[0]
536
+ out["sparse_values"] = sparse[1]
455
537
  if d.get("database"):
456
538
  cls._esc_database(d["database"])
457
- return d
539
+ if d.get("date") is not None:
540
+ out["date"] = _check_int(d["date"], "date", 0, 65535)
541
+ if d.get("category") is not None:
542
+ out["category"] = _check_int(d["category"], "category", 0, 65535)
543
+ if "no_ttl" in d and d["no_ttl"] is not None:
544
+ out["no_ttl"] = _check_bool(d["no_ttl"], "no_ttl")
545
+ return out
458
546
 
459
547
  def ingest(
460
548
  self,
@@ -466,6 +554,8 @@ class MassEngineClient:
466
554
  """Inserts or upserts a batch of documents into `tenant` (or the bound `mk_...` key's tenant when empty)."""
467
555
  esc_tenant = self._validate_optional_tenant(tenant)
468
556
  db = self._validate_optional_database(database)
557
+ if not docs:
558
+ raise ValueError("docs must be non-empty")
469
559
  serialized = [self._serialize_doc(d) for d in docs]
470
560
  path = "/v1/ingest" if esc_tenant == "" else f"/v1/tenants/{esc_tenant}/ingest"
471
561
  body: Dict[str, Any] = {"docs": serialized}
@@ -487,6 +577,7 @@ class MassEngineClient:
487
577
  metadata_filter: Optional[Dict[str, Any]] = None,
488
578
  offset: int = 0,
489
579
  min_score: Optional[float] = None,
580
+ effort: Optional[int] = None,
490
581
  rerank_pool: Optional[int] = None,
491
582
  nprobe: Optional[int] = None,
492
583
  skip_meta: bool = False,
@@ -510,6 +601,7 @@ class MassEngineClient:
510
601
  metadata_filter=metadata_filter,
511
602
  offset=offset,
512
603
  min_score=min_score,
604
+ effort=effort,
513
605
  rerank_pool=rerank_pool,
514
606
  nprobe=nprobe,
515
607
  skip_meta=skip_meta,
@@ -530,8 +622,8 @@ class MassEngineClient:
530
622
  database: str = "",
531
623
  ) -> Dict[str, Any]:
532
624
  """Executes multiple dense, lexical, sparse, or hybrid search queries in a single round-trip."""
533
- if not queries:
534
- raise ValueError("queries must be non-empty")
625
+ if not queries or len(queries) > _MAX_BATCH_SEARCH_SIZE:
626
+ raise ValueError(f"queries length must be between 1 and {_MAX_BATCH_SEARCH_SIZE}")
535
627
  esc_tenant = self._validate_optional_tenant(tenant)
536
628
  db = self._validate_optional_database(database)
537
629
  serialized: List[Dict[str, Any]] = []
@@ -557,8 +649,34 @@ class MassEngineClient:
557
649
  if sparse is not None:
558
650
  q_copy["sparse_indices"] = sparse[0]
559
651
  q_copy["sparse_values"] = sparse[1]
652
+ if "k" in q_copy and q_copy["k"] is not None:
653
+ q_copy["k"] = _check_int(q_copy["k"], "k", 1, 1000)
654
+ if q_copy.get("offset") is not None:
655
+ q_copy["offset"] = _check_int(q_copy["offset"], "offset", 0, 10000)
656
+ if q_copy.get("rerank_pool") is not None:
657
+ q_copy["rerank_pool"] = _check_int(q_copy["rerank_pool"], "rerank_pool", 0)
658
+ if q_copy.get("nprobe") is not None:
659
+ q_copy["nprobe"] = _check_int(q_copy["nprobe"], "nprobe", 0)
660
+ if "skip_meta" in q_copy and q_copy["skip_meta"] is not None:
661
+ q_copy["skip_meta"] = _check_bool(q_copy["skip_meta"], "skip_meta")
662
+ if q_copy.get("min_date") is not None:
663
+ q_copy["min_date"] = _check_int(q_copy["min_date"], "min_date", 0, 65535)
664
+ if q_copy.get("max_date") is not None:
665
+ q_copy["max_date"] = _check_int(q_copy["max_date"], "max_date", 0, 65535)
666
+ if q_copy.get("category") is not None:
667
+ q_copy["category"] = _check_int(q_copy["category"], "category", 0, 65535)
668
+ if q_copy.get("categories") is not None:
669
+ q_copy["categories"] = _validate_uint16_seq(q_copy["categories"], "categories")
670
+ if q_copy.get("min_doc_id") is not None:
671
+ q_copy["min_doc_id"] = _check_int(q_copy["min_doc_id"], "min_doc_id", 0, _MAX_DOC_ID)
672
+ if q_copy.get("max_doc_id") is not None:
673
+ q_copy["max_doc_id"] = _check_int(q_copy["max_doc_id"], "max_doc_id", 0, _MAX_DOC_ID)
560
674
  if q_copy.get("hybrid_alpha") is not None:
561
675
  q_copy["hybrid_alpha"] = _validate_hybrid_alpha(q_copy["hybrid_alpha"])
676
+ if q_copy.get("min_score") is not None:
677
+ q_copy["min_score"] = _validate_min_score(q_copy["min_score"])
678
+ if q_copy.get("effort") is not None:
679
+ q_copy["effort"] = _validate_effort(q_copy["effort"])
562
680
  if q_copy.get("tenant"):
563
681
  self._esc_tenant(q_copy["tenant"])
564
682
  if q_copy.get("database"):
@@ -602,10 +720,10 @@ class MassEngineClient:
602
720
  if metadata is not None:
603
721
  body["metadata"] = metadata
604
722
  if date is not None:
605
- body["date"] = int(date)
723
+ body["date"] = _check_int(date, "date", 0, 65535)
606
724
  if category is not None:
607
- body["category"] = int(category)
608
- if replace_metadata:
725
+ body["category"] = _check_int(category, "category", 0, 65535)
726
+ if _check_bool(replace_metadata, "replace_metadata"):
609
727
  body["replace_metadata"] = True
610
728
  return self._request_json("PATCH", self._doc_path(tenant, doc_id), body)
611
729
 
@@ -620,6 +738,8 @@ class MassEngineClient:
620
738
  esc_tenant = self._validate_optional_tenant(tenant)
621
739
  db = self._validate_optional_database(database)
622
740
  id_list = list(ids)
741
+ if not id_list or len(id_list) > _MAX_BATCH_GET_SIZE:
742
+ raise ValueError(f"ids length must be between 1 and {_MAX_BATCH_GET_SIZE}")
623
743
  for doc_id in id_list:
624
744
  self._esc_doc_id(doc_id)
625
745
  path = "/v1/docs/batch-get" if esc_tenant == "" else f"/v1/tenants/{esc_tenant}/docs/batch-get"
@@ -639,12 +759,18 @@ class MassEngineClient:
639
759
  docs: Iterable[Union[Doc, Dict[str, Any]]],
640
760
  *,
641
761
  database: str = "",
762
+ batch_size: int = 0,
642
763
  ) -> int:
643
764
  """Streams a collection of documents into `tenant` via NDJSON."""
644
765
  esc_tenant = self._validate_optional_tenant(tenant)
766
+ if isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size < 0 or batch_size > 4096:
767
+ raise ValueError("batch_size must be between 1 and 4096")
645
768
  base_path = "/v1/import" if esc_tenant == "" else f"/v1/tenants/{esc_tenant}/import"
646
769
  path = self._append_db_query(base_path, database)
647
- lines = [json.dumps(self._serialize_doc(d)) for d in docs]
770
+ if batch_size > 0:
771
+ sep = "&" if "?" in path else "?"
772
+ path = f"{path}{sep}batch_size={batch_size}"
773
+ lines = [json.dumps(self._serialize_doc(d), allow_nan=False) for d in docs]
648
774
  payload = ("\n".join(lines) + "\n").encode("utf-8")
649
775
  req = urllib.request.Request(
650
776
  url=f"{self.base_url}{path}",
@@ -727,20 +853,34 @@ class MassEngineClient:
727
853
  rf: int = 0,
728
854
  data_type: str = "",
729
855
  mode: str = "",
856
+ ttl_days: int = 0,
857
+ time_bucket_days: int = 0,
858
+ append_only: bool = False,
730
859
  ) -> Dict[str, Any]:
731
860
  """Creates or updates a named database under `tenant` (or the bound `mk_...` key's tenant)."""
732
861
  esc_tenant = self._validate_optional_tenant(tenant)
733
862
  self._esc_database(database)
863
+ ns_val = _check_int(num_shards, "num_shards", 0)
864
+ rf_val = _check_int(rf, "rf", 0)
865
+ ttl_val = _check_int(ttl_days, "ttl_days", 0, 65535)
866
+ tb_val = _check_int(time_bucket_days, "time_bucket_days", 0, 3650)
867
+ ao_val = _check_bool(append_only, "append_only")
734
868
  path = "/v1/databases" if esc_tenant == "" else f"/v1/tenants/{esc_tenant}/databases"
735
869
  body: Dict[str, Any] = {"database": database}
736
- if num_shards > 0:
737
- body["num_shards"] = int(num_shards)
738
- if rf > 0:
739
- body["rf"] = int(rf)
870
+ if ns_val > 0:
871
+ body["num_shards"] = ns_val
872
+ if rf_val > 0:
873
+ body["rf"] = rf_val
740
874
  if data_type:
741
875
  body["data_type"] = data_type
742
876
  if mode:
743
877
  body["mode"] = mode
878
+ if ttl_val > 0:
879
+ body["ttl_days"] = ttl_val
880
+ if tb_val > 0:
881
+ body["time_bucket_days"] = tb_val
882
+ if ao_val:
883
+ body["append_only"] = True
744
884
  resp = self._request_json("POST", path, body)
745
885
  if isinstance(resp, dict) and isinstance(resp.get("database"), dict):
746
886
  db_obj = dict(resp["database"])
@@ -784,6 +924,10 @@ class MassEngineClient:
784
924
 
785
925
  def create_tenant_key(self, tenant: str, key: str = "") -> str:
786
926
  """Creates or registers a tenant-scoped RBAC API key (requires admin key)."""
927
+ if key != "":
928
+ validated = self._validate_api_key(key)
929
+ if validated != key:
930
+ raise ValueError("custom API key must not contain leading or trailing whitespace")
787
931
  resp = self._request_json(
788
932
  "POST",
789
933
  f"/v1/tenants/{self._esc_tenant(tenant)}/keys",
@@ -793,6 +937,9 @@ class MassEngineClient:
793
937
 
794
938
  def revoke_tenant_key(self, tenant: str, key: str) -> Dict[str, Any]:
795
939
  """Revokes a tenant-scoped RBAC API key (requires admin key)."""
940
+ validated = self._validate_api_key(key)
941
+ if not validated or validated != key:
942
+ raise ValueError("valid non-empty API key is required for revocation")
796
943
  return self._request_json(
797
944
  "DELETE",
798
945
  f"/v1/tenants/{self._esc_tenant(tenant)}/keys",
@@ -805,7 +952,25 @@ class MassEngineClient:
805
952
  quota: Union[TenantQuota, Dict[str, Any]],
806
953
  ) -> Dict[str, Any]:
807
954
  """Sets a tenant's plan tier, max_docs/max_bytes caps, max_qps limit, and suspension status."""
808
- q_dict = quota.to_dict() if isinstance(quota, TenantQuota) else quota
955
+ if isinstance(quota, TenantQuota):
956
+ q_dict = quota.to_dict()
957
+ elif isinstance(quota, dict):
958
+ q_dict = dict(quota)
959
+ if q_dict.get("max_docs") is not None:
960
+ q_dict["max_docs"] = _check_int(q_dict["max_docs"], "max_docs", 0, 0xFFFFFFFFFFFFFFFF)
961
+ if q_dict.get("max_bytes") is not None:
962
+ q_dict["max_bytes"] = _check_int(q_dict["max_bytes"], "max_bytes", 0, 0xFFFFFFFFFFFFFFFF)
963
+ if q_dict.get("burst") is not None:
964
+ q_dict["burst"] = _check_int(q_dict["burst"], "burst", 0, 0xFFFFFFFFFFFFFFFF)
965
+ if q_dict.get("max_qps") is not None:
966
+ qps = q_dict["max_qps"]
967
+ if isinstance(qps, bool) or not isinstance(qps, (int, float)) or not math.isfinite(float(qps)) or float(qps) < 0:
968
+ raise ValueError("max_qps must be a finite non-negative number")
969
+ q_dict["max_qps"] = float(qps)
970
+ if "suspended" in q_dict and q_dict["suspended"] is not None:
971
+ q_dict["suspended"] = _check_bool(q_dict["suspended"], "suspended")
972
+ else:
973
+ raise ValueError("quota must be a TenantQuota or dict")
809
974
  resp = self._request_json(
810
975
  "PUT",
811
976
  f"/v1/tenants/{self._esc_tenant(tenant)}/quota",
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["hatchling>=1.25"]
2
+ requires = ["hatchling==1.27.0"]
3
3
  build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "massengine"
7
- version = "1.2.0"
7
+ version = "1.2.3"
8
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"
@@ -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
- time.sleep(0.15)
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.2.0")
281
+ self.assertEqual(massengine.__version__, "1.2.3")
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.2.0")
284
+ self.assertEqual(_MockGatewayHandler.last_user_agent, "massengine-python/1.2.3")
261
285
  r_ok = admin.ready()
262
286
  self.assertTrue(r_ok["ready"])
263
287
  self.assertEqual(r_ok["unavailable_shards"], [])
@@ -523,12 +547,19 @@ class TestMassEngineClient(unittest.TestCase):
523
547
  self.assertEqual(dbs[0]["database"], "analytics")
524
548
 
525
549
  _MockGatewayHandler.get_db_405 = False
550
+ before_direct = len(_MockGatewayHandler.recorded_paths)
526
551
  got_db = client.get_database(tenant, "analytics")
527
552
  self.assertEqual(got_db["database"], "analytics")
553
+ self.assertEqual(len(_MockGatewayHandler.recorded_paths) - before_direct, 1)
528
554
 
529
555
  _MockGatewayHandler.get_db_405 = True
556
+ before_fb = len(_MockGatewayHandler.recorded_paths)
530
557
  got_fb = client.get_database(tenant, "analytics")
531
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)
532
563
 
533
564
  deleted = client.delete_database(tenant, "analytics")
534
565
  self.assertEqual(deleted, 2)
@@ -608,10 +639,164 @@ class TestMassEngineClient(unittest.TestCase):
608
639
  tiny_export_client.export_tenant("acme")
609
640
  self.assertIn("max_response_bytes", str(ctx2.exception))
610
641
 
611
- fast_client = MassEngineClient(base_url=self.base_url, timeout=0.03)
642
+ fast_client = MassEngineClient(base_url=self.base_url, timeout=0.02)
612
643
  with self.assertRaises((TimeoutError, socket.timeout, OSError)):
613
644
  fast_client.flush()
614
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.3")
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
+
748
+ # Security & parity audit v1.2.2 checks
749
+ for bad_url in [
750
+ "http://localhost:8080?",
751
+ "http://localhost:8080#",
752
+ "http://localhost:8080\\bad",
753
+ "http://:8080",
754
+ "http://localhost:8080/v1/../admin",
755
+ ]:
756
+ with self.assertRaises(ValueError, msg=f"base_url={bad_url}"):
757
+ MassEngineClient(base_url=bad_url)
758
+
759
+ with self.assertRaises(ValueError):
760
+ client.create_database("acme", "d", ttl_days=70000)
761
+ with self.assertRaises(ValueError):
762
+ client.create_database("acme", "d", ttl_days=-5)
763
+ with self.assertRaises(ValueError):
764
+ client.create_database("acme", "d", ttl_days=True) # type: ignore[arg-type]
765
+ with self.assertRaises(ValueError):
766
+ client.create_database("acme", "d", time_bucket_days=3651)
767
+ with self.assertRaises(ValueError):
768
+ client.create_database("acme", "d", append_only="false") # type: ignore[arg-type]
769
+ with self.assertRaises(ValueError):
770
+ client.ingest("acme", [])
771
+ with self.assertRaises(ValueError):
772
+ client.ingest("acme", [{"id": "no-vec"}])
773
+ with self.assertRaises(ValueError):
774
+ Doc(doc_id=1 << 44, vector=[1.0, 0.0]).to_dict()
775
+ with self.assertRaises(ValueError):
776
+ Doc(id="x", vector=[1e20, 0.0]).to_dict()
777
+ with self.assertRaises(ValueError):
778
+ Doc(id="x", vector=[1.0, 0.0], date=True).to_dict() # type: ignore[arg-type]
779
+ with self.assertRaises(ValueError):
780
+ SearchRequest(vector=[1.0, 0.0], k=0).to_dict()
781
+ with self.assertRaises(ValueError):
782
+ SearchRequest(vector=[1.0, 0.0], k=1001).to_dict()
783
+ with self.assertRaises(ValueError):
784
+ SearchRequest(vector=[1.0, 0.0], offset=-1).to_dict()
785
+ with self.assertRaises(ValueError):
786
+ SearchRequest(vector=[1.0, 0.0], categories="12").to_dict() # type: ignore[arg-type]
787
+ with self.assertRaises(ValueError):
788
+ client.batch_search([{"vector": [1.0, 0.0], "k": True}]) # type: ignore[list-item]
789
+ with self.assertRaises(ValueError):
790
+ client.patch_doc("acme", "x", category=True) # type: ignore[arg-type]
791
+ with self.assertRaises(ValueError):
792
+ client.batch_get_docs("acme", [])
793
+ with self.assertRaises(ValueError):
794
+ client.set_tenant_quota("acme", {"max_qps": -1})
795
+ with self.assertRaises(ValueError):
796
+ client.create_tenant_key("acme", " mk_bad")
797
+ with self.assertRaises(ValueError):
798
+ client.revoke_tenant_key("acme", "")
799
+
615
800
 
616
801
  if __name__ == "__main__":
617
802
  unittest.main()
File without changes
File without changes