cembedding 0.8.0__tar.gz → 0.9.0__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.
Files changed (41) hide show
  1. {cembedding-0.8.0 → cembedding-0.9.0}/PKG-INFO +35 -4
  2. {cembedding-0.8.0 → cembedding-0.9.0}/README.md +34 -3
  3. {cembedding-0.8.0 → cembedding-0.9.0}/cembedding/__init__.py +1 -1
  4. {cembedding-0.8.0 → cembedding-0.9.0}/cembedding/server.py +216 -0
  5. cembedding-0.9.0/cloto-connector.json +143 -0
  6. cembedding-0.9.0/tests/test_capabilities.py +367 -0
  7. cembedding-0.8.0/cloto-connector.json +0 -143
  8. {cembedding-0.8.0 → cembedding-0.9.0}/.dockerignore +0 -0
  9. {cembedding-0.8.0 → cembedding-0.9.0}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
  10. {cembedding-0.8.0 → cembedding-0.9.0}/.github/ISSUE_TEMPLATE/config.yml +0 -0
  11. {cembedding-0.8.0 → cembedding-0.9.0}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
  12. {cembedding-0.8.0 → cembedding-0.9.0}/.github/workflows/ci.yml +0 -0
  13. {cembedding-0.8.0 → cembedding-0.9.0}/.github/workflows/publish.yml +0 -0
  14. {cembedding-0.8.0 → cembedding-0.9.0}/.gitignore +0 -0
  15. {cembedding-0.8.0 → cembedding-0.9.0}/Dockerfile +0 -0
  16. {cembedding-0.8.0 → cembedding-0.9.0}/LICENSE +0 -0
  17. {cembedding-0.8.0 → cembedding-0.9.0}/cembedding/__main__.py +0 -0
  18. {cembedding-0.8.0 → cembedding-0.9.0}/cembedding/_vendored_mcp_common/__init__.py +0 -0
  19. {cembedding-0.8.0 → cembedding-0.9.0}/cembedding/_vendored_mcp_common/mcp_utils.py +0 -0
  20. {cembedding-0.8.0 → cembedding-0.9.0}/cembedding/_vendored_mcp_common/validation.py +0 -0
  21. {cembedding-0.8.0 → cembedding-0.9.0}/cembedding/auth.py +0 -0
  22. {cembedding-0.8.0 → cembedding-0.9.0}/cembedding/download_model.py +0 -0
  23. {cembedding-0.8.0 → cembedding-0.9.0}/cembedding/sidecar.py +0 -0
  24. {cembedding-0.8.0 → cembedding-0.9.0}/conftest.py +0 -0
  25. {cembedding-0.8.0 → cembedding-0.9.0}/docs/CONTIGUOUS_SIDECAR_DESIGN.md +0 -0
  26. {cembedding-0.8.0 → cembedding-0.9.0}/pyproject.toml +0 -0
  27. {cembedding-0.8.0 → cembedding-0.9.0}/scripts/backfill_embedding_index.py +0 -0
  28. {cembedding-0.8.0 → cembedding-0.9.0}/scripts/bench_sidecar_startup.py +0 -0
  29. {cembedding-0.8.0 → cembedding-0.9.0}/server.py +0 -0
  30. {cembedding-0.8.0 → cembedding-0.9.0}/skills/cembedding/SKILL.md +0 -0
  31. {cembedding-0.8.0 → cembedding-0.9.0}/tests/test_auth.py +0 -0
  32. {cembedding-0.8.0 → cembedding-0.9.0}/tests/test_backfill.py +0 -0
  33. {cembedding-0.8.0 → cembedding-0.9.0}/tests/test_batch_coalescing.py +0 -0
  34. {cembedding-0.8.0 → cembedding-0.9.0}/tests/test_http_bind.py +0 -0
  35. {cembedding-0.8.0 → cembedding-0.9.0}/tests/test_model_variants.py +0 -0
  36. {cembedding-0.8.0 → cembedding-0.9.0}/tests/test_onnx_padding.py +0 -0
  37. {cembedding-0.8.0 → cembedding-0.9.0}/tests/test_ort_session_options.py +0 -0
  38. {cembedding-0.8.0 → cembedding-0.9.0}/tests/test_sidecar.py +0 -0
  39. {cembedding-0.8.0 → cembedding-0.9.0}/tests/test_token_info.py +0 -0
  40. {cembedding-0.8.0 → cembedding-0.9.0}/tests/test_vector_index.py +0 -0
  41. {cembedding-0.8.0 → cembedding-0.9.0}/tests/test_version_surface.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cembedding
3
- Version: 0.8.0
3
+ Version: 0.9.0
4
4
  Summary: Local-first embedding server: vector generation + index/search over HTTP (ONNX on-device or API providers). The reference /embed server for CPersona.
5
5
  Project-URL: Homepage, https://github.com/Cloto-dev/CEmbedding
6
6
  Project-URL: Repository, https://github.com/Cloto-dev/CEmbedding
@@ -51,6 +51,7 @@ Description-Content-Type: text/markdown
51
51
 
52
52
  Vector embeddings over a tiny HTTP contract.
53
53
  On-device ONNX or any OpenAI-compatible API. The reference `/embed` server for [CPersona](https://github.com/Cloto-dev/CPersona).
54
+ Also available as the CEmbedding MCP embedding server (stdio and Streamable HTTP).
54
55
 
55
56
  [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/Cloto-dev/CEmbedding/blob/main/LICENSE)
56
57
  [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)]()
