vernkv 1.0.0__py3-none-win_amd64.whl
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.
- vernkv/__init__.py +15 -0
- vernkv/_bin/vernkv-server.exe +0 -0
- vernkv/_binary.py +92 -0
- vernkv/ai.py +216 -0
- vernkv/client.py +782 -0
- vernkv-1.0.0.dist-info/METADATA +125 -0
- vernkv-1.0.0.dist-info/RECORD +9 -0
- vernkv-1.0.0.dist-info/WHEEL +4 -0
- vernkv-1.0.0.dist-info/entry_points.txt +3 -0
vernkv/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Vern Python SDK — ultra-minimal, zero-dependency core client & AI primitives."""
|
|
2
|
+
|
|
3
|
+
from .ai import ConversationMemory, SemanticCache, VernKVStore
|
|
4
|
+
from .client import VectorHit, Vern, VernError, VernKV, VernKVError
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"ConversationMemory",
|
|
8
|
+
"SemanticCache",
|
|
9
|
+
"VectorHit",
|
|
10
|
+
"Vern",
|
|
11
|
+
"VernError",
|
|
12
|
+
"VernKV",
|
|
13
|
+
"VernKVError",
|
|
14
|
+
"VernKVStore",
|
|
15
|
+
]
|
|
Binary file
|
vernkv/_binary.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Binary discovery for bundled or source-built vernkv-server."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.resources
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _exe_name() -> str:
|
|
15
|
+
return "vernkv-server.exe" if platform.system().lower() == "windows" else "vernkv-server"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _bundled_binary() -> Path | None:
|
|
19
|
+
try:
|
|
20
|
+
bin_dir = importlib.resources.files("vernkv").joinpath("_bin")
|
|
21
|
+
candidate = Path(str(bin_dir)) / _exe_name()
|
|
22
|
+
if candidate.is_file() and os.access(candidate, os.X_OK):
|
|
23
|
+
return candidate
|
|
24
|
+
except Exception:
|
|
25
|
+
return None
|
|
26
|
+
return None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _find_repo_root() -> Path | None:
|
|
30
|
+
starts = [Path(__file__).resolve().parent, Path.cwd().resolve()]
|
|
31
|
+
for start in starts:
|
|
32
|
+
for parent in (start, *start.parents):
|
|
33
|
+
if (parent / "go.mod").is_file() and (parent / "cmd" / "vernkv-server" / "main.go").is_file():
|
|
34
|
+
return parent
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _build_from_repo(repo_root: Path) -> Path | None:
|
|
39
|
+
go_bin = shutil.which("go")
|
|
40
|
+
if not go_bin:
|
|
41
|
+
return None
|
|
42
|
+
cache_dir = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "vernkv" / "bin"
|
|
43
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
target = cache_dir / _exe_name()
|
|
45
|
+
env = os.environ.copy()
|
|
46
|
+
env["CGO_ENABLED"] = "0"
|
|
47
|
+
res = subprocess.run(
|
|
48
|
+
[go_bin, "build", "-o", str(target), "./cmd/vernkv-server"],
|
|
49
|
+
cwd=str(repo_root),
|
|
50
|
+
env=env,
|
|
51
|
+
capture_output=True,
|
|
52
|
+
text=True,
|
|
53
|
+
)
|
|
54
|
+
if res.returncode != 0:
|
|
55
|
+
raise RuntimeError(f"failed to build vernkv-server from source:\n{res.stderr}")
|
|
56
|
+
return target
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def resolve_server_binary(explicit: str | os.PathLike[str] | None = None) -> Path:
|
|
60
|
+
"""Locate vernkv-server from explicit path, env, bundled wheel binary, PATH, or Go source."""
|
|
61
|
+
if explicit is not None:
|
|
62
|
+
p = Path(explicit).expanduser().resolve()
|
|
63
|
+
if p.is_file():
|
|
64
|
+
return p
|
|
65
|
+
raise FileNotFoundError(f"vernkv-server binary not found at {p}")
|
|
66
|
+
|
|
67
|
+
if env_bin := os.environ.get("VERNKV_SERVER_BIN"):
|
|
68
|
+
p = Path(env_bin).expanduser().resolve()
|
|
69
|
+
if p.is_file():
|
|
70
|
+
return p
|
|
71
|
+
raise FileNotFoundError(f"VERNKV_SERVER_BIN points to missing file: {p}")
|
|
72
|
+
|
|
73
|
+
if bundled := _bundled_binary():
|
|
74
|
+
return bundled
|
|
75
|
+
|
|
76
|
+
if on_path := shutil.which(_exe_name()):
|
|
77
|
+
return Path(on_path)
|
|
78
|
+
|
|
79
|
+
if repo_root := _find_repo_root():
|
|
80
|
+
if built := _build_from_repo(repo_root):
|
|
81
|
+
return built
|
|
82
|
+
|
|
83
|
+
raise FileNotFoundError(
|
|
84
|
+
"Could not locate vernkv-server binary. Install a platform wheel, set VERNKV_SERVER_BIN, "
|
|
85
|
+
"add vernkv-server to PATH, or ensure Go is installed when running inside the vernkv repo."
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def run_server_cli() -> None:
|
|
90
|
+
"""Console script entrypoint forwarding CLI flags to vernkv-server."""
|
|
91
|
+
binary = resolve_server_binary()
|
|
92
|
+
os.execv(str(binary), [str(binary), *sys.argv[1:]])
|
vernkv/ai.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Zero-dependency AI primitives built on top of Vern."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
import uuid
|
|
8
|
+
from typing import Any, Callable, Sequence
|
|
9
|
+
|
|
10
|
+
from .client import VectorHit, Vern, VernError
|
|
11
|
+
|
|
12
|
+
EmbedFn = Callable[[list[str]], Sequence[Sequence[float]]]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class VernKVStore:
|
|
16
|
+
"""Local hybrid RAG vector + metadata + document store backed by Vern."""
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
client: Vern,
|
|
21
|
+
index: str = "documents",
|
|
22
|
+
*,
|
|
23
|
+
embed_fn: EmbedFn | None = None,
|
|
24
|
+
metric: str = "cosine",
|
|
25
|
+
index_type: str = "flat",
|
|
26
|
+
) -> None:
|
|
27
|
+
self.client = client
|
|
28
|
+
self.index = index
|
|
29
|
+
self.embed_fn = embed_fn
|
|
30
|
+
self.metric = metric
|
|
31
|
+
self.index_type = index_type
|
|
32
|
+
|
|
33
|
+
def add_texts(
|
|
34
|
+
self,
|
|
35
|
+
texts: Sequence[str],
|
|
36
|
+
*,
|
|
37
|
+
metadatas: Sequence[dict[str, Any] | None] | None = None,
|
|
38
|
+
ids: Sequence[str] | None = None,
|
|
39
|
+
vectors: Sequence[Sequence[float]] | None = None,
|
|
40
|
+
ttl_seconds: int = 0,
|
|
41
|
+
) -> list[str]:
|
|
42
|
+
text_list = list(texts)
|
|
43
|
+
if not text_list:
|
|
44
|
+
return []
|
|
45
|
+
|
|
46
|
+
if vectors is None:
|
|
47
|
+
if self.embed_fn is None:
|
|
48
|
+
raise ValueError("either embed_fn or explicit vectors must be provided")
|
|
49
|
+
vec_list = list(self.embed_fn(text_list))
|
|
50
|
+
else:
|
|
51
|
+
vec_list = list(vectors)
|
|
52
|
+
|
|
53
|
+
if len(vec_list) != len(text_list):
|
|
54
|
+
raise ValueError(f"vectors length ({len(vec_list)}) != texts length ({len(text_list)})")
|
|
55
|
+
|
|
56
|
+
id_list = list(ids) if ids is not None else [str(uuid.uuid4()) for _ in text_list]
|
|
57
|
+
if len(id_list) != len(text_list):
|
|
58
|
+
raise ValueError(f"ids length ({len(id_list)}) != texts length ({len(text_list)})")
|
|
59
|
+
|
|
60
|
+
if metadatas is not None and len(metadatas) != len(text_list):
|
|
61
|
+
raise ValueError(f"metadatas length ({len(metadatas)}) != texts length ({len(text_list)})")
|
|
62
|
+
|
|
63
|
+
items: list[dict[str, Any]] = []
|
|
64
|
+
for i, text in enumerate(text_list):
|
|
65
|
+
item: dict[str, Any] = {
|
|
66
|
+
"id": id_list[i],
|
|
67
|
+
"vector": vec_list[i],
|
|
68
|
+
"doc": text,
|
|
69
|
+
}
|
|
70
|
+
if metadatas is not None and metadatas[i]:
|
|
71
|
+
item["meta"] = metadatas[i]
|
|
72
|
+
if ttl_seconds > 0:
|
|
73
|
+
item["ttl_seconds"] = ttl_seconds
|
|
74
|
+
items.append(item)
|
|
75
|
+
|
|
76
|
+
self.client.vadd_batch(self.index, items, metric=self.metric, index_type=self.index_type)
|
|
77
|
+
return id_list
|
|
78
|
+
|
|
79
|
+
def search(
|
|
80
|
+
self,
|
|
81
|
+
query: str | Sequence[float],
|
|
82
|
+
*,
|
|
83
|
+
top_k: int = 5,
|
|
84
|
+
filter: dict[str, Any] | None = None,
|
|
85
|
+
include_doc: bool = True,
|
|
86
|
+
include_meta: bool = True,
|
|
87
|
+
) -> list[VectorHit]:
|
|
88
|
+
if isinstance(query, str):
|
|
89
|
+
if self.embed_fn is None:
|
|
90
|
+
raise ValueError("embed_fn is required when querying with raw text")
|
|
91
|
+
vec = self.embed_fn([query])[0]
|
|
92
|
+
else:
|
|
93
|
+
vec = query
|
|
94
|
+
|
|
95
|
+
try:
|
|
96
|
+
return self.client.vsearch(
|
|
97
|
+
self.index,
|
|
98
|
+
vec,
|
|
99
|
+
top_k=top_k,
|
|
100
|
+
filter=filter,
|
|
101
|
+
include_doc=include_doc,
|
|
102
|
+
include_meta=include_meta,
|
|
103
|
+
)
|
|
104
|
+
except VernError as exc:
|
|
105
|
+
if exc.status_code == 404:
|
|
106
|
+
return []
|
|
107
|
+
raise
|
|
108
|
+
|
|
109
|
+
def delete(self, doc_id: str) -> bool:
|
|
110
|
+
return self.client.vdel(self.index, doc_id)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class SemanticCache:
|
|
114
|
+
"""Similarity-based LLM prompt/response cache with automatic TTL expiry."""
|
|
115
|
+
|
|
116
|
+
def __init__(
|
|
117
|
+
self,
|
|
118
|
+
client: Vern,
|
|
119
|
+
*,
|
|
120
|
+
embed_fn: EmbedFn,
|
|
121
|
+
index: str = "llm_cache",
|
|
122
|
+
threshold: float = 0.95,
|
|
123
|
+
ttl_seconds: int = 3600,
|
|
124
|
+
) -> None:
|
|
125
|
+
self.client = client
|
|
126
|
+
self.embed_fn = embed_fn
|
|
127
|
+
self.index = index
|
|
128
|
+
self.threshold = threshold
|
|
129
|
+
self.ttl_seconds = ttl_seconds
|
|
130
|
+
|
|
131
|
+
def lookup(self, prompt: str, *, filter: dict[str, Any] | None = None) -> str | None:
|
|
132
|
+
vec = self.embed_fn([prompt])[0]
|
|
133
|
+
try:
|
|
134
|
+
hits = self.client.vsearch(
|
|
135
|
+
self.index,
|
|
136
|
+
vec,
|
|
137
|
+
top_k=1,
|
|
138
|
+
filter=filter,
|
|
139
|
+
include_doc=True,
|
|
140
|
+
include_meta=False,
|
|
141
|
+
)
|
|
142
|
+
except VernError as exc:
|
|
143
|
+
if exc.status_code == 404:
|
|
144
|
+
return None
|
|
145
|
+
raise
|
|
146
|
+
if hits and hits[0].score >= self.threshold:
|
|
147
|
+
return hits[0].doc
|
|
148
|
+
return None
|
|
149
|
+
|
|
150
|
+
def store(
|
|
151
|
+
self,
|
|
152
|
+
prompt: str,
|
|
153
|
+
response: str,
|
|
154
|
+
*,
|
|
155
|
+
meta: dict[str, Any] | None = None,
|
|
156
|
+
ttl_seconds: int | None = None,
|
|
157
|
+
) -> str:
|
|
158
|
+
vec = self.embed_fn([prompt])[0]
|
|
159
|
+
entry_id = str(uuid.uuid4())
|
|
160
|
+
ttl = self.ttl_seconds if ttl_seconds is None else ttl_seconds
|
|
161
|
+
self.client.vadd(
|
|
162
|
+
self.index,
|
|
163
|
+
entry_id,
|
|
164
|
+
vec,
|
|
165
|
+
meta=meta,
|
|
166
|
+
doc=response,
|
|
167
|
+
ttl_seconds=ttl,
|
|
168
|
+
metric="cosine",
|
|
169
|
+
)
|
|
170
|
+
return entry_id
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class ConversationMemory:
|
|
174
|
+
"""Chronologically ordered session/thread chat history stored by KV prefix."""
|
|
175
|
+
|
|
176
|
+
def __init__(
|
|
177
|
+
self,
|
|
178
|
+
client: Vern,
|
|
179
|
+
session_id: str,
|
|
180
|
+
*,
|
|
181
|
+
namespace: str = "chat",
|
|
182
|
+
ttl_seconds: int = 0,
|
|
183
|
+
) -> None:
|
|
184
|
+
self.client = client
|
|
185
|
+
self.session_id = session_id
|
|
186
|
+
self.prefix = f"{namespace}:{session_id}:"
|
|
187
|
+
self.ttl_seconds = ttl_seconds
|
|
188
|
+
self._seq = 0
|
|
189
|
+
|
|
190
|
+
def append(self, role: str, content: str, *, meta: dict[str, Any] | None = None) -> str:
|
|
191
|
+
self._seq += 1
|
|
192
|
+
ts_ms = int(time.time() * 1000)
|
|
193
|
+
key = f"{self.prefix}{ts_ms:016d}:{self._seq:06d}"
|
|
194
|
+
record = {
|
|
195
|
+
"role": role,
|
|
196
|
+
"content": content,
|
|
197
|
+
"ts_ms": ts_ms,
|
|
198
|
+
"meta": meta or {},
|
|
199
|
+
}
|
|
200
|
+
self.client.put(key, json.dumps(record), ttl_seconds=self.ttl_seconds)
|
|
201
|
+
return key
|
|
202
|
+
|
|
203
|
+
def messages(self, *, limit: int = 100, offset: int = 0) -> list[dict[str, Any]]:
|
|
204
|
+
rows = self.client.scan(prefix=self.prefix, limit=limit, offset=offset)
|
|
205
|
+
out: list[dict[str, Any]] = []
|
|
206
|
+
for _, raw in rows:
|
|
207
|
+
assert isinstance(raw, str)
|
|
208
|
+
out.append(json.loads(raw))
|
|
209
|
+
return out
|
|
210
|
+
|
|
211
|
+
def clear(self) -> int:
|
|
212
|
+
rows = self.client.scan(prefix=self.prefix, limit=10000)
|
|
213
|
+
if not rows:
|
|
214
|
+
return 0
|
|
215
|
+
ops = [{"op": "delete", "key": k} for k, _ in rows]
|
|
216
|
+
return self.client.batch(ops)
|
vernkv/client.py
ADDED
|
@@ -0,0 +1,782 @@
|
|
|
1
|
+
"""Core Vern client with zero-dep RESP2 binary fast path & HTTP fallback."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import http.client
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import signal
|
|
11
|
+
import socket
|
|
12
|
+
import struct
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import threading
|
|
16
|
+
import urllib.parse
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Sequence
|
|
20
|
+
|
|
21
|
+
from ._binary import resolve_server_binary
|
|
22
|
+
|
|
23
|
+
_READY_RE = re.compile(r"VERNKV_READY\s+resp=(\S*)\s+http=(\S+)")
|
|
24
|
+
_MAX_HTTP_BATCH_BYTES = 8 * 1024 * 1024
|
|
25
|
+
_MAX_RESP_PIPELINE_ITEMS = 256
|
|
26
|
+
_MAX_RESP_PIPELINE_BYTES = 4 * 1024 * 1024
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class VernError(RuntimeError):
|
|
30
|
+
"""Raised when Vern returns an API error or server lifecycle fails."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, message: str, status_code: int | None = None) -> None:
|
|
33
|
+
super().__init__(message)
|
|
34
|
+
self.status_code = status_code
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
VernKVError = VernError
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _RESPServerError(VernError):
|
|
41
|
+
"""Error frame returned by the RESP2 server (stream remains synchronized)."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class VectorHit:
|
|
46
|
+
"""Single vector similarity search result."""
|
|
47
|
+
|
|
48
|
+
id: str
|
|
49
|
+
score: float
|
|
50
|
+
meta: dict[str, Any] = field(default_factory=dict)
|
|
51
|
+
doc: str = ""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _RESPConn:
|
|
55
|
+
"""Persistent, TCP_NODELAY RESP2 connection using Python stdlib sockets."""
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
host: str,
|
|
60
|
+
port: int,
|
|
61
|
+
timeout: float,
|
|
62
|
+
username: str | None = None,
|
|
63
|
+
password: str | None = None,
|
|
64
|
+
) -> None:
|
|
65
|
+
self._sock = socket.create_connection((host, port), timeout=timeout)
|
|
66
|
+
try:
|
|
67
|
+
self._sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
68
|
+
self._rfile = self._sock.makefile("rb", buffering=65536)
|
|
69
|
+
if password is not None:
|
|
70
|
+
args: list[str | bytes] = ["AUTH", username, password] if username else ["AUTH", password]
|
|
71
|
+
self.execute(*args)
|
|
72
|
+
except Exception:
|
|
73
|
+
self.close()
|
|
74
|
+
raise
|
|
75
|
+
|
|
76
|
+
def close(self) -> None:
|
|
77
|
+
rfile = getattr(self, "_rfile", None)
|
|
78
|
+
if rfile is not None:
|
|
79
|
+
try:
|
|
80
|
+
rfile.close()
|
|
81
|
+
except Exception:
|
|
82
|
+
pass
|
|
83
|
+
self._rfile = None
|
|
84
|
+
sock = getattr(self, "_sock", None)
|
|
85
|
+
if sock is not None:
|
|
86
|
+
try:
|
|
87
|
+
sock.close()
|
|
88
|
+
except Exception:
|
|
89
|
+
pass
|
|
90
|
+
self._sock = None
|
|
91
|
+
|
|
92
|
+
def execute(self, *args: str | bytes) -> Any:
|
|
93
|
+
return self.pipeline([args])[0]
|
|
94
|
+
|
|
95
|
+
def pipeline(self, cmds: Sequence[Sequence[str | bytes]]) -> list[Any]:
|
|
96
|
+
if not cmds:
|
|
97
|
+
return []
|
|
98
|
+
payload = b"".join(_encode_resp_cmd(cmd) for cmd in cmds)
|
|
99
|
+
self._sock.sendall(payload)
|
|
100
|
+
|
|
101
|
+
results: list[Any] = [None] * len(cmds)
|
|
102
|
+
first_server_err: _RESPServerError | None = None
|
|
103
|
+
for idx in range(len(cmds)):
|
|
104
|
+
try:
|
|
105
|
+
results[idx] = _read_resp_reply(self._rfile)
|
|
106
|
+
except _RESPServerError as exc:
|
|
107
|
+
if first_server_err is None:
|
|
108
|
+
first_server_err = exc
|
|
109
|
+
if first_server_err is not None:
|
|
110
|
+
raise first_server_err
|
|
111
|
+
return results
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class Vern:
|
|
115
|
+
"""Thread-safe Vern client using binary RESP2 TCP when available and HTTP JSON fallback."""
|
|
116
|
+
|
|
117
|
+
def __init__(
|
|
118
|
+
self,
|
|
119
|
+
url: str = "http://127.0.0.1:8080",
|
|
120
|
+
*,
|
|
121
|
+
resp_addr: str | None = None,
|
|
122
|
+
username: str | None = None,
|
|
123
|
+
password: str | None = None,
|
|
124
|
+
timeout: float = 15.0,
|
|
125
|
+
_proc: subprocess.Popen[str] | None = None,
|
|
126
|
+
) -> None:
|
|
127
|
+
parsed = urllib.parse.urlparse(url)
|
|
128
|
+
if parsed.scheme not in ("http", "https") or not parsed.hostname:
|
|
129
|
+
raise ValueError(f"invalid Vern URL: {url!r}")
|
|
130
|
+
|
|
131
|
+
self.url = url.rstrip("/")
|
|
132
|
+
self.resp_addr = resp_addr or None
|
|
133
|
+
self._resp_host: str | None = None
|
|
134
|
+
self._resp_port: int | None = None
|
|
135
|
+
if self.resp_addr:
|
|
136
|
+
rhost, rport = self.resp_addr.rsplit(":", 1)
|
|
137
|
+
self._resp_host = rhost
|
|
138
|
+
self._resp_port = int(rport)
|
|
139
|
+
|
|
140
|
+
self._scheme = parsed.scheme
|
|
141
|
+
self._host = parsed.hostname
|
|
142
|
+
self._port = parsed.port or (443 if self._scheme == "https" else 80)
|
|
143
|
+
self._base_path = parsed.path.rstrip("/")
|
|
144
|
+
self._username = username
|
|
145
|
+
self._password = password
|
|
146
|
+
self._timeout = timeout
|
|
147
|
+
self._proc = _proc
|
|
148
|
+
self._closed = False
|
|
149
|
+
self._local = threading.local()
|
|
150
|
+
self._conns_mu = threading.Lock()
|
|
151
|
+
self._open_http_conns: set[http.client.HTTPConnection] = set()
|
|
152
|
+
self._open_resp_conns: set[_RESPConn] = set()
|
|
153
|
+
|
|
154
|
+
self._auth_header: str | None = None
|
|
155
|
+
if password is not None:
|
|
156
|
+
user = username or ""
|
|
157
|
+
token = base64.b64encode(f"{user}:{password}".encode("utf-8")).decode("ascii")
|
|
158
|
+
self._auth_header = f"Basic {token}"
|
|
159
|
+
|
|
160
|
+
@classmethod
|
|
161
|
+
def local(
|
|
162
|
+
cls,
|
|
163
|
+
db_path: str | os.PathLike[str] = "./vern_data",
|
|
164
|
+
*,
|
|
165
|
+
sync_writes: bool = True,
|
|
166
|
+
enable_resp: bool = True,
|
|
167
|
+
username: str | None = None,
|
|
168
|
+
password: str | None = None,
|
|
169
|
+
server_bin: str | os.PathLike[str] | None = None,
|
|
170
|
+
startup_timeout: float = 10.0,
|
|
171
|
+
request_timeout: float = 15.0,
|
|
172
|
+
) -> Vern:
|
|
173
|
+
"""Start an isolated local vernkv-server on ephemeral localhost ports and return a client."""
|
|
174
|
+
binary = resolve_server_binary(server_bin)
|
|
175
|
+
db_dir = Path(db_path).expanduser().resolve()
|
|
176
|
+
db_dir.mkdir(parents=True, exist_ok=True)
|
|
177
|
+
|
|
178
|
+
cmd = [
|
|
179
|
+
str(binary),
|
|
180
|
+
"-db",
|
|
181
|
+
str(db_dir),
|
|
182
|
+
"-resp-addr",
|
|
183
|
+
"127.0.0.1:0" if enable_resp else "",
|
|
184
|
+
"-http-addr",
|
|
185
|
+
"127.0.0.1:0",
|
|
186
|
+
f"-sync={'true' if sync_writes else 'false'}",
|
|
187
|
+
]
|
|
188
|
+
proc = subprocess.Popen(
|
|
189
|
+
cmd,
|
|
190
|
+
stdout=subprocess.PIPE,
|
|
191
|
+
stderr=subprocess.PIPE,
|
|
192
|
+
text=True,
|
|
193
|
+
bufsize=1,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
http_addr: str | None = None
|
|
197
|
+
bound_resp_addr: str | None = None
|
|
198
|
+
ready_err: list[str] = []
|
|
199
|
+
|
|
200
|
+
def _wait_ready() -> None:
|
|
201
|
+
nonlocal http_addr, bound_resp_addr
|
|
202
|
+
assert proc.stdout is not None
|
|
203
|
+
for line in proc.stdout:
|
|
204
|
+
m = _READY_RE.search(line)
|
|
205
|
+
if m:
|
|
206
|
+
bound_resp_addr = m.group(1) or None
|
|
207
|
+
http_addr = m.group(2)
|
|
208
|
+
break
|
|
209
|
+
|
|
210
|
+
t = threading.Thread(target=_wait_ready, daemon=True)
|
|
211
|
+
t.start()
|
|
212
|
+
t.join(timeout=startup_timeout)
|
|
213
|
+
|
|
214
|
+
if http_addr is None:
|
|
215
|
+
if proc.stderr is not None:
|
|
216
|
+
try:
|
|
217
|
+
if proc.poll() is not None:
|
|
218
|
+
ready_err.append(proc.stderr.read())
|
|
219
|
+
except Exception:
|
|
220
|
+
pass
|
|
221
|
+
_terminate_proc(proc)
|
|
222
|
+
detail = f": {''.join(ready_err).strip()}" if ready_err else ""
|
|
223
|
+
raise VernError(f"vernkv-server failed to start within {startup_timeout}s{detail}")
|
|
224
|
+
|
|
225
|
+
for stream in (proc.stdout, proc.stderr):
|
|
226
|
+
if stream is not None:
|
|
227
|
+
threading.Thread(target=_drain_stream, args=(stream,), daemon=True).start()
|
|
228
|
+
|
|
229
|
+
return cls(
|
|
230
|
+
f"http://{http_addr}",
|
|
231
|
+
resp_addr=bound_resp_addr,
|
|
232
|
+
username=username,
|
|
233
|
+
password=password,
|
|
234
|
+
timeout=request_timeout,
|
|
235
|
+
_proc=proc,
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
def close(self) -> None:
|
|
239
|
+
if self._closed:
|
|
240
|
+
return
|
|
241
|
+
self._closed = True
|
|
242
|
+
with self._conns_mu:
|
|
243
|
+
http_conns = list(self._open_http_conns)
|
|
244
|
+
resp_conns = list(self._open_resp_conns)
|
|
245
|
+
self._open_http_conns.clear()
|
|
246
|
+
self._open_resp_conns.clear()
|
|
247
|
+
for hc in http_conns:
|
|
248
|
+
try:
|
|
249
|
+
hc.close()
|
|
250
|
+
except Exception:
|
|
251
|
+
pass
|
|
252
|
+
for rc in resp_conns:
|
|
253
|
+
rc.close()
|
|
254
|
+
self._local.http_conn = None
|
|
255
|
+
self._local.resp_conn = None
|
|
256
|
+
if self._proc is not None:
|
|
257
|
+
_terminate_proc(self._proc)
|
|
258
|
+
self._proc = None
|
|
259
|
+
|
|
260
|
+
def __enter__(self) -> Vern:
|
|
261
|
+
return self
|
|
262
|
+
|
|
263
|
+
def __exit__(self, *_: Any) -> None:
|
|
264
|
+
self.close()
|
|
265
|
+
|
|
266
|
+
def _get_http_conn(self) -> http.client.HTTPConnection:
|
|
267
|
+
conn = getattr(self._local, "http_conn", None)
|
|
268
|
+
if conn is None:
|
|
269
|
+
if self._scheme == "https":
|
|
270
|
+
conn = http.client.HTTPSConnection(self._host, self._port, timeout=self._timeout)
|
|
271
|
+
else:
|
|
272
|
+
conn = http.client.HTTPConnection(self._host, self._port, timeout=self._timeout)
|
|
273
|
+
self._local.http_conn = conn
|
|
274
|
+
with self._conns_mu:
|
|
275
|
+
self._open_http_conns.add(conn)
|
|
276
|
+
return conn
|
|
277
|
+
|
|
278
|
+
def _get_resp_conn(self) -> _RESPConn:
|
|
279
|
+
assert self._resp_host is not None and self._resp_port is not None
|
|
280
|
+
conn = getattr(self._local, "resp_conn", None)
|
|
281
|
+
if conn is None:
|
|
282
|
+
conn = _RESPConn(
|
|
283
|
+
self._resp_host,
|
|
284
|
+
self._resp_port,
|
|
285
|
+
self._timeout,
|
|
286
|
+
username=self._username,
|
|
287
|
+
password=self._password,
|
|
288
|
+
)
|
|
289
|
+
self._local.resp_conn = conn
|
|
290
|
+
with self._conns_mu:
|
|
291
|
+
self._open_resp_conns.add(conn)
|
|
292
|
+
return conn
|
|
293
|
+
|
|
294
|
+
def _drop_resp_conn(self, conn: _RESPConn) -> None:
|
|
295
|
+
with self._conns_mu:
|
|
296
|
+
self._open_resp_conns.discard(conn)
|
|
297
|
+
conn.close()
|
|
298
|
+
if getattr(self._local, "resp_conn", None) is conn:
|
|
299
|
+
self._local.resp_conn = None
|
|
300
|
+
|
|
301
|
+
def _resp_pipeline(self, cmds: Sequence[Sequence[str | bytes]]) -> list[Any]:
|
|
302
|
+
if self._closed:
|
|
303
|
+
raise VernError("Vern client is closed")
|
|
304
|
+
last_exc: Exception | None = None
|
|
305
|
+
for attempt in range(2):
|
|
306
|
+
conn = self._get_resp_conn()
|
|
307
|
+
try:
|
|
308
|
+
return conn.pipeline(cmds)
|
|
309
|
+
except _RESPServerError:
|
|
310
|
+
raise
|
|
311
|
+
except (OSError, EOFError, VernError) as exc:
|
|
312
|
+
last_exc = exc
|
|
313
|
+
self._drop_resp_conn(conn)
|
|
314
|
+
if attempt == 1:
|
|
315
|
+
raise VernError(f"RESP command failed: {exc}") from exc
|
|
316
|
+
raise VernError(f"RESP command failed: {last_exc}")
|
|
317
|
+
|
|
318
|
+
def _resp_exec(self, *args: str | bytes) -> Any:
|
|
319
|
+
return self._resp_pipeline([args])[0]
|
|
320
|
+
|
|
321
|
+
def _request(
|
|
322
|
+
self,
|
|
323
|
+
method: str,
|
|
324
|
+
path: str,
|
|
325
|
+
body_obj: Any = None,
|
|
326
|
+
*,
|
|
327
|
+
allow_404: bool = False,
|
|
328
|
+
) -> tuple[int, Any]:
|
|
329
|
+
if self._closed:
|
|
330
|
+
raise VernError("Vern client is closed")
|
|
331
|
+
|
|
332
|
+
raw_body: bytes | None = None
|
|
333
|
+
headers: dict[str, str] = {}
|
|
334
|
+
if body_obj is not None:
|
|
335
|
+
raw_body = json.dumps(body_obj, separators=(",", ":")).encode("utf-8")
|
|
336
|
+
headers["Content-Type"] = "application/json"
|
|
337
|
+
if self._auth_header is not None:
|
|
338
|
+
headers["Authorization"] = self._auth_header
|
|
339
|
+
|
|
340
|
+
full_path = f"{self._base_path}{path}"
|
|
341
|
+
last_exc: Exception | None = None
|
|
342
|
+
|
|
343
|
+
for attempt in range(2):
|
|
344
|
+
conn = self._get_http_conn()
|
|
345
|
+
try:
|
|
346
|
+
conn.request(method, full_path, body=raw_body, headers=headers)
|
|
347
|
+
resp = conn.getresponse()
|
|
348
|
+
data = resp.read()
|
|
349
|
+
parsed = json.loads(data.decode("utf-8")) if data else None
|
|
350
|
+
if resp.status == 404 and allow_404:
|
|
351
|
+
return 404, parsed
|
|
352
|
+
if resp.status >= 400:
|
|
353
|
+
msg = parsed.get("error") if isinstance(parsed, dict) else data.decode("utf-8", "replace")
|
|
354
|
+
raise VernError(msg or f"HTTP {resp.status}", status_code=resp.status)
|
|
355
|
+
return resp.status, parsed
|
|
356
|
+
except (http.client.HTTPException, OSError) as exc:
|
|
357
|
+
last_exc = exc
|
|
358
|
+
with self._conns_mu:
|
|
359
|
+
self._open_http_conns.discard(conn)
|
|
360
|
+
try:
|
|
361
|
+
conn.close()
|
|
362
|
+
except Exception:
|
|
363
|
+
pass
|
|
364
|
+
self._local.http_conn = None
|
|
365
|
+
if attempt == 1:
|
|
366
|
+
raise VernError(f"request {method} {path} failed: {exc}") from exc
|
|
367
|
+
|
|
368
|
+
raise VernError(f"request {method} {path} failed: {last_exc}")
|
|
369
|
+
|
|
370
|
+
# --- Health / Admin ---
|
|
371
|
+
|
|
372
|
+
def health(self) -> dict[str, Any]:
|
|
373
|
+
_, data = self._request("GET", "/health")
|
|
374
|
+
return data
|
|
375
|
+
|
|
376
|
+
def stats(self) -> dict[str, Any]:
|
|
377
|
+
_, data = self._request("GET", "/stats")
|
|
378
|
+
return data
|
|
379
|
+
|
|
380
|
+
def compact(self) -> dict[str, Any]:
|
|
381
|
+
_, data = self._request("POST", "/compact")
|
|
382
|
+
return data
|
|
383
|
+
|
|
384
|
+
# --- KV Operations (binary RESP2 when available, HTTP fallback otherwise) ---
|
|
385
|
+
|
|
386
|
+
def put(self, key: str, value: str | bytes, ttl_seconds: int = 0) -> None:
|
|
387
|
+
if self._resp_host is not None:
|
|
388
|
+
raw = bytes(value) if isinstance(value, (bytes, bytearray, memoryview)) else value.encode("utf-8")
|
|
389
|
+
if ttl_seconds > 0:
|
|
390
|
+
self._resp_exec("SET", key, raw, "EX", str(int(ttl_seconds)))
|
|
391
|
+
else:
|
|
392
|
+
self._resp_exec("SET", key, raw)
|
|
393
|
+
return
|
|
394
|
+
|
|
395
|
+
payload: dict[str, Any] = {}
|
|
396
|
+
if isinstance(value, (bytes, bytearray, memoryview)):
|
|
397
|
+
payload["value_b64"] = base64.b64encode(bytes(value)).decode("ascii")
|
|
398
|
+
else:
|
|
399
|
+
payload["value"] = value
|
|
400
|
+
if ttl_seconds > 0:
|
|
401
|
+
payload["ttl_seconds"] = int(ttl_seconds)
|
|
402
|
+
self._request("PUT", f"/kv/{urllib.parse.quote(key, safe='')}", payload)
|
|
403
|
+
|
|
404
|
+
def get(self, key: str, *, as_bytes: bool = False) -> str | bytes | None:
|
|
405
|
+
if self._resp_host is not None:
|
|
406
|
+
raw = self._resp_exec("GET", key)
|
|
407
|
+
if raw is None:
|
|
408
|
+
return None
|
|
409
|
+
return raw if as_bytes else raw.decode("utf-8", errors="replace")
|
|
410
|
+
|
|
411
|
+
q = "?encoding=base64" if as_bytes else ""
|
|
412
|
+
status, data = self._request("GET", f"/kv/{urllib.parse.quote(key, safe='')}{q}", allow_404=True)
|
|
413
|
+
if status == 404:
|
|
414
|
+
return None
|
|
415
|
+
return _decode_item_value(data, as_bytes=as_bytes)
|
|
416
|
+
|
|
417
|
+
def delete(self, key: str) -> None:
|
|
418
|
+
if self._resp_host is not None:
|
|
419
|
+
self._resp_exec("DEL", key)
|
|
420
|
+
return
|
|
421
|
+
self._request("DELETE", f"/kv/{urllib.parse.quote(key, safe='')}")
|
|
422
|
+
|
|
423
|
+
def batch(self, ops: Sequence[dict[str, Any]]) -> int:
|
|
424
|
+
encoded_ops: list[dict[str, Any]] = []
|
|
425
|
+
for op in ops:
|
|
426
|
+
kind = op["op"].lower()
|
|
427
|
+
entry: dict[str, Any] = {"op": kind, "key": op["key"]}
|
|
428
|
+
if kind == "put":
|
|
429
|
+
val = op.get("value", "")
|
|
430
|
+
if isinstance(val, (bytes, bytearray, memoryview)):
|
|
431
|
+
entry["value_b64"] = base64.b64encode(bytes(val)).decode("ascii")
|
|
432
|
+
else:
|
|
433
|
+
entry["value"] = val
|
|
434
|
+
if op.get("ttl_seconds", 0) > 0:
|
|
435
|
+
entry["ttl_seconds"] = int(op["ttl_seconds"])
|
|
436
|
+
encoded_ops.append(entry)
|
|
437
|
+
_, data = self._request("POST", "/batch", {"ops": encoded_ops})
|
|
438
|
+
return int(data.get("committed", 0))
|
|
439
|
+
|
|
440
|
+
def scan(
|
|
441
|
+
self,
|
|
442
|
+
*,
|
|
443
|
+
prefix: str = "",
|
|
444
|
+
start: str = "",
|
|
445
|
+
end: str = "",
|
|
446
|
+
limit: int = 100,
|
|
447
|
+
offset: int = 0,
|
|
448
|
+
as_bytes: bool = False,
|
|
449
|
+
) -> list[tuple[str, str | bytes]]:
|
|
450
|
+
params: dict[str, str] = {"limit": str(limit), "offset": str(offset)}
|
|
451
|
+
if prefix:
|
|
452
|
+
params["prefix"] = prefix
|
|
453
|
+
if start:
|
|
454
|
+
params["start"] = start
|
|
455
|
+
if end:
|
|
456
|
+
params["end"] = end
|
|
457
|
+
if as_bytes:
|
|
458
|
+
params["encoding"] = "base64"
|
|
459
|
+
qs = urllib.parse.urlencode(params)
|
|
460
|
+
_, data = self._request("GET", f"/scan?{qs}")
|
|
461
|
+
out: list[tuple[str, str | bytes]] = []
|
|
462
|
+
for item in data.get("items", []):
|
|
463
|
+
out.append((item["key"], _decode_item_value(item, as_bytes=as_bytes)))
|
|
464
|
+
return out
|
|
465
|
+
|
|
466
|
+
# --- Vector Operations (packed float32 RESP2 fast path + HTTP fallback) ---
|
|
467
|
+
|
|
468
|
+
def vadd(
|
|
469
|
+
self,
|
|
470
|
+
index: str,
|
|
471
|
+
id: str,
|
|
472
|
+
vector: Sequence[float],
|
|
473
|
+
*,
|
|
474
|
+
meta: dict[str, Any] | None = None,
|
|
475
|
+
doc: str = "",
|
|
476
|
+
ttl_seconds: int = 0,
|
|
477
|
+
metric: str = "",
|
|
478
|
+
index_type: str = "",
|
|
479
|
+
) -> int:
|
|
480
|
+
item: dict[str, Any] = {"id": id, "vector": vector}
|
|
481
|
+
if meta:
|
|
482
|
+
item["meta"] = meta
|
|
483
|
+
if doc:
|
|
484
|
+
item["doc"] = doc
|
|
485
|
+
if ttl_seconds > 0:
|
|
486
|
+
item["ttl_seconds"] = int(ttl_seconds)
|
|
487
|
+
return self.vadd_batch(index, [item], metric=metric, index_type=index_type)
|
|
488
|
+
|
|
489
|
+
def vadd_batch(
|
|
490
|
+
self,
|
|
491
|
+
index: str,
|
|
492
|
+
items: Sequence[dict[str, Any]],
|
|
493
|
+
*,
|
|
494
|
+
metric: str = "",
|
|
495
|
+
index_type: str = "",
|
|
496
|
+
) -> int:
|
|
497
|
+
if not items:
|
|
498
|
+
return 0
|
|
499
|
+
if self._resp_host is not None:
|
|
500
|
+
return self._vadd_batch_resp(index, items, metric=metric, index_type=index_type)
|
|
501
|
+
return self._vadd_batch_http(index, items, metric=metric, index_type=index_type)
|
|
502
|
+
|
|
503
|
+
def _vadd_batch_resp(
|
|
504
|
+
self,
|
|
505
|
+
index: str,
|
|
506
|
+
items: Sequence[dict[str, Any]],
|
|
507
|
+
*,
|
|
508
|
+
metric: str = "",
|
|
509
|
+
index_type: str = "",
|
|
510
|
+
) -> int:
|
|
511
|
+
total_added = 0
|
|
512
|
+
cmds: list[list[str | bytes]] = []
|
|
513
|
+
approx_bytes = 0
|
|
514
|
+
|
|
515
|
+
for raw in items:
|
|
516
|
+
packed = _pack_f32(raw["vector"])
|
|
517
|
+
cmd: list[str | bytes] = ["VADD", index, raw["id"], packed]
|
|
518
|
+
if metric:
|
|
519
|
+
cmd.extend(("METRIC", metric))
|
|
520
|
+
if index_type:
|
|
521
|
+
cmd.extend(("TYPE", index_type))
|
|
522
|
+
meta = raw.get("meta")
|
|
523
|
+
if meta:
|
|
524
|
+
cmd.extend(("META", json.dumps(meta, separators=(",", ":"))))
|
|
525
|
+
doc = raw.get("doc")
|
|
526
|
+
if doc:
|
|
527
|
+
cmd.extend(("DOC", doc))
|
|
528
|
+
ttl = raw.get("ttl_seconds", 0)
|
|
529
|
+
if ttl > 0:
|
|
530
|
+
cmd.extend(("EX", str(int(ttl))))
|
|
531
|
+
|
|
532
|
+
est = 64 + len(packed) + len(doc or "") * 2
|
|
533
|
+
if cmds and (len(cmds) >= _MAX_RESP_PIPELINE_ITEMS or approx_bytes + est > _MAX_RESP_PIPELINE_BYTES):
|
|
534
|
+
self._resp_pipeline(cmds)
|
|
535
|
+
total_added += len(cmds)
|
|
536
|
+
cmds = []
|
|
537
|
+
approx_bytes = 0
|
|
538
|
+
cmds.append(cmd)
|
|
539
|
+
approx_bytes += est
|
|
540
|
+
|
|
541
|
+
if cmds:
|
|
542
|
+
self._resp_pipeline(cmds)
|
|
543
|
+
total_added += len(cmds)
|
|
544
|
+
return total_added
|
|
545
|
+
|
|
546
|
+
def _vadd_batch_http(
|
|
547
|
+
self,
|
|
548
|
+
index: str,
|
|
549
|
+
items: Sequence[dict[str, Any]],
|
|
550
|
+
*,
|
|
551
|
+
metric: str = "",
|
|
552
|
+
index_type: str = "",
|
|
553
|
+
) -> int:
|
|
554
|
+
total_added = 0
|
|
555
|
+
chunk: list[dict[str, Any]] = []
|
|
556
|
+
approx_bytes = 0
|
|
557
|
+
path = f"/vectors/{urllib.parse.quote(index, safe='')}/add"
|
|
558
|
+
|
|
559
|
+
def _flush() -> None:
|
|
560
|
+
nonlocal total_added, chunk, approx_bytes
|
|
561
|
+
if not chunk:
|
|
562
|
+
return
|
|
563
|
+
payload: dict[str, Any] = {"items": chunk}
|
|
564
|
+
if metric:
|
|
565
|
+
payload["metric"] = metric
|
|
566
|
+
if index_type:
|
|
567
|
+
payload["type"] = index_type
|
|
568
|
+
_, data = self._request("POST", path, payload)
|
|
569
|
+
total_added += int(data.get("added", len(chunk)))
|
|
570
|
+
chunk = []
|
|
571
|
+
approx_bytes = 0
|
|
572
|
+
|
|
573
|
+
for raw in items:
|
|
574
|
+
norm = {
|
|
575
|
+
"id": raw["id"],
|
|
576
|
+
"vector": _to_float_list(raw["vector"]),
|
|
577
|
+
}
|
|
578
|
+
if raw.get("meta"):
|
|
579
|
+
norm["meta"] = raw["meta"]
|
|
580
|
+
if raw.get("doc"):
|
|
581
|
+
norm["doc"] = raw["doc"]
|
|
582
|
+
if raw.get("ttl_seconds", 0) > 0:
|
|
583
|
+
norm["ttl_seconds"] = int(raw["ttl_seconds"])
|
|
584
|
+
est = 64 + len(norm["vector"]) * 12 + len(norm.get("doc", "")) * 2
|
|
585
|
+
if chunk and (approx_bytes + est > _MAX_HTTP_BATCH_BYTES or len(chunk) >= 512):
|
|
586
|
+
_flush()
|
|
587
|
+
chunk.append(norm)
|
|
588
|
+
approx_bytes += est
|
|
589
|
+
|
|
590
|
+
_flush()
|
|
591
|
+
return total_added
|
|
592
|
+
|
|
593
|
+
def vsearch(
|
|
594
|
+
self,
|
|
595
|
+
index: str,
|
|
596
|
+
vector: Sequence[float],
|
|
597
|
+
*,
|
|
598
|
+
top_k: int = 10,
|
|
599
|
+
filter: dict[str, Any] | None = None,
|
|
600
|
+
include_doc: bool = True,
|
|
601
|
+
include_meta: bool = True,
|
|
602
|
+
) -> list[VectorHit]:
|
|
603
|
+
if self._resp_host is not None:
|
|
604
|
+
cmd: list[str | bytes] = ["VSEARCH", index, _pack_f32(vector), "TOP", str(int(top_k))]
|
|
605
|
+
if filter:
|
|
606
|
+
cmd.extend(("FILTER", json.dumps(filter, separators=(",", ":"))))
|
|
607
|
+
if include_meta:
|
|
608
|
+
cmd.append("WITHMETA")
|
|
609
|
+
if include_doc:
|
|
610
|
+
cmd.append("WITHDOC")
|
|
611
|
+
rows = self._resp_exec(*cmd)
|
|
612
|
+
hits: list[VectorHit] = []
|
|
613
|
+
for row in rows or ():
|
|
614
|
+
pos = 2
|
|
615
|
+
meta: dict[str, Any] = {}
|
|
616
|
+
doc = ""
|
|
617
|
+
if include_meta:
|
|
618
|
+
raw_meta = row[pos]
|
|
619
|
+
if raw_meta:
|
|
620
|
+
meta = json.loads(raw_meta.decode("utf-8"))
|
|
621
|
+
pos += 1
|
|
622
|
+
if include_doc:
|
|
623
|
+
raw_doc = row[pos]
|
|
624
|
+
if raw_doc:
|
|
625
|
+
doc = raw_doc.decode("utf-8", errors="replace")
|
|
626
|
+
hits.append(
|
|
627
|
+
VectorHit(
|
|
628
|
+
id=row[0].decode("utf-8"),
|
|
629
|
+
score=float(row[1]),
|
|
630
|
+
meta=meta,
|
|
631
|
+
doc=doc,
|
|
632
|
+
)
|
|
633
|
+
)
|
|
634
|
+
return hits
|
|
635
|
+
|
|
636
|
+
payload: dict[str, Any] = {
|
|
637
|
+
"vector": _to_float_list(vector),
|
|
638
|
+
"top_k": int(top_k),
|
|
639
|
+
"include_doc": bool(include_doc),
|
|
640
|
+
"include_meta": bool(include_meta),
|
|
641
|
+
}
|
|
642
|
+
if filter:
|
|
643
|
+
payload["filter"] = filter
|
|
644
|
+
path = f"/vectors/{urllib.parse.quote(index, safe='')}/search"
|
|
645
|
+
_, data = self._request("POST", path, payload)
|
|
646
|
+
hits = []
|
|
647
|
+
for row in data.get("results") or []:
|
|
648
|
+
hits.append(
|
|
649
|
+
VectorHit(
|
|
650
|
+
id=row["id"],
|
|
651
|
+
score=float(row["score"]),
|
|
652
|
+
meta=row.get("meta") or {},
|
|
653
|
+
doc=row.get("doc") or "",
|
|
654
|
+
)
|
|
655
|
+
)
|
|
656
|
+
return hits
|
|
657
|
+
|
|
658
|
+
def vdel(self, index: str, id: str) -> bool:
|
|
659
|
+
if self._resp_host is not None:
|
|
660
|
+
return bool(self._resp_exec("VDEL", index, id))
|
|
661
|
+
idx_q = urllib.parse.quote(index, safe="")
|
|
662
|
+
id_q = urllib.parse.quote(id, safe="")
|
|
663
|
+
_, data = self._request("DELETE", f"/vectors/{idx_q}/{id_q}")
|
|
664
|
+
return bool(data.get("deleted", False))
|
|
665
|
+
|
|
666
|
+
def vinfo(self, index: str | None = None) -> dict[str, Any] | list[dict[str, Any]] | None:
|
|
667
|
+
if index is None:
|
|
668
|
+
_, data = self._request("GET", "/vectors")
|
|
669
|
+
return data.get("indexes", [])
|
|
670
|
+
status, data = self._request("GET", f"/vectors/{urllib.parse.quote(index, safe='')}", allow_404=True)
|
|
671
|
+
if status == 404:
|
|
672
|
+
return None
|
|
673
|
+
return data
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
VernKV = Vern
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def _pack_f32(vec: Any) -> bytes:
|
|
680
|
+
if sys.byteorder == "little":
|
|
681
|
+
dtype = getattr(vec, "dtype", None)
|
|
682
|
+
if getattr(dtype, "str", None) == "<f4" and getattr(vec, "ndim", 0) == 1:
|
|
683
|
+
flags = getattr(vec, "flags", None)
|
|
684
|
+
if flags is not None and flags["C_CONTIGUOUS"]:
|
|
685
|
+
return vec.tobytes()
|
|
686
|
+
n = len(vec)
|
|
687
|
+
if n == 0:
|
|
688
|
+
raise VernError("vector must not be empty")
|
|
689
|
+
return struct.pack(f"<{n}f", *vec)
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def _to_float_list(vec: Any) -> list[float]:
|
|
693
|
+
if hasattr(vec, "tolist"):
|
|
694
|
+
return [float(x) for x in vec.tolist()]
|
|
695
|
+
return [float(x) for x in vec]
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def _encode_resp_cmd(parts: Sequence[str | bytes]) -> bytes:
|
|
699
|
+
out = [f"*{len(parts)}\r\n".encode("ascii")]
|
|
700
|
+
for part in parts:
|
|
701
|
+
b = bytes(part) if isinstance(part, (bytes, bytearray, memoryview)) else str(part).encode("utf-8")
|
|
702
|
+
out.append(f"${len(b)}\r\n".encode("ascii"))
|
|
703
|
+
out.append(b)
|
|
704
|
+
out.append(b"\r\n")
|
|
705
|
+
return b"".join(out)
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def _read_exact(rfile: Any, n: int) -> bytes:
|
|
709
|
+
buf = rfile.read(n)
|
|
710
|
+
if buf is None or len(buf) != n:
|
|
711
|
+
raise EOFError("unexpected EOF from Vern RESP2 connection")
|
|
712
|
+
return buf
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def _read_resp_reply(rfile: Any) -> Any:
|
|
716
|
+
line = rfile.readline()
|
|
717
|
+
if not line or not line.endswith(b"\r\n"):
|
|
718
|
+
raise EOFError("unexpected EOF reading RESP2 header")
|
|
719
|
+
prefix = line[:1]
|
|
720
|
+
body = line[1:-2]
|
|
721
|
+
if prefix == b"+":
|
|
722
|
+
return body.decode("utf-8", errors="replace")
|
|
723
|
+
if prefix == b"-":
|
|
724
|
+
msg = body.decode("utf-8", errors="replace")
|
|
725
|
+
clean = msg[4:] if msg.startswith("ERR ") else msg
|
|
726
|
+
status = 404 if "not found" in clean.lower() else None
|
|
727
|
+
raise _RESPServerError(clean, status_code=status)
|
|
728
|
+
if prefix == b":":
|
|
729
|
+
return int(body)
|
|
730
|
+
if prefix == b"$":
|
|
731
|
+
size = int(body)
|
|
732
|
+
if size < 0:
|
|
733
|
+
return None
|
|
734
|
+
data = _read_exact(rfile, size)
|
|
735
|
+
if _read_exact(rfile, 2) != b"\r\n":
|
|
736
|
+
raise VernError("malformed RESP2 bulk trailer")
|
|
737
|
+
return data
|
|
738
|
+
if prefix == b"*":
|
|
739
|
+
count = int(body)
|
|
740
|
+
if count < 0:
|
|
741
|
+
return None
|
|
742
|
+
return [_read_resp_reply(rfile) for _ in range(count)]
|
|
743
|
+
raise VernError(f"unsupported RESP2 prefix: {prefix!r}")
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def _decode_item_value(item: dict[str, Any], *, as_bytes: bool) -> str | bytes:
|
|
747
|
+
if "value_b64" in item and item["value_b64"] is not None:
|
|
748
|
+
raw = base64.b64decode(item["value_b64"])
|
|
749
|
+
return raw if as_bytes else raw.decode("utf-8", errors="replace")
|
|
750
|
+
val = item.get("value", "")
|
|
751
|
+
return val.encode("utf-8") if as_bytes else val
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def _drain_stream(stream: Any) -> None:
|
|
755
|
+
try:
|
|
756
|
+
for _ in stream:
|
|
757
|
+
pass
|
|
758
|
+
except Exception:
|
|
759
|
+
pass
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def _terminate_proc(proc: subprocess.Popen[str]) -> None:
|
|
763
|
+
try:
|
|
764
|
+
if proc.poll() is None:
|
|
765
|
+
try:
|
|
766
|
+
sig = signal.SIGTERM if os.name == "nt" else signal.SIGINT
|
|
767
|
+
proc.send_signal(sig)
|
|
768
|
+
proc.wait(timeout=5)
|
|
769
|
+
except Exception:
|
|
770
|
+
try:
|
|
771
|
+
proc.terminate()
|
|
772
|
+
proc.wait(timeout=2)
|
|
773
|
+
except Exception:
|
|
774
|
+
proc.kill()
|
|
775
|
+
proc.wait(timeout=2)
|
|
776
|
+
finally:
|
|
777
|
+
for stream in (proc.stdout, proc.stderr, proc.stdin):
|
|
778
|
+
if stream is not None:
|
|
779
|
+
try:
|
|
780
|
+
stream.close()
|
|
781
|
+
except Exception:
|
|
782
|
+
pass
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: vernkv
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Zero-dependency Python SDK & high-speed local vector RAG database powered by VernKV
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
Provides-Extra: dev
|
|
8
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# *VernKV*
|
|
12
|
+
|
|
13
|
+
[](https://pkg.go.dev/github.com/ver1619/VERN_KV)
|
|
14
|
+

|
|
15
|
+

|
|
16
|
+
[](notes/index.md)
|
|
17
|
+

|
|
18
|
+
[](LICENSE)
|
|
19
|
+
|
|
20
|
+
<p align="center">
|
|
21
|
+
<img
|
|
22
|
+
src="./logo.jpg"
|
|
23
|
+
alt="VernKV logo"
|
|
24
|
+
width="300"
|
|
25
|
+
>
|
|
26
|
+
</p>
|
|
27
|
+
|
|
28
|
+
An embeddable, pure-Go **LSM-Tree Key-Value & Vector Search Database** for **Linux and Windows**, with a CLI, HTTP/RESP2 server, and Python AI SDK (`vernkv`).
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Architecture
|
|
33
|
+
|
|
34
|
+
<div align="center">
|
|
35
|
+
|
|
36
|
+
```mermaid
|
|
37
|
+
flowchart TD
|
|
38
|
+
Clients["Clients (Python vernkv / CLI / HTTP REST / RESP2 / Go)"]
|
|
39
|
+
Server["Network Server (server/) & CLI (cmd/)"]
|
|
40
|
+
Engine["Core Engine (engine/) + Cross-Process LOCK + kv_vault"]
|
|
41
|
+
WAL["WAL Group Commit (wal/)"]
|
|
42
|
+
Mem["Memtable SkipList (memtable/)"]
|
|
43
|
+
Vec["Pure-Go Vector Index: Flat & HNSW (vector/)"]
|
|
44
|
+
SST["SSTables L0..L6 + Bloom Filters & Codecs (sstable/)"]
|
|
45
|
+
Man["Atomic MANIFEST (manifest/)"]
|
|
46
|
+
|
|
47
|
+
Clients --> Server
|
|
48
|
+
Server --> Engine
|
|
49
|
+
Server --> Vec
|
|
50
|
+
Engine --> WAL --> Mem
|
|
51
|
+
Vec -.->|"Atomic WriteBatch (_vec:, _vmeta:, _vdoc:)"| Engine
|
|
52
|
+
Mem -->|"Flush & Compaction"| SST --> Man
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
</div>
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## Quick Setup
|
|
60
|
+
|
|
61
|
+
> [!IMPORTANT]
|
|
62
|
+
> **Windows Users:** Our documentation and walkthrough commands use Linux/POSIX Bash syntax. Please run them inside **Git Bash** (included with [Git for Windows](https://gitforwindows.org/)).
|
|
63
|
+
|
|
64
|
+
- **Python (`pip` / `uv` — zero external deps, bundles server binary):**
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
pip install vernkv / uv add vernkv
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
- **Go (`v1.0.0` binaries or library import):**
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
go install github.com/ver1619/VERN_KV/cmd/vernkv-server@v1.0.0
|
|
74
|
+
go get github.com/ver1619/VERN_KV@v1.0.0
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
- **From GitHub Source:**
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
git clone https://github.com/ver1619/VERN_KV.git && cd VERN_KV
|
|
81
|
+
make build && make test
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
See [notes/vern/getting_started.md](notes/vern/getting_started.md) and [notes/vern/python_sdk.md](notes/vern/python_sdk.md) for prebuilt GitHub Release downloads, wheels, and full Windows instructions.
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## Project Structure
|
|
89
|
+
|
|
90
|
+
```text
|
|
91
|
+
VERN_KV/
|
|
92
|
+
├── cmd/ # CLI REPL (vernkv-cli) and network server (vernkv-server)
|
|
93
|
+
├── engine/ # LSM-Tree DB, group commit, compaction, LOCK, .config & kv_vault
|
|
94
|
+
├── memtable/ # Lock-free-read skip list write buffer
|
|
95
|
+
├── wal/ # Checksummed write-ahead log segments & truncation
|
|
96
|
+
├── sstable/ # Prefix-compressed data blocks, Bloom filters & compression codecs
|
|
97
|
+
├── manifest/ # Atomic MANIFEST journal
|
|
98
|
+
├── iter/ # Lazy stream operators & iterators
|
|
99
|
+
├── iterators/ # Multi-way merge & MVCC version filter iterators
|
|
100
|
+
├── query/ # Cursor bridge, KVStream & DBStats
|
|
101
|
+
├── vector/ # Pure-Go Flat & HNSW vector indexes + atomic LSM store
|
|
102
|
+
├── server/ # Redis RESP2 TCP & HTTP JSON REST handlers
|
|
103
|
+
├── sdk/python/ # Zero-dependency Python SDK (vernkv) & Linux/Windows wheel builder
|
|
104
|
+
├── tests/ # Integration, crash-recovery & determinism test suites
|
|
105
|
+
└── notes/ # Full architecture, developer, user & hands-on dev-test docs
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
## Documentation
|
|
111
|
+
|
|
112
|
+
Read the complete documentation starting at **[notes/index.md](notes/index.md)**:
|
|
113
|
+
|
|
114
|
+
| Section | Focus | Entry Point |
|
|
115
|
+
|---|---|---|
|
|
116
|
+
| **Architecture** | Storage engine, WAL/Memtable/SSTable/Manifest formats, network server, vector engine, iterators & caching | [notes/arch/](notes/index.md#1-system-architecture-notesarch) |
|
|
117
|
+
| **End-User & Python SDK** | Linux/Windows setup, Python SDK workflows, `kv_vault` credentials & `.config`, CLI reference, server & vector APIs | [notes/vern/](notes/index.md#3-end-user--python-sdk-guides-notesvern) |
|
|
118
|
+
| **Developer & Benchmarks** | Contributor workflow, `Makefile` & CI/CD releases, test matrix, and reproducible hardware benchmarks | [notes/developer/](notes/index.md#2-developer--benchmark-guides-notesdeveloper) |
|
|
119
|
+
| **Hands-On Walkthroughs** | Isolated sandbox CLI/server tests and dedicated `uv` Python AI test project | [notes/dev-test/vern.md](notes/dev-test/vern.md) · [notes/dev-test/vern_ai.md](notes/dev-test/vern_ai.md) |
|
|
120
|
+
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
## References
|
|
124
|
+
|
|
125
|
+
- **[ver1619/itFrame](https://github.com/ver1619/itFrame)** — Composable, lazy iterator framework in Go used for VernKV's stream query pipelines (`iter/` and `query/`).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
vernkv/__init__.py,sha256=llWUaX565B4YwIPRE6RyqrsVMaZIoAWKAAbroEnGKrs,378
|
|
2
|
+
vernkv/_binary.py,sha256=OKmzwbqWTLh0bhXHm4B5w-mmPbsG80QU5fo_2bRCIsM,2998
|
|
3
|
+
vernkv/ai.py,sha256=_057saqK7dSRrL5IyjxJWETe6Kb67FG2je1Obp53dM8,6593
|
|
4
|
+
vernkv/client.py,sha256=zV5cMBTLyIeseMGE3xZV9J0oRovkMwN6HqM7gGWYCYw,26642
|
|
5
|
+
vernkv/_bin/vernkv-server.exe,sha256=RbsUWljSTCp-RDS14bTO4pWRks3rky02JkMfqy3xpaA,6810624
|
|
6
|
+
vernkv-1.0.0.dist-info/entry_points.txt,sha256=2wR5wdYMDNesb_rhreoUbHRni1rLAdzdhKE6aZHsgFg,108
|
|
7
|
+
vernkv-1.0.0.dist-info/WHEEL,sha256=zsMHOzppUTzXwzDfJuTemP0mFqF4no2cRUU-ccpjWl8,95
|
|
8
|
+
vernkv-1.0.0.dist-info/METADATA,sha256=SW3COmP9-vpbUEJw_B-15rda6VbUhWrGiDsHslsquwc,5140
|
|
9
|
+
vernkv-1.0.0.dist-info/RECORD,,
|