@@ -97,6 +98,36 @@ Response entry: { "count": <int>, "window": <int>, "truncated": <bool>, "wi
97
98
  - The counting tokenizer loads on the first request that needs it (about 29 MiB resident
98
99
  for jina-v5-nano), so a server that is never asked pays nothing.
99
100
 
101
+ ### Which backend produced a vector
102
+
103
+ A caller stores vectors and comes back later to ask whether a stored one may still be
104
+ compared with a fresh one. Over `/embed` it cannot tell: it posts texts and the server
105
+ picks the model, so a client that falls back to a configured default reads two different
106
+ models as one. `/capabilities` answers what actually ran.
107
+
108
+ ```
109
+ GET /capabilities
110
+ Response: { "identity": { "provider": ..., "model": ..., "dimensions": <int>,
111
+ "window": <int>, "pooling": ..., "normalized": <bool>,
112
+ "digests": { "graph": ..., "tokenizer": ..., "weights": ... } },
113
+ "incomplete": [ ... ],
114
+ "fingerprint": "1:<hex>" | null }
115
+ ```
116
+
117
+ - `fingerprint` is the one value to store beside a vector. Two vectors may be compared
118
+ when their fingerprints are equal.
119
+ - It covers everything that moves the numbers: the graph and tokenizer contents, the
120
+ width, the truncation window, the pooling, and the provider. Two precisions of one
121
+ model fingerprint differently; a configured model name cannot tell them apart.
122
+ - `incomplete` names the components this deployment could not establish, and `fingerprint`
123
+ is then `null` — never a shorter fingerprint over the part it knew. A remote API
124
+ (`api_openai`) and the MLX provider report at least their digests as missing, because
125
+ the files that would be hashed are not this process's to read.
126
+ - **`null` means unknown, not unchanged.** A caller that receives it keeps whatever it
127
+ did before this endpoint existed; it must not read a matching default as a matching model.
128
+ - The digest of a model graph is computed once per file state and cached, so the first
129
+ call after a restart pays for reading it and later calls do not.
130
+
100
131
  Point any client (e.g. CPersona's `CPERSONA_EMBEDDING_URL` / generic `EMBEDDING_HTTP_URL`) at `http://127.0.0.1:8401/embed`.
101
132
 
102
133
  ## Quick Start (on-device ONNX)
@@ -250,9 +281,9 @@ cembedding-sidecar build --db data/embedding_index.db # write one now
250
281
 
251
282
  ## Authentication (v0.6.2)
252
283
 
253
- Both HTTP surfaces — the REST endpoints (`/embed`, `/count_tokens`, `/index`, `/search`,
254
- `/remove`, `/purge`) and the Streamable HTTP MCP transport — accept an inbound
255
- bearer token:
284
+ Both HTTP surfaces — the REST endpoints (`/embed`, `/count_tokens`, `/capabilities`,
285
+ `/index`, `/search`, `/remove`, `/purge`) and the Streamable HTTP MCP transport — accept
286
+ an inbound bearer token:
256
287
 
257
288
  ```bash
258
289
  CEMBEDDING_AUTH_TOKEN=$(openssl rand -hex 32)
@@ -6,6 +6,7 @@
6
6
 
7
7
  Vector embeddings over a tiny HTTP contract.
8
8
  On-device ONNX or any OpenAI-compatible API. The reference `/embed` server for [CPersona](https://github.com/Cloto-dev/CPersona).
9
+ Also available as the CEmbedding MCP embedding server (stdio and Streamable HTTP).
9
10
 
10
11
  [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/Cloto-dev/CEmbedding/blob/main/LICENSE)
11
12
  [![Python](https://img.shields.io/badge/python-3.10+-blue.svg)]()
@@ -52,6 +53,36 @@ Response entry: { "count": <int>, "window": <int>, "truncated": <bool>, "wi
52
53
  - The counting tokenizer loads on the first request that needs it (about 29 MiB resident
53
54
  for jina-v5-nano), so a server that is never asked pays nothing.
54
55
 
56
+ ### Which backend produced a vector
57
+
58
+ A caller stores vectors and comes back later to ask whether a stored one may still be
59
+ compared with a fresh one. Over `/embed` it cannot tell: it posts texts and the server
60
+ picks the model, so a client that falls back to a configured default reads two different
61
+ models as one. `/capabilities` answers what actually ran.
62
+
63
+ ```
64
+ GET /capabilities
65
+ Response: { "identity": { "provider": ..., "model": ..., "dimensions": <int>,
66
+ "window": <int>, "pooling": ..., "normalized": <bool>,
67
+ "digests": { "graph": ..., "tokenizer": ..., "weights": ... } },
68
+ "incomplete": [ ... ],
69
+ "fingerprint": "1:<hex>" | null }
70
+ ```
71
+
72
+ - `fingerprint` is the one value to store beside a vector. Two vectors may be compared
73
+ when their fingerprints are equal.
74
+ - It covers everything that moves the numbers: the graph and tokenizer contents, the
75
+ width, the truncation window, the pooling, and the provider. Two precisions of one
76
+ model fingerprint differently; a configured model name cannot tell them apart.
77
+ - `incomplete` names the components this deployment could not establish, and `fingerprint`
78
+ is then `null` — never a shorter fingerprint over the part it knew. A remote API
79
+ (`api_openai`) and the MLX provider report at least their digests as missing, because
80
+ the files that would be hashed are not this process's to read.
81
+ - **`null` means unknown, not unchanged.** A caller that receives it keeps whatever it
82
+ did before this endpoint existed; it must not read a matching default as a matching model.
83
+ - The digest of a model graph is computed once per file state and cached, so the first
84
+ call after a restart pays for reading it and later calls do not.
85
+
55
86
  Point any client (e.g. CPersona's `CPERSONA_EMBEDDING_URL` / generic `EMBEDDING_HTTP_URL`) at `http://127.0.0.1:8401/embed`.
56
87
 
57
88
  ## Quick Start (on-device ONNX)
@@ -205,9 +236,9 @@ cembedding-sidecar build --db data/embedding_index.db # write one now
205
236
 
206
237
  ## Authentication (v0.6.2)
207
238
 
208
- Both HTTP surfaces — the REST endpoints (`/embed`, `/count_tokens`, `/index`, `/search`,
209
- `/remove`, `/purge`) and the Streamable HTTP MCP transport — accept an inbound
210
- bearer token:
239
+ Both HTTP surfaces — the REST endpoints (`/embed`, `/count_tokens`, `/capabilities`,
240
+ `/index`, `/search`, `/remove`, `/purge`) and the Streamable HTTP MCP transport — accept
241
+ an inbound bearer token:
211
242
 
212
243
  ```bash
213
244
  CEMBEDDING_AUTH_TOKEN=$(openssl rand -hex 32)
@@ -1,3 +1,3 @@
1
1
  """CEmbedding — local-first embedding server (the reference /embed server for CPersona)."""
2
2
 
3
- __version__ = "0.8.0"
3
+ __version__ = "0.9.0"
@@ -9,6 +9,8 @@ Design: docs/CPERSONA_MEMORY_DESIGN.md Section 5
9
9
  """
10
10
 
11
11
  import asyncio
12
+ import hashlib
13
+ import json
12
14
  import logging
13
15
  import os
14
16
  import platform as _platform
@@ -330,6 +332,9 @@ class _TokenCounter:
330
332
 
331
333
  @property
332
334
  def window(self) -> int:
335
+ """Where the embedding path truncates — and so part of the backend's
336
+ identity: two deployments differing only here return different vectors
337
+ for any text long enough to reach it."""
333
338
  return self._window
334
339
 
335
340
  def count(self, texts: list[str]) -> list[dict]:
@@ -358,6 +363,126 @@ class _TokenCounter:
358
363
  return out
359
364
 
360
365
 
366
+ # ============================================================
367
+ # Backend identity
368
+ # ============================================================
369
+
370
+ #: The fields an identity must carry before a caller may compare two sets of
371
+ #: stored vectors. Every one of them changes the numbers, so a set missing any
372
+ #: is not reduced to a fingerprint: a server answering with the half it knew
373
+ #: would compare equal to a server running something else.
374
+ IDENTITY_FIELDS = ("provider", "model", "dimensions", "window", "pooling", "normalized")
375
+
376
+ #: The files an identity must digest. A model whose graph carries its own
377
+ #: weights has no third entry, so "weights" is reported when present and not
378
+ #: required here.
379
+ IDENTITY_DIGESTS = ("graph", "tokenizer")
380
+
381
+ #: sha256 by (path, size, mtime), so a model replaced in place is re-read. Kept
382
+ #: for the life of the process: the graph of a mid-size model is hundreds of
383
+ #: megabytes and its digest is asked for on every caller's startup.
384
+ _DIGEST_CACHE: dict[tuple[str, int, int], str] = {}
385
+ _DIGEST_LOCK = asyncio.Lock()
386
+
387
+
388
+ def _digest_file(path: str) -> str:
389
+ h = hashlib.sha256()
390
+ with open(path, "rb") as f:
391
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
392
+ h.update(chunk)
393
+ return h.hexdigest()
394
+
395
+
396
+ async def _file_digest(path: str) -> str | None:
397
+ """sha256 of one file, computed once and off the event loop.
398
+
399
+ None when the file cannot be read. That is a missing component, not an empty
400
+ one: :func:`backend_identity` turns it into a refusal to fingerprint.
401
+ """
402
+ try:
403
+ st = os.stat(path)
404
+ except OSError:
405
+ return None
406
+ key = (os.path.abspath(path), st.st_size, st.st_mtime_ns)
407
+ cached = _DIGEST_CACHE.get(key)
408
+ if cached is not None:
409
+ return cached
410
+ async with _DIGEST_LOCK:
411
+ # Re-read under the lock so two callers arriving together hash once.
412
+ cached = _DIGEST_CACHE.get(key)
413
+ if cached is not None:
414
+ return cached
415
+ try:
416
+ digest = await asyncio.get_running_loop().run_in_executor(None, _digest_file, path)
417
+ except OSError:
418
+ return None
419
+ _DIGEST_CACHE[key] = digest
420
+ return digest
421
+
422
+
423
+ def _onnx_identity(provider: "EmbeddingProvider", model: str, *, pooling: str) -> dict:
424
+ """The identity the local ONNX providers share.
425
+
426
+ ``pooling`` is named here and performed in the provider's ``_embed_sync`` a
427
+ few lines away. The two are deliberately separate statements of one fact:
428
+ changing how token states are reduced without changing this string would
429
+ leave the fingerprint equal across vectors that are not, so a test pins each
430
+ provider's declared pooling and a change has to be made in both places.
431
+ """
432
+ counter = provider.token_counter()
433
+ identity = {
434
+ "model": model,
435
+ "dimensions": provider.dimensions(),
436
+ "pooling": pooling,
437
+ "normalized": True,
438
+ }
439
+ if counter is not None:
440
+ identity["window"] = counter.window
441
+ return identity
442
+
443
+
444
+ def _fingerprint(fields: Mapping) -> str:
445
+ """One token standing for a whole identity, equal across processes.
446
+
447
+ Serialised with sorted keys so two servers that agree on the facts agree on
448
+ the string, and carrying a scheme number so a later change to what an
449
+ identity contains cannot be mistaken for the same value computed differently.
450
+ """
451
+ body = json.dumps(fields, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
452
+ return "1:" + hashlib.sha256(body.encode("utf-8")).hexdigest()
453
+
454
+
455
+ async def backend_identity(provider: "EmbeddingProvider") -> dict:
456
+ """What produced this server's vectors, and the token standing for it.
457
+
458
+ ``fingerprint`` is what a caller stores beside a vector to decide later
459
+ whether a new vector may be compared with it. It is present only when every
460
+ field and digest is present; otherwise it is null and ``incomplete`` names
461
+ what is missing. A caller that receives null keeps whatever it did before
462
+ this endpoint existed and must not read "unknown" as "unchanged" — a default
463
+ that happens to match is not evidence that the model did.
464
+ """
465
+ fields = {k: v for k, v in provider.identity().items() if v is not None}
466
+ fields["provider"] = EMBEDDING_PROVIDER
467
+
468
+ digests: dict[str, str] = {}
469
+ for label, path in sorted(provider.identity_files().items()):
470
+ digest = await _file_digest(path)
471
+ if digest is not None:
472
+ digests[label] = digest
473
+ if digests:
474
+ fields["digests"] = digests
475
+
476
+ incomplete = [f for f in IDENTITY_FIELDS if f not in fields]
477
+ incomplete += [f"digests.{label}" for label in IDENTITY_DIGESTS if label not in digests]
478
+
479
+ return {
480
+ "identity": fields,
481
+ "incomplete": incomplete,
482
+ "fingerprint": None if incomplete else _fingerprint(fields),
483
+ }
484
+
485
+
361
486
  class EmbeddingProvider(ABC):
362
487
  """Abstract base class for embedding providers."""
363
488
 
@@ -382,6 +507,34 @@ class EmbeddingProvider(ABC):
382
507
  """
383
508
  return getattr(self, "_counter", None)
384
509
 
510
+ def identity(self) -> dict:
511
+ """What this backend is, in the terms that decide whether two sets of
512
+ stored vectors may be compared.
513
+
514
+ Every field here changes the numbers: the graph, the tokenizer, the
515
+ width, the truncation point, and the way token states are reduced to one
516
+ vector. A provider reports only what it can establish from what it
517
+ actually loaded. A field it cannot establish is left out, and
518
+ :func:`backend_identity` then declines to fingerprint at all rather than
519
+ fingerprinting the half it knows — a partial identity that compares equal
520
+ is the failure this endpoint exists to prevent.
521
+ """
522
+ return {}
523
+
524
+ def identity_files(self) -> dict[str, str]:
525
+ """Label -> path for the files whose contents define this backend.
526
+
527
+ A provider names every file it loaded, not just the entry point. Weights
528
+ held in ONNX external-data format live beside the graph, so hashing the
529
+ ``.onnx`` alone would give one digest to two different sets of weights.
530
+
531
+ The paths come from ``_loaded_files``, which a provider fills at the
532
+ moment it opens them. Recomputing them here from configuration would
533
+ report the file the settings name rather than the file in the session,
534
+ and those differ after any download, fallback or clamp.
535
+ """
536
+ return dict(getattr(self, "_loaded_files", None) or {})
537
+
385
538
  async def shutdown(self) -> None:
386
539
  """Clean up resources."""
387
540
 
@@ -447,6 +600,16 @@ class OpenAIEmbeddingProvider(EmbeddingProvider):
447
600
  def dimensions(self) -> int:
448
601
  return self._dimensions
449
602
 
603
+ def identity(self) -> dict:
604
+ """The model name this process sends, and the width it last saw back.
605
+
606
+ No digest, no window and no pooling: the graph and the tokenizer are on
607
+ the other side of the network, and the name is what the operator asked
608
+ for rather than what answered. That gap is why this provider never
609
+ completes an identity — see :func:`backend_identity`.
610
+ """
611
+ return {"model": self._model, "dimensions": self._dimensions, "normalized": True}
612
+
450
613
  async def shutdown(self) -> None:
451
614
  if self._client:
452
615
  await self._client.aclose()
@@ -511,6 +674,7 @@ class OnnxMiniLMProvider(EmbeddingProvider):
511
674
  self._tokenizer.enable_padding(pad_id=0, pad_token="[PAD]")
512
675
  self._tokenizer.enable_truncation(max_length=miniml_seq_len)
513
676
  self._counter = _TokenCounter.from_file(tokenizer_path, miniml_seq_len)
677
+ self._loaded_files = {"graph": model_path, "tokenizer": tokenizer_path}
514
678
 
515
679
  logger.info(
516
680
  "ONNX MiniLM provider initialized (dir=%s, seq_len=%d, requested=%s, active=%s)",
@@ -559,6 +723,9 @@ class OnnxMiniLMProvider(EmbeddingProvider):
559
723
  def dimensions(self) -> int:
560
724
  return 384
561
725
 
726
+ def identity(self) -> dict:
727
+ return _onnx_identity(self, "all-MiniLM-L6-v2", pooling="mean")
728
+
562
729
  async def shutdown(self) -> None:
563
730
  self._session = None
564
731
  self._tokenizer = None
@@ -701,6 +868,23 @@ class MlxBgeM3Provider(EmbeddingProvider):
701
868
  def dimensions(self) -> int:
702
869
  return 1024
703
870
 
871
+ def identity(self) -> dict:
872
+ """Everything but the files.
873
+
874
+ ``mlx_load`` takes a repository id as readily as a directory and resolves
875
+ it through a cache this process does not own, so there is no path here
876
+ that is certainly the one that was read. Reporting the configured string
877
+ as if it were a digest would be the mistake this endpoint exists to stop,
878
+ so the file half is simply absent and the identity stays incomplete.
879
+ """
880
+ return {
881
+ "model": self._model_path,
882
+ "dimensions": self.dimensions(),
883
+ "window": min(ONNX_MAX_SEQ_LEN, 8192),
884
+ "pooling": "model",
885
+ "normalized": True,
886
+ }
887
+
704
888
  async def shutdown(self) -> None:
705
889
  self._model = None
706
890
  self._tokenizer = None
@@ -758,6 +942,7 @@ class OnnxBgeM3Provider(EmbeddingProvider):
758
942
  self._tokenizer.enable_padding(pad_id=1, pad_token="<pad>")
759
943
  self._tokenizer.enable_truncation(max_length=bge_seq_len)
760
944
  self._counter = _TokenCounter.from_file(tokenizer_path, bge_seq_len)
945
+ self._loaded_files = {"graph": model_path, "tokenizer": tokenizer_path}
761
946
 
762
947
  logger.info(
763
948
  "ONNX BGE-M3 provider initialized (dir=%s, seq_len=%d, requested=%s, active=%s)",
@@ -801,6 +986,9 @@ class OnnxBgeM3Provider(EmbeddingProvider):
801
986
  def dimensions(self) -> int:
802
987
  return 1024
803
988
 
989
+ def identity(self) -> dict:
990
+ return _onnx_identity(self, "bge-m3", pooling="cls")
991
+
804
992
  async def shutdown(self) -> None:
805
993
  self._session = None
806
994
  self._tokenizer = None
@@ -862,6 +1050,13 @@ class OnnxJinaV5NanoProvider(EmbeddingProvider):
862
1050
  self._tokenizer.enable_padding(pad_id=0, pad_token="<pad>")
863
1051
  self._tokenizer.enable_truncation(max_length=ONNX_MAX_SEQ_LEN)
864
1052
  self._counter = _TokenCounter.from_file(tokenizer_path, ONNX_MAX_SEQ_LEN)
1053
+ # The graph here is a stub that names its weights in a sibling file, so
1054
+ # both are listed: two precisions of this model have nearly identical
1055
+ # .onnx files and entirely different .onnx_data ones.
1056
+ self._loaded_files = {"graph": model_path, "tokenizer": tokenizer_path}
1057
+ external_data = f"{model_path}_data"
1058
+ if os.path.exists(external_data):
1059
+ self._loaded_files["weights"] = external_data
865
1060
 
866
1061
  logger.info(
867
1062
  "ONNX Jina-v5-nano provider initialized (dir=%s, variant=%s, seq_len=%d, requested=%s, active=%s)",
@@ -912,6 +1107,9 @@ class OnnxJinaV5NanoProvider(EmbeddingProvider):
912
1107
  def dimensions(self) -> int:
913
1108
  return 768
914
1109
 
1110
+ def identity(self) -> dict:
1111
+ return _onnx_identity(self, "jina-embeddings-v5-text-nano-retrieval", pooling="last_token")
1112
+
915
1113
  async def shutdown(self) -> None:
916
1114
  self._session = None
917
1115
  self._tokenizer = None
@@ -1751,6 +1949,23 @@ async def handle_count_tokens(request: web.Request) -> web.Response:
1751
1949
  return web.json_response({"error": f"Token counting failed: {e}"}, status=500)
1752
1950
 
1753
1951
 
1952
+ async def handle_capabilities(request: web.Request) -> web.Response:
1953
+ """GET /capabilities — what this backend is, and the fingerprint standing for it.
1954
+
1955
+ Its own route rather than a field on ``/embed``: the answer is the same for
1956
+ every request and costs a digest of the model the first time, while /embed is
1957
+ on the path of every write a caller makes.
1958
+ """
1959
+ if _provider is None:
1960
+ return web.json_response({"error": "Provider not initialized"}, status=503)
1961
+
1962
+ try:
1963
+ return web.json_response(await backend_identity(_provider))
1964
+ except Exception as e:
1965
+ logger.exception("Capability report failed")
1966
+ return web.json_response({"error": f"Capability report failed: {e}"}, status=500)
1967
+
1968
+
1754
1969
  async def handle_index(request: web.Request) -> web.Response:
1755
1970
  """POST /index — Index vectors for later search."""
1756
1971
  if _provider is None or _vector_index is None:
@@ -1857,6 +2072,7 @@ def build_http_app(auth_token: str | None) -> web.Application:
1857
2072
  app = web.Application(middlewares=middlewares)
1858
2073
  app.router.add_post("/embed", handle_embed)
1859
2074
  app.router.add_post("/count_tokens", handle_count_tokens)
2075
+ app.router.add_get("/capabilities", handle_capabilities)
1860
2076
  if EMBEDDING_INDEX_ENABLED and _vector_index is not None:
1861
2077
  app.router.add_post("/index", handle_index)
1862
2078
  app.router.add_post("/search", handle_search)
@@ -0,0 +1,143 @@
1
+ {
2
+ "spec_version": 1,
3
+ "connector_type": "mgp_server",
4
+ "id": "cembedding",
5
+ "name": "CEmbedding",
6
+ "description": "Local-first embedding server: vector generation + index/search over HTTP (ONNX on-device or API providers). The reference /embed and remote /search server for CPersona.",
7
+ "version": "0.9.0",
8
+ "category": "tool",
9
+ "trust_level": "core",
10
+ "magic_seal": "sha256:f75b48b630e7b1cf539577121ffddede7e35a72aadc92733d064359145ff5e64",
11
+ "install": {
12
+ "source": {
13
+ "type": "git",
14
+ "url": "https://github.com/Cloto-dev/CEmbedding",
15
+ "reference": "",
16
+ "subdir": null
17
+ },
18
+ "package_manager": "uv",
19
+ "runtime": "python",
20
+ "directory": "",
21
+ "dependencies": [],
22
+ "bin_name": null
23
+ },
24
+ "icon": "layers",
25
+ "tags": [
26
+ "embedding",
27
+ "vector",
28
+ "search",
29
+ "onnx"
30
+ ],
31
+ "host_compatibility": [
32
+ "clotocore",
33
+ "claude-code",
34
+ "claude-desktop",
35
+ "cursor",
36
+ "project-airi"
37
+ ],
38
+ "env_vars": [],
39
+ "optional_env_vars": [
40
+ {
41
+ "name": "EMBEDDING_PROVIDER",
42
+ "default": "api_openai",
43
+ "description": "Embedding provider: api_openai | onnx_miniml | onnx_jina_v5_nano | onnx_bge_m3 | mlx_bge_m3."
44
+ },
45
+ {
46
+ "name": "EMBEDDING_HTTP_PORT",
47
+ "default": "8401",
48
+ "description": "HTTP port for /embed and the vector-index endpoints."
49
+ },
50
+ {
51
+ "name": "EMBEDDING_INDEX_ENABLED",
52
+ "default": "true",
53
+ "description": "Enable the persistent vector index endpoints (/index, /search, /remove, /purge)."
54
+ },
55
+ {
56
+ "name": "EMBEDDING_INDEX_DB_PATH",
57
+ "default": "data/embedding_index.db",
58
+ "description": "SQLite file backing the vector index."
59
+ },
60
+ {
61
+ "name": "EMBEDDING_SEARCH_BACKEND",
62
+ "default": "numpy",
63
+ "description": "/search matmul backend: numpy (Accelerate BLAS) or mlx (Apple-GPU resident matrix; numpy fallback when mlx is absent). v0.6.0."
64
+ },
65
+ {
66
+ "name": "EMBEDDING_SIDECAR",
67
+ "default": "auto",
68
+ "description": "Startup source for the resident vectors: 'auto' maps them from the sidecar file, 'off' always reads them from SQLite. v0.7.0."
69
+ },
70
+ {
71
+ "name": "EMBEDDING_SIDECAR_PATH",
72
+ "default": "",
73
+ "description": "Where the sidecar file lives. Empty = alongside the index database, named after it. v0.7.0."
74
+ },
75
+ {
76
+ "name": "EMBEDDING_SIDECAR_MIN_ROWS",
77
+ "default": "10000",
78
+ "description": "Smallest corpus that gets a sidecar file; below it the in-memory index is cheap enough that a file adds nothing. v0.7.0."
79
+ },
80
+ {
81
+ "name": "EMBEDDING_SIDECAR_MAX_TAIL",
82
+ "default": "0.25",
83
+ "description": "Rebuild the sidecar when the rows written since the last build exceed this fraction of the rows in the file. v0.7.0."
84
+ },
85
+ {
86
+ "name": "ONNX_MODEL_DIR",
87
+ "default": "",
88
+ "description": "Override the model directory for ONNX providers (auto-resolved by provider when empty)."
89
+ },
90
+ {
91
+ "name": "ONNX_EP_PREFERENCE",
92
+ "default": "",
93
+ "description": "ONNX execution providers, comma-separated. Empty = auto (CoreML on macOS, DirectML on Windows, else CPU; CPU always ensured)."
94
+ },
95
+ {
96
+ "name": "ONNX_MAX_SEQ_LEN",
97
+ "default": "2048",
98
+ "description": "Max tokenization length (1-8192; MiniLM clamped to 512 internally)."
99
+ },
100
+ {
101
+ "name": "EMBEDDING_MODEL_VARIANT",
102
+ "default": "fp32",
103
+ "description": "Precision of jina-v5-nano to load: fp32 / fp16 / int8, downloaded on first use. int8 saves about 280 MB of resident memory and costs four to eight times more per query; vectors already stored were produced at fp32. v0.7.0."
104
+ },
105
+ {
106
+ "name": "ONNX_INTRA_OP_THREADS",
107
+ "default": "0",
108
+ "description": "ONNX Runtime intra-op threads. 0 = the runtime decides. Set it when the process runs under a CPU quota the runtime cannot see (container limit, shared host); over-subscribing is slower, not faster. v0.7.0."
109
+ },
110
+ {
111
+ "name": "ONNX_GRAPH_OPT_LEVEL",
112
+ "default": "all",
113
+ "description": "ONNX Runtime graph optimization level: disable / basic / extended / all. Lower it only to compare against an un-fused graph. v0.7.0."
114
+ },
115
+ {
116
+ "name": "EMBEDDING_MAX_BATCH",
117
+ "default": "64",
118
+ "description": "Most texts one model run may carry when concurrent requests are merged into it. 0 disables merging and gives one pass per request. v0.7.0."
119
+ },
120
+ {
121
+ "name": "EMBEDDING_API_KEY",
122
+ "default": "",
123
+ "description": "Required for the api_openai provider."
124
+ },
125
+ {
126
+ "name": "EMBEDDING_API_URL",
127
+ "default": "https://api.openai.com/v1/embeddings",
128
+ "description": "API endpoint for the api_openai provider."
129
+ },
130
+ {
131
+ "name": "CEMBEDDING_AUTH_TOKEN",
132
+ "default": "",
133
+ "description": "Inbound bearer token required on every HTTP request (REST endpoints and the Streamable HTTP MCP transport). Empty = unauthenticated, which is safe only when nothing but this machine can reach the process — a tunnel or reverse proxy forwards to loopback, so a loopback bind is not evidence of that. v0.6.2."
134
+ },
135
+ {
136
+ "name": "CEMBEDDING_REQUIRE_AUTH",
137
+ "default": "false",
138
+ "description": "Refuse to start when CEMBEDDING_AUTH_TOKEN is empty, instead of starting unauthenticated with a warning. v0.6.2."
139
+ }
140
+ ],
141
+ "auto_restart": true,
142
+ "changelog": "v0.9.0: GET /capabilities says which backend produced the vectors, so a caller that stores vectors can tell whether a stored one may still be compared with a fresh one. Over /embed it cannot: the request carries texts and the server picks the model, so a client that falls back to a configured name reads two different models as one, including two precisions of one model, which return different vectors through the same tokenizer. The report names the provider, model, width, truncation window, pooling, normalization, and the digests of the graph, tokenizer and weight files the provider actually opened, and reduces them to one fingerprint to store beside a vector. When a component cannot be established, incomplete names it and the fingerprint is null, never a fingerprint over part of the identity; api_openai and mlx_bge_m3 report null because the files that would be hashed are not this process's to read. Null means unknown, not unchanged. /embed is untouched; digests are computed once per file state, off the event loop, and cached. The route sits behind the same bearer authentication as the other REST endpoints. Verified end to end on jina-v5-nano: a complete identity with a fingerprint, 401 without the token when one is configured, and a client pointed at a server without the route reads the 404 as unknown. 34 regression tests.\n\nv0.8.0: The server reports where each text's embedding window closes, so a caller storing long records can split them where the vector stops seeing them instead of guessing from a character count (for one token window that position varies by more than a factor of two). POST /embed accepts an opt-in token_info flag, and POST /count_tokens returns the same report without running the model. Each entry carries the token count, the window, whether the text was cut, and window_end_char, the character offset where the embedded prefix ends. Without the flag /embed answers exactly as before. Providers that cannot see their tokens (api_openai, mlx_bge_m3) report null, meaning unknown. The counting tokenizer is a separate instance that loads on first use (about 29 MiB resident for jina-v5-nano); counting costs 0.4 to 1.6% of an embed call and only when asked. Verified end to end on jina-v5-nano: embedding the reported prefix gives the same vector as the whole text, and cutting 8 characters earlier does not. 24 regression tests.\n\nv0.7.0: Performance and footprint, with results unchanged. Startup maps the resident vectors from a contiguous file next to the index database instead of decoding every blob out of SQLite (100k x 768: 0.23 s and 1.1 GiB peak, to 0.09 s and 402 MiB); SQLite stays the durable record and the file is a cache that can be deleted. The index keeps one matrix per namespace instead of a per-item map plus a rebuilt stack, so a write no longer costs the next search a rebuild (20k x 384: 153 ms to 17 ms over 30 write+search rounds). Concurrent /embed requests that arrive while a model pass is running share the next pass instead of each paying for one (32 clients: p50 219 ms to 90 ms, 150 to 358 req/s). fp16 and int8 weights of jina-v5-nano are selectable with EMBEDDING_MODEL_VARIANT; fp32 stays the default because int8 saves about 280 MB but costs four to eight times more per query. ONNX_INTRA_OP_THREADS and ONNX_GRAPH_OPT_LEVEL configure the runtime session, both defaulting to what it did before. The one observable difference: once the sidecar splits a namespace into two segments, the two BLAS calls can accumulate in different orders, so rows whose scores tie exactly may order differently. EMBEDDING_SIDECAR=off keeps the previous startup path, EMBEDDING_MAX_BATCH=0 the previous embed path. 116 regression tests.\n\nv0.6.2: SECURITY — both HTTP surfaces now support inbound bearer authentication, which they previously had no mechanism for at all. Set CEMBEDDING_AUTH_TOKEN and every request to the REST endpoints (/embed, /index, /search, /remove, /purge) and to the Streamable HTTP MCP transport must carry 'Authorization: Bearer <token>'; missing headers, wrong schemes and wrong tokens are all rejected with 401, compared with hmac.compare_digest. The change is additive: with no token configured the server behaves exactly as 0.6.1 and logs a warning, and CEMBEDDING_REQUIRE_AUTH=true turns that warning into a startup error for operators who want fail-closed today. A later release will make requiring a token the default. The warning deliberately states that a loopback bind is not evidence that requests are local — a tunnel or reverse proxy forwards to loopback, which is how the sibling CPersona server ran publicly reachable and unauthenticated for 13 days. 40 regression tests drive the real middleware at the ASGI and aiohttp layers.\n\nv0.6.1: ONNX providers now pad each batch to its longest sequence instead of a fixed ONNX_MAX_SEQ_LEN. Fixed-length padding made every forward pass cost the full max length (default 2048) regardless of input size: a short recall query encoded in ~617 ms; pad-to-longest brings it to ~7 ms (~90x) and batch document encode from ~0.5 to ~460 docs/s, with bit-identical embeddings (pooling honors the attention mask; parity verified to cosine 1.0). Affects all three local ONNX providers (jina-v5-nano, bge-m3, MiniLM). Adds padding-regression tests.\n\nv0.6.0: /search runs one matmul over a per-namespace resident matrix instead of a per-item Python loop, with vectorized threshold + top-K selection (~21x at 237k x 384: 131 ms -> 6 ms/query). New EMBEDDING_SEARCH_BACKEND env (numpy default, mlx = Apple-GPU resident matrix with numpy fallback). New scripts/backfill_embedding_index.py migrates existing cpersona embedding blobs into the index so a deployment can flip CPERSONA_VECTOR_SEARCH_MODE=remote without losing pre-flip semantic recall. Adds the test suite (12 tests) and CI the repo lacked since extraction.\n\nv0.5.0: PyPI packaging release — flat layout restructured into the cembedding/ package with console scripts (cembedding, cembedding-download-model); published to PyPI as 'cembedding'. Functionally identical to clotohub-servers servers/embedding 0.4.0, from which this repository was extracted on 2026-06-28.\n\nv0.4.0 and earlier: see the clotohub-servers repository history (servers/embedding)."
143
+ }
@@ -0,0 +1,367 @@
1
+ """The identity of the backend behind the vectors.
2
+
3
+ A caller stores vectors next to the name of whatever produced them, and later
4
+ compares that name to decide whether a stored vector may still be compared with
5
+ a fresh one. Over HTTP the caller never learns the name: it posts texts and the
6
+ server picks the model, so the caller falls back to a configured default and two
7
+ different models read as one.
8
+
9
+ These tests pin what makes the report usable for that decision: every component
10
+ that moves the numbers moves the fingerprint, an identity the server cannot
11
+ complete is reported as incomplete rather than fingerprinted over the half it
12
+ knows, a model replaced in place gets a new digest, and the response `/embed`
13
+ returns is the one it returned before this endpoint existed.
14
+ """
15
+
16
+ import os
17
+ import sys
18
+ import types
19
+
20
+ import pytest
21
+ from aiohttp.test_utils import TestClient, TestServer
22
+ from tokenizers import Tokenizer
23
+ from tokenizers.models import WordLevel
24
+ from tokenizers.pre_tokenizers import Whitespace
25
+
26
+ from cembedding import server
27
+ from cembedding.server import _TokenCounter, backend_identity
28
+
29
+ COMPLETE = {
30
+ "model": "bge-m3",
31
+ "dimensions": 1024,
32
+ "window": 512,
33
+ "pooling": "cls",
34
+ "normalized": True,
35
+ }
36
+
37
+
38
+ class FakeProvider:
39
+ """A provider with no model behind it, reporting whatever it is handed."""
40
+
41
+ def __init__(self, identity=None, files=None):
42
+ self._identity = COMPLETE if identity is None else identity
43
+ self._files = files or {}
44
+ self.embed_calls = 0
45
+
46
+ async def embed(self, texts):
47
+ self.embed_calls += 1
48
+ return [[0.0, 1.0] for _ in texts]
49
+
50
+ def dimensions(self):
51
+ return 2
52
+
53
+ def identity(self):
54
+ return dict(self._identity)
55
+
56
+ def identity_files(self):
57
+ return dict(self._files)
58
+
59
+ token_counter = server.EmbeddingProvider.token_counter
60
+
61
+
62
+ @pytest.fixture(autouse=True)
63
+ def clean_digest_cache():
64
+ """Each test starts with an empty cache: a digest kept from another test's
65
+ file would hide both the caching test and the re-read test."""
66
+ server._DIGEST_CACHE.clear()
67
+ yield
68
+ server._DIGEST_CACHE.clear()
69
+
70
+
71
+ @pytest.fixture
72
+ def model_files(tmp_path):
73
+ graph = tmp_path / "model.onnx"
74
+ tokenizer = tmp_path / "tokenizer.json"
75
+ graph.write_bytes(b"graph-bytes")
76
+ tokenizer.write_bytes(b"tokenizer-bytes")
77
+ return {"graph": str(graph), "tokenizer": str(tokenizer)}
78
+
79
+
80
+ def _client(auth_token=None):
81
+ return TestClient(TestServer(server.build_http_app(auth_token)))
82
+
83
+
84
+ # ------------------------------------------------------------- the fingerprint
85
+
86
+
87
+ async def test_a_complete_identity_is_fingerprinted(model_files, monkeypatch):
88
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "onnx_bge_m3")
89
+ report = await backend_identity(FakeProvider(files=model_files))
90
+
91
+ assert report["incomplete"] == []
92
+ assert report["fingerprint"].startswith("1:")
93
+ assert report["identity"]["provider"] == "onnx_bge_m3"
94
+ assert set(report["identity"]["digests"]) == {"graph", "tokenizer"}
95
+
96
+
97
+ async def test_the_same_backend_fingerprints_the_same_twice(model_files, monkeypatch):
98
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "onnx_bge_m3")
99
+ first = await backend_identity(FakeProvider(files=model_files))
100
+ server._DIGEST_CACHE.clear() # recomputed from the files, not replayed
101
+ second = await backend_identity(FakeProvider(files=model_files))
102
+
103
+ assert first["fingerprint"] == second["fingerprint"]
104
+
105
+
106
+ @pytest.mark.parametrize(
107
+ "field, value",
108
+ [
109
+ ("model", "bge-m3-other"),
110
+ ("dimensions", 768),
111
+ ("window", 8192),
112
+ ("pooling", "mean"),
113
+ ("normalized", False),
114
+ ],
115
+ )
116
+ async def test_every_field_that_moves_the_vectors_moves_the_fingerprint(field, value, model_files, monkeypatch):
117
+ """The point of the endpoint. A component that changes the numbers and not
118
+ the fingerprint would let a caller compare vectors from two backends."""
119
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "onnx_bge_m3")
120
+ base = await backend_identity(FakeProvider(files=model_files))
121
+ changed = await backend_identity(FakeProvider({**COMPLETE, field: value}, files=model_files))
122
+
123
+ assert changed["fingerprint"] is not None
124
+ assert changed["fingerprint"] != base["fingerprint"]
125
+
126
+
127
+ async def test_the_provider_is_part_of_the_identity(model_files, monkeypatch):
128
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "onnx_bge_m3")
129
+ base = await backend_identity(FakeProvider(files=model_files))
130
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "mlx_bge_m3")
131
+ changed = await backend_identity(FakeProvider(files=model_files))
132
+
133
+ assert changed["fingerprint"] != base["fingerprint"]
134
+
135
+
136
+ @pytest.mark.parametrize("label", ["graph", "tokenizer"])
137
+ async def test_replacing_a_file_in_place_changes_the_fingerprint(label, model_files, monkeypatch):
138
+ """Same path, same configuration, different bytes — the case a configured
139
+ model name cannot see at all."""
140
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "onnx_bge_m3")
141
+ base = await backend_identity(FakeProvider(files=model_files))
142
+
143
+ with open(model_files[label], "wb") as f:
144
+ f.write(b"replaced-bytes-of-a-different-length")
145
+ changed = await backend_identity(FakeProvider(files=model_files))
146
+
147
+ assert changed["fingerprint"] != base["fingerprint"]
148
+
149
+
150
+ async def test_a_second_weights_file_is_part_of_the_identity(model_files, tmp_path, monkeypatch):
151
+ """A graph that names its weights in a sibling file: hashing the graph alone
152
+ would give one digest to two different sets of weights."""
153
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "onnx_jina_v5_nano")
154
+ weights = tmp_path / "model.onnx_data"
155
+ weights.write_bytes(b"fp32-weights")
156
+ with_weights = {**model_files, "weights": str(weights)}
157
+
158
+ base = await backend_identity(FakeProvider(files=with_weights))
159
+ weights.write_bytes(b"int8-weights")
160
+ changed = await backend_identity(FakeProvider(files=with_weights))
161
+
162
+ assert base["incomplete"] == []
163
+ assert changed["fingerprint"] != base["fingerprint"]
164
+
165
+
166
+ # ------------------------------------------------------------ what is not known
167
+
168
+
169
+ @pytest.mark.parametrize("field", list(COMPLETE))
170
+ async def test_a_missing_field_is_reported_and_not_fingerprinted(field, model_files, monkeypatch):
171
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "onnx_bge_m3")
172
+ partial = {k: v for k, v in COMPLETE.items() if k != field}
173
+ report = await backend_identity(FakeProvider(partial, files=model_files))
174
+
175
+ assert report["fingerprint"] is None
176
+ assert field in report["incomplete"]
177
+
178
+
179
+ @pytest.mark.parametrize("label", ["graph", "tokenizer"])
180
+ async def test_a_file_that_cannot_be_read_is_missing_not_empty(label, model_files, tmp_path, monkeypatch):
181
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "onnx_bge_m3")
182
+ files = {**model_files, label: str(tmp_path / "absent")}
183
+ report = await backend_identity(FakeProvider(files=files))
184
+
185
+ assert report["fingerprint"] is None
186
+ assert f"digests.{label}" in report["incomplete"]
187
+ assert label not in report["identity"].get("digests", {})
188
+
189
+
190
+ async def test_a_backend_with_no_files_names_both_digests(monkeypatch):
191
+ """A remote API: the graph and the tokenizer are on the other side of the
192
+ network, so the identity stays incomplete however complete the fields are."""
193
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "api_openai")
194
+ report = await backend_identity(FakeProvider(files={}))
195
+
196
+ assert report["fingerprint"] is None
197
+ assert report["incomplete"] == ["digests.graph", "digests.tokenizer"]
198
+
199
+
200
+ async def test_two_incomplete_backends_are_not_told_apart_by_null(monkeypatch):
201
+ """Both answer null, which is why null is not a value a caller may compare.
202
+ The report says so by naming the missing parts instead."""
203
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "api_openai")
204
+ one = await backend_identity(FakeProvider({**COMPLETE, "model": "one"}))
205
+ other = await backend_identity(FakeProvider({**COMPLETE, "model": "other"}))
206
+
207
+ assert one["fingerprint"] is other["fingerprint"] is None
208
+ assert one["identity"]["model"] != other["identity"]["model"]
209
+
210
+
211
+ # ------------------------------------------------------------------- the digest
212
+
213
+
214
+ async def test_the_digest_is_computed_once_per_file_state(model_files, monkeypatch):
215
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "onnx_bge_m3")
216
+ reads = []
217
+ original = server._digest_file
218
+ monkeypatch.setattr(server, "_digest_file", lambda p: reads.append(p) or original(p))
219
+
220
+ provider = FakeProvider(files=model_files)
221
+ await backend_identity(provider)
222
+ await backend_identity(provider)
223
+ assert len(reads) == 2 # graph and tokenizer, once each
224
+
225
+ with open(model_files["graph"], "wb") as f:
226
+ f.write(b"replaced")
227
+ await backend_identity(provider)
228
+ assert len(reads) == 3 # the replaced file, and only it
229
+
230
+
231
+ # ----------------------------------------------------------------- the endpoint
232
+
233
+
234
+ async def test_capabilities_reports_over_http(model_files, monkeypatch):
235
+ monkeypatch.setattr(server, "EMBEDDING_PROVIDER", "onnx_bge_m3")
236
+ monkeypatch.setattr(server, "_provider", FakeProvider(files=model_files))
237
+ async with _client() as client:
238
+ resp = await client.get("/capabilities")
239
+ body = await resp.json()
240
+
241
+ assert resp.status == 200
242
+ assert body["identity"]["model"] == "bge-m3"
243
+ assert body["fingerprint"].startswith("1:")
244
+
245
+
246
+ async def test_capabilities_answers_503_before_the_model_is_loaded(monkeypatch):
247
+ monkeypatch.setattr(server, "_provider", None)
248
+ async with _client() as client:
249
+ resp = await client.get("/capabilities")
250
+ assert resp.status == 503
251
+
252
+
253
+ async def test_capabilities_is_behind_the_same_bearer_check(model_files, monkeypatch):
254
+ monkeypatch.setattr(server, "_provider", FakeProvider(files=model_files))
255
+ async with _client(auth_token="secret") as client:
256
+ assert (await client.get("/capabilities")).status == 401
257
+ resp = await client.get("/capabilities", headers={"Authorization": "Bearer secret"})
258
+ assert resp.status == 200
259
+
260
+
261
+ async def test_embed_answers_exactly_as_it_did_before(model_files, monkeypatch):
262
+ """The identity is on its own route. A caller that never asks for it receives
263
+ the response it received before this endpoint existed."""
264
+ monkeypatch.setattr(server, "_provider", FakeProvider(files=model_files))
265
+ async with _client() as client:
266
+ resp = await client.post("/embed", json={"texts": ["alpha beta"]})
267
+ assert await resp.json() == {"embeddings": [[0.0, 1.0]], "dimensions": 2}
268
+
269
+
270
+ # ------------------------------------------------- what each provider declares
271
+
272
+
273
+ @pytest.mark.parametrize(
274
+ "cls, model, pooling",
275
+ [
276
+ (server.OnnxMiniLMProvider, "all-MiniLM-L6-v2", "mean"),
277
+ (server.OnnxBgeM3Provider, "bge-m3", "cls"),
278
+ (server.OnnxJinaV5NanoProvider, "jina-embeddings-v5-text-nano-retrieval", "last_token"),
279
+ ],
280
+ )
281
+ def test_each_onnx_provider_declares_the_pooling_it_performs(cls, model, pooling):
282
+ """The declared reduction and the performed one are separate statements of
283
+ one fact. Changing `_embed_sync` without changing the declaration would leave
284
+ the fingerprint equal across vectors that are not, so both have to move."""
285
+ provider = cls.__new__(cls)
286
+ provider._counter = _TokenCounter(None, 512, None)
287
+ identity = provider.identity()
288
+
289
+ assert identity["model"] == model
290
+ assert identity["pooling"] == pooling
291
+ assert identity["window"] == 512
292
+
293
+
294
+ def test_a_provider_that_cannot_see_its_tokens_omits_the_window():
295
+ """No window reported is a missing component, never an unbounded one."""
296
+ provider = server.OnnxBgeM3Provider.__new__(server.OnnxBgeM3Provider)
297
+ assert "window" not in provider.identity()
298
+
299
+
300
+ def test_a_provider_reports_the_files_it_opened(tmp_path):
301
+ provider = server.OnnxBgeM3Provider.__new__(server.OnnxBgeM3Provider)
302
+ assert provider.identity_files() == {}
303
+
304
+ provider._loaded_files = {"graph": str(tmp_path / "model.onnx")}
305
+ assert provider.identity_files() == {"graph": str(tmp_path / "model.onnx")}
306
+
307
+
308
+ def _toy_tokenizer() -> Tokenizer:
309
+ tok = Tokenizer(WordLevel({"[UNK]": 0}, unk_token="[UNK]"))
310
+ tok.pre_tokenizer = Whitespace()
311
+ return tok
312
+
313
+
314
+ def _stub_onnx_load(monkeypatch):
315
+ """Let a provider's initialize() run without a model on disk.
316
+
317
+ ``os.path.exists`` is left alone: whether the sibling weights file is there
318
+ is the thing under test, so a stub answering True for every path would make
319
+ the assertion pass on a provider that never looked.
320
+ """
321
+ monkeypatch.setitem(sys.modules, "onnxruntime", types.ModuleType("onnxruntime"))
322
+ session = type("Session", (), {"get_providers": lambda self: ["CPUExecutionProvider"]})()
323
+ monkeypatch.setattr(server, "_create_ort_session", lambda *a, **k: session)
324
+ monkeypatch.setattr(Tokenizer, "from_file", staticmethod(lambda _p: _toy_tokenizer()))
325
+
326
+
327
+ @pytest.mark.parametrize("with_weights", [True, False])
328
+ async def test_the_jina_provider_records_the_weights_beside_its_graph(monkeypatch, tmp_path, with_weights):
329
+ """The graph of this model is a stub naming its weights in a sibling file.
330
+ Recording only the graph would give one identity to two precisions, so this
331
+ pins the provider that opens them rather than the helper that hashes them."""
332
+ from cembedding.download_model import JINA_VARIANT_STEMS
333
+
334
+ _stub_onnx_load(monkeypatch)
335
+ stem = JINA_VARIANT_STEMS[server.EMBEDDING_MODEL_VARIANT]
336
+ graph = tmp_path / f"{stem}.onnx"
337
+ graph.write_bytes(b"graph")
338
+ (tmp_path / "tokenizer.json").write_bytes(b"{}")
339
+ weights = tmp_path / f"{stem}.onnx_data"
340
+ if with_weights:
341
+ weights.write_bytes(b"weights")
342
+
343
+ provider = server.OnnxJinaV5NanoProvider(str(tmp_path))
344
+ await provider.initialize()
345
+ files = provider.identity_files()
346
+
347
+ assert files["graph"] == str(graph)
348
+ assert files["tokenizer"] == str(tmp_path / "tokenizer.json")
349
+ assert files.get("weights") == (str(weights) if with_weights else None)
350
+
351
+
352
+ @pytest.mark.parametrize(
353
+ "cls, stem",
354
+ [(server.OnnxMiniLMProvider, "model"), (server.OnnxBgeM3Provider, "model")],
355
+ )
356
+ async def test_a_single_file_provider_records_its_graph_and_tokenizer(monkeypatch, tmp_path, cls, stem):
357
+ _stub_onnx_load(monkeypatch)
358
+ (tmp_path / f"{stem}.onnx").write_bytes(b"graph")
359
+ (tmp_path / "tokenizer.json").write_bytes(b"{}")
360
+
361
+ provider = cls(str(tmp_path))
362
+ await provider.initialize()
363
+
364
+ assert provider.identity_files() == {
365
+ "graph": os.path.join(str(tmp_path), f"{stem}.onnx"),
366
+ "tokenizer": os.path.join(str(tmp_path), "tokenizer.json"),
367
+ }
@@ -1,143 +0,0 @@
1
- {
2
- "spec_version": 1,
3
- "connector_type": "mgp_server",
4
- "id": "cembedding",
5
- "name": "CEmbedding",
6
- "description": "Local-first embedding server: vector generation + index/search over HTTP (ONNX on-device or API providers). The reference /embed and remote /search server for CPersona.",
7
- "version": "0.8.0",
8
- "category": "tool",
9
- "trust_level": "core",
10
- "magic_seal": "sha256:f75b48b630e7b1cf539577121ffddede7e35a72aadc92733d064359145ff5e64",
11
- "install": {
12
- "source": {
13
- "type": "git",
14
- "url": "https://github.com/Cloto-dev/CEmbedding",
15
- "reference": "",
16
- "subdir": null
17
- },
18
- "package_manager": "uv",
19
- "runtime": "python",
20
- "directory": "",
21
- "dependencies": [],
22
- "bin_name": null
23
- },
24
- "icon": "layers",
25
- "tags": [
26
- "embedding",
27
- "vector",
28
- "search",
29
- "onnx"
30
- ],
31
- "host_compatibility": [
32
- "clotocore",
33
- "claude-code",
34
- "claude-desktop",
35
- "cursor",
36
- "project-airi"
37
- ],
38
- "env_vars": [],
39
- "optional_env_vars": [
40
- {
41
- "name": "EMBEDDING_PROVIDER",
42
- "default": "api_openai",
43
- "description": "Embedding provider: api_openai | onnx_miniml | onnx_jina_v5_nano | onnx_bge_m3 | mlx_bge_m3."
44
- },
45
- {
46
- "name": "EMBEDDING_HTTP_PORT",
47
- "default": "8401",
48
- "description": "HTTP port for /embed and the vector-index endpoints."
49
- },
50
- {
51
- "name": "EMBEDDING_INDEX_ENABLED",
52
- "default": "true",
53
- "description": "Enable the persistent vector index endpoints (/index, /search, /remove, /purge)."
54
- },
55
- {
56
- "name": "EMBEDDING_INDEX_DB_PATH",
57
- "default": "data/embedding_index.db",
58
- "description": "SQLite file backing the vector index."
59
- },
60
- {
61
- "name": "EMBEDDING_SEARCH_BACKEND",
62
- "default": "numpy",
63
- "description": "/search matmul backend: numpy (Accelerate BLAS) or mlx (Apple-GPU resident matrix; numpy fallback when mlx is absent). v0.6.0."
64
- },
65
- {
66
- "name": "EMBEDDING_SIDECAR",
67
- "default": "auto",
68
- "description": "Startup source for the resident vectors: 'auto' maps them from the sidecar file, 'off' always reads them from SQLite. v0.7.0."
69
- },
70
- {
71
- "name": "EMBEDDING_SIDECAR_PATH",
72
- "default": "",
73
- "description": "Where the sidecar file lives. Empty = alongside the index database, named after it. v0.7.0."
74
- },
75
- {
76
- "name": "EMBEDDING_SIDECAR_MIN_ROWS",
77
- "default": "10000",
78
- "description": "Smallest corpus that gets a sidecar file; below it the in-memory index is cheap enough that a file adds nothing. v0.7.0."
79
- },
80
- {
81
- "name": "EMBEDDING_SIDECAR_MAX_TAIL",
82
- "default": "0.25",
83
- "description": "Rebuild the sidecar when the rows written since the last build exceed this fraction of the rows in the file. v0.7.0."
84
- },
85
- {
86
- "name": "ONNX_MODEL_DIR",
87
- "default": "",
88
- "description": "Override the model directory for ONNX providers (auto-resolved by provider when empty)."
89
- },
90
- {
91
- "name": "ONNX_EP_PREFERENCE",
92
- "default": "",
93
- "description": "ONNX execution providers, comma-separated. Empty = auto (CoreML on macOS, DirectML on Windows, else CPU; CPU always ensured)."
94
- },
95
- {
96
- "name": "ONNX_MAX_SEQ_LEN",
97
- "default": "2048",
98
- "description": "Max tokenization length (1-8192; MiniLM clamped to 512 internally)."
99
- },
100
- {
101
- "name": "EMBEDDING_MODEL_VARIANT",
102
- "default": "fp32",
103
- "description": "Precision of jina-v5-nano to load: fp32 / fp16 / int8, downloaded on first use. int8 saves about 280 MB of resident memory and costs four to eight times more per query; vectors already stored were produced at fp32. v0.7.0."
104
- },
105
- {
106
- "name": "ONNX_INTRA_OP_THREADS",
107
- "default": "0",
108
- "description": "ONNX Runtime intra-op threads. 0 = the runtime decides. Set it when the process runs under a CPU quota the runtime cannot see (container limit, shared host); over-subscribing is slower, not faster. v0.7.0."
109
- },
110
- {
111
- "name": "ONNX_GRAPH_OPT_LEVEL",
112
- "default": "all",
113
- "description": "ONNX Runtime graph optimization level: disable / basic / extended / all. Lower it only to compare against an un-fused graph. v0.7.0."
114
- },
115
- {
116
- "name": "EMBEDDING_MAX_BATCH",
117
- "default": "64",
118
- "description": "Most texts one model run may carry when concurrent requests are merged into it. 0 disables merging and gives one pass per request. v0.7.0."
119
- },
120
- {
121
- "name": "EMBEDDING_API_KEY",
122
- "default": "",
123
- "description": "Required for the api_openai provider."
124
- },
125
- {
126
- "name": "EMBEDDING_API_URL",
127
- "default": "https://api.openai.com/v1/embeddings",
128
- "description": "API endpoint for the api_openai provider."
129
- },
130
- {
131
- "name": "CEMBEDDING_AUTH_TOKEN",
132
- "default": "",
133
- "description": "Inbound bearer token required on every HTTP request (REST endpoints and the Streamable HTTP MCP transport). Empty = unauthenticated, which is safe only when nothing but this machine can reach the process — a tunnel or reverse proxy forwards to loopback, so a loopback bind is not evidence of that. v0.6.2."
134
- },
135
- {
136
- "name": "CEMBEDDING_REQUIRE_AUTH",
137
- "default": "false",
138
- "description": "Refuse to start when CEMBEDDING_AUTH_TOKEN is empty, instead of starting unauthenticated with a warning. v0.6.2."
139
- }
140
- ],
141
- "auto_restart": true,
142
- "changelog": "v0.8.0: The server reports where each text's embedding window closes, so a caller storing long records can split them where the vector stops seeing them instead of guessing from a character count (for one token window that position varies by more than a factor of two). POST /embed accepts an opt-in token_info flag, and POST /count_tokens returns the same report without running the model. Each entry carries the token count, the window, whether the text was cut, and window_end_char, the character offset where the embedded prefix ends. Without the flag /embed answers exactly as before. Providers that cannot see their tokens (api_openai, mlx_bge_m3) report null, meaning unknown. The counting tokenizer is a separate instance that loads on first use (about 29 MiB resident for jina-v5-nano); counting costs 0.4 to 1.6% of an embed call and only when asked. Verified end to end on jina-v5-nano: embedding the reported prefix gives the same vector as the whole text, and cutting 8 characters earlier does not. 24 regression tests.\n\nv0.7.0: Performance and footprint, with results unchanged. Startup maps the resident vectors from a contiguous file next to the index database instead of decoding every blob out of SQLite (100k x 768: 0.23 s and 1.1 GiB peak, to 0.09 s and 402 MiB); SQLite stays the durable record and the file is a cache that can be deleted. The index keeps one matrix per namespace instead of a per-item map plus a rebuilt stack, so a write no longer costs the next search a rebuild (20k x 384: 153 ms to 17 ms over 30 write+search rounds). Concurrent /embed requests that arrive while a model pass is running share the next pass instead of each paying for one (32 clients: p50 219 ms to 90 ms, 150 to 358 req/s). fp16 and int8 weights of jina-v5-nano are selectable with EMBEDDING_MODEL_VARIANT; fp32 stays the default because int8 saves about 280 MB but costs four to eight times more per query. ONNX_INTRA_OP_THREADS and ONNX_GRAPH_OPT_LEVEL configure the runtime session, both defaulting to what it did before. The one observable difference: once the sidecar splits a namespace into two segments, the two BLAS calls can accumulate in different orders, so rows whose scores tie exactly may order differently. EMBEDDING_SIDECAR=off keeps the previous startup path, EMBEDDING_MAX_BATCH=0 the previous embed path. 116 regression tests.\n\nv0.6.2: SECURITY — both HTTP surfaces now support inbound bearer authentication, which they previously had no mechanism for at all. Set CEMBEDDING_AUTH_TOKEN and every request to the REST endpoints (/embed, /index, /search, /remove, /purge) and to the Streamable HTTP MCP transport must carry 'Authorization: Bearer <token>'; missing headers, wrong schemes and wrong tokens are all rejected with 401, compared with hmac.compare_digest. The change is additive: with no token configured the server behaves exactly as 0.6.1 and logs a warning, and CEMBEDDING_REQUIRE_AUTH=true turns that warning into a startup error for operators who want fail-closed today. A later release will make requiring a token the default. The warning deliberately states that a loopback bind is not evidence that requests are local — a tunnel or reverse proxy forwards to loopback, which is how the sibling CPersona server ran publicly reachable and unauthenticated for 13 days. 40 regression tests drive the real middleware at the ASGI and aiohttp layers.\n\nv0.6.1: ONNX providers now pad each batch to its longest sequence instead of a fixed ONNX_MAX_SEQ_LEN. Fixed-length padding made every forward pass cost the full max length (default 2048) regardless of input size: a short recall query encoded in ~617 ms; pad-to-longest brings it to ~7 ms (~90x) and batch document encode from ~0.5 to ~460 docs/s, with bit-identical embeddings (pooling honors the attention mask; parity verified to cosine 1.0). Affects all three local ONNX providers (jina-v5-nano, bge-m3, MiniLM). Adds padding-regression tests.\n\nv0.6.0: /search runs one matmul over a per-namespace resident matrix instead of a per-item Python loop, with vectorized threshold + top-K selection (~21x at 237k x 384: 131 ms -> 6 ms/query). New EMBEDDING_SEARCH_BACKEND env (numpy default, mlx = Apple-GPU resident matrix with numpy fallback). New scripts/backfill_embedding_index.py migrates existing cpersona embedding blobs into the index so a deployment can flip CPERSONA_VECTOR_SEARCH_MODE=remote without losing pre-flip semantic recall. Adds the test suite (12 tests) and CI the repo lacked since extraction.\n\nv0.5.0: PyPI packaging release — flat layout restructured into the cembedding/ package with console scripts (cembedding, cembedding-download-model); published to PyPI as 'cembedding'. Functionally identical to clotohub-servers servers/embedding 0.4.0, from which this repository was extracted on 2026-06-28.\n\nv0.4.0 and earlier: see the clotohub-servers repository history (servers/embedding)."
143
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes