skeg 0.3.0__py3-none-any.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.
skeg/__init__.py ADDED
@@ -0,0 +1,232 @@
1
+ """skeg-py: Python client for skeg.
2
+
3
+ Start here:
4
+
5
+ import skeg
6
+ with skeg.connect() as c: # RESP3, port 6379
7
+ c.set(b"hello", b"world")
8
+ c.vindex_create("notes", dim=1024) # kind defaults to tq2
9
+ c.vset("notes", 1, embedding, payload=b"chapter-3")
10
+ for hit in c.vsearch("notes", query, k=10, with_payload=True):
11
+ print(hit.id, hit.score, hit.payload)
12
+
13
+ RESP3 carries the full command surface. The native binary protocol is a
14
+ smaller set on port 7379, reachable when you want its lower framing
15
+ overhead:
16
+
17
+ from skeg import RespClient # RESP2/3 wire (port 6379), what connect() returns
18
+ from skeg import BinaryClient # native binary protocol (port 7379)
19
+ from skeg import client # binary protocol, PyO3 backend if installed
20
+
21
+ Wire formats (skeg binary protocol v1 and the RESP3 subset) are frozen
22
+ on the server side. The package is pure Python; the PyO3 backend
23
+ (`skeg._native`) is built separately and is not part of 0.8.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import errno
29
+ import os
30
+ import stat
31
+
32
+ from . import _wire
33
+ from .binary import BinaryClient, Hit, VectorBackend, VectorKind, VectorKindV2
34
+ from .config import Backend, IndexConfig, Kind, Metric, Persistence
35
+ from .errors import (
36
+ ConfigMismatch,
37
+ DescriptorCorrupt,
38
+ IdSpaceExhausted,
39
+ IncompleteCollection,
40
+ MappingCorrupt,
41
+ MappingIncomplete,
42
+ NotConnected,
43
+ NotSent,
44
+ OutcomeUnknown,
45
+ PipelineStopped,
46
+ ProtocolError,
47
+ ServerError,
48
+ SkegError,
49
+ StaleDescriptor,
50
+ StaleSession,
51
+ UnmanagedIndex,
52
+ Unresolved,
53
+ Unsupported,
54
+ )
55
+ from .collection import Batch, Collection, Match, Refused, Row, Unknown, Written
56
+ from .index import Index
57
+ from .resp import RespClient
58
+
59
+ # Backend selection for `client`: PyO3 if a build of it is installed and
60
+ # `prefer_native` holds, else pure Python.
61
+ try:
62
+ from ._native import BinaryClient as _NativeBinary # type: ignore
63
+
64
+ _HAS_NATIVE = True
65
+ except ImportError:
66
+ _HAS_NATIVE = False
67
+
68
+
69
+ def connect(
70
+ host: str = "127.0.0.1",
71
+ port: int = 6379,
72
+ *,
73
+ timeout: float = 5.0,
74
+ protocol: int = 3,
75
+ user: str | None = None,
76
+ password: str | None = None,
77
+ password_file: str | os.PathLike[str] | None = None,
78
+ ) -> RespClient:
79
+ """Open a RESP3 connection. **The recommended way into skeg.**
80
+
81
+ RESP3 carries the whole command surface - KV, vectors with payloads
82
+ and filters, bulk VMSET, tenancy, quotas, QoS. The native binary
83
+ protocol behind `client()` is a smaller set on a different port.
84
+
85
+ The connection is negotiated before it is handed back, so callers do
86
+ not have to remember to send HELLO. Pass `protocol=2` to stay on
87
+ RESP2, where RESP3-only reply types (doubles, maps) arrive in their
88
+ downgraded form.
89
+
90
+ Credentials log in with HELLO AUTH: `user` with `password` or
91
+ `password_file`. Without arguments, the CLI's `SKEG_CLIENT__USER` and
92
+ `SKEG_CLIENT__PASSWORD_FILE` are read. A password file follows the
93
+ CLI's rules: a regular file, not a symlink, no group or other
94
+ permission, at most 64 KiB, one trailing newline dropped, not empty.
95
+ A refused login closes the connection; no message carries the password.
96
+ """
97
+ if protocol not in (2, 3):
98
+ raise ValueError(f"protocol must be 2 or 3, got {protocol!r}")
99
+ auth = _credentials(user, password, password_file)
100
+ c = RespClient.connect(host, port, timeout=timeout)
101
+ try:
102
+ c.hello(protocol, auth=auth)
103
+ except BaseException:
104
+ c.close()
105
+ raise
106
+ return c
107
+
108
+
109
+ _SECRET_MAX = 64 * 1024
110
+
111
+
112
+ def _credentials(
113
+ user: str | None, password: str | None, password_file: object
114
+ ) -> tuple[str, str] | None:
115
+ if user is None and password is None and password_file is None:
116
+ user = os.environ.get("SKEG_CLIENT__USER")
117
+ password_file = os.environ.get("SKEG_CLIENT__PASSWORD_FILE")
118
+ if password is not None and password_file is not None:
119
+ raise ValueError("pass password or password_file, not both")
120
+ if password_file is not None:
121
+ password = _read_secret(os.fspath(password_file)) # type: ignore[arg-type]
122
+ if user is None and password is None:
123
+ return None
124
+ if not user:
125
+ raise ValueError("a password needs a user")
126
+ if not password:
127
+ raise ValueError(f"user {user!r} needs a password or a password_file")
128
+ return user, password
129
+
130
+
131
+ def _read_secret(path: str) -> str:
132
+ """The CLI's password file rules, checked on the opened descriptor."""
133
+ try:
134
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC)
135
+ except OSError as e:
136
+ if e.errno == errno.ELOOP:
137
+ raise ValueError(f"password file {path}: a symlink") from None
138
+ raise ValueError(f"password file {path}: {e.strerror}") from None
139
+ with os.fdopen(fd, "rb") as f:
140
+ st = os.fstat(f.fileno())
141
+ if not stat.S_ISREG(st.st_mode):
142
+ raise ValueError(f"password file {path}: not a regular file")
143
+ if st.st_mode & 0o077:
144
+ raise ValueError(
145
+ f"password file {path}: readable by group or others "
146
+ f"(mode {stat.S_IMODE(st.st_mode):o}); chmod 600"
147
+ )
148
+ raw = f.read(_SECRET_MAX + 1)
149
+ if len(raw) > _SECRET_MAX:
150
+ raise ValueError(f"password file {path}: over 64 KiB")
151
+ if raw.endswith(b"\n"):
152
+ raw = raw[:-1]
153
+ if not raw:
154
+ raise ValueError(f"password file {path}: empty")
155
+ try:
156
+ return raw.decode("utf-8")
157
+ except UnicodeDecodeError:
158
+ raise ValueError(f"password file {path}: not UTF-8") from None
159
+
160
+
161
+ def client(
162
+ addr: str = "127.0.0.1",
163
+ port: int = 7379,
164
+ *,
165
+ prefer_native: bool = True,
166
+ version: int = _wire.VERSION_V1,
167
+ ) -> BinaryClient:
168
+ """Open a **binary-protocol** connection with the best available backend.
169
+
170
+ This is the narrower door: the native wire has no payloads, no search
171
+ filters and no tenancy commands. For those - and for anything new -
172
+ use `skeg.connect()`, which speaks RESP3.
173
+
174
+ Reach for this one when you want the native wire specifically, e.g.
175
+ for its lower framing overhead on a hot KV path.
176
+
177
+ `prefer_native=False` forces the pure-Python implementation even when
178
+ the PyO3 backend is available (useful for benchmarks and to compare
179
+ the two paths under the same workload).
180
+
181
+ `version` picks the native frame version; both backends support v1
182
+ (the default) and v2. v2 is required for the TurboQuant kinds and for
183
+ `native_hello()`.
184
+ """
185
+ if prefer_native and _HAS_NATIVE:
186
+ return _NativeBinary.connect(addr, port, version=version) # type: ignore[no-any-return]
187
+ return BinaryClient.connect(addr, port, version=version)
188
+
189
+
190
+ __all__ = [
191
+ "Backend",
192
+ "Batch",
193
+ "BinaryClient",
194
+ "Collection",
195
+ "ConfigMismatch",
196
+ "DescriptorCorrupt",
197
+ "Hit",
198
+ "IdSpaceExhausted",
199
+ "IncompleteCollection",
200
+ "Index",
201
+ "IndexConfig",
202
+ "Kind",
203
+ "MappingCorrupt",
204
+ "MappingIncomplete",
205
+ "Match",
206
+ "Metric",
207
+ "Persistence",
208
+ "NotConnected",
209
+ "NotSent",
210
+ "OutcomeUnknown",
211
+ "PipelineStopped",
212
+ "Refused",
213
+ "ProtocolError",
214
+ "RespClient",
215
+ "Row",
216
+ "ServerError",
217
+ "SkegError",
218
+ "StaleDescriptor",
219
+ "StaleSession",
220
+ "Unknown",
221
+ "UnmanagedIndex",
222
+ "Unresolved",
223
+ "Unsupported",
224
+ "Written",
225
+ "VectorBackend",
226
+ "VectorKind",
227
+ "VectorKindV2",
228
+ "client",
229
+ "connect",
230
+ ]
231
+
232
+ __version__ = "0.3.0"
@@ -0,0 +1,142 @@
1
+ """Where a collection keeps its state in the KV space, and the records.
2
+
3
+ Every key starts with `PREFIX`, whose first bytes are not a payload marker
4
+ (the server refuses user keys at `\\x00vp`/`\\x00vq`). The server adds the
5
+ owner in front, so the client never builds a tenant prefix.
6
+
7
+ PREFIX + H(name) + b"/d" descriptor
8
+ PREFIX + H(name) + b"/i" init election
9
+ PREFIX + H(name) + b"/" + H(inc) + b"/c" id counter
10
+ PREFIX + H(name) + b"/" + H(inc) + b"/e/" + H(ext) id election
11
+ PREFIX + H(name) + b"/" + H(inc) + b"/f/" + H(ext) forward: ext -> id
12
+ PREFIX + H(name) + b"/" + H(inc) + b"/r/" + id reverse: id -> ext
13
+
14
+ H is the full SHA-256 in hex, so every part has a fixed length or is last.
15
+ Isolation from user keys is client-enforced: a raw client can write here.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import re
22
+
23
+ from .errors import MappingCorrupt
24
+
25
+ PREFIX = b"\x00skc/"
26
+ ID_MAX = 2**63 - 1
27
+ EXT_MAX = 1024
28
+
29
+
30
+ def _h(b: bytes) -> bytes:
31
+ return hashlib.sha256(b).hexdigest().encode()
32
+
33
+
34
+ class NameKeys:
35
+ """The keys of a collection name, shared by all its incarnations."""
36
+
37
+ def __init__(self, name: str) -> None:
38
+ self.prefix = PREFIX + _h(name.encode()) + b"/"
39
+ self.descriptor = self.prefix + b"d"
40
+ self.init = self.prefix + b"i"
41
+
42
+
43
+ class Keys(NameKeys):
44
+ """The keys of one collection incarnation."""
45
+
46
+ def __init__(self, name: str, incarnation: str) -> None:
47
+ super().__init__(name)
48
+ self._ns = self.prefix + _h(incarnation.encode()) + b"/"
49
+ self.counter = self._ns + b"c"
50
+
51
+ def election(self, ext: bytes) -> bytes:
52
+ return self._ns + b"e/" + _h(ext)
53
+
54
+ def forward(self, ext: bytes) -> bytes:
55
+ return self._ns + b"f/" + _h(ext)
56
+
57
+ def reverse(self, i: int) -> bytes:
58
+ return self._ns + b"r/" + str(i).encode()
59
+
60
+
61
+ _KEY = re.compile(
62
+ rb"\x00skc/([0-9a-f]{64})/(?:(d|i)|([0-9a-f]{64})/(?:(c)|(e|f)/([0-9a-f]{64})|(r)/([1-9][0-9]*)))"
63
+ )
64
+ _KINDS = {b"d": "descriptor", b"i": "init", b"c": "counter", b"e": "election",
65
+ b"f": "forward", b"r": "reverse"} # fmt: skip
66
+
67
+
68
+ def parse_key(key: bytes) -> tuple[str, str, str | None, str | None]:
69
+ """(kind, name hash, incarnation hash, ext hash or id); ValueError otherwise."""
70
+ m = _KEY.fullmatch(key)
71
+ if m is None:
72
+ raise ValueError(f"not a collection key: {key[:80]!r}")
73
+ name, top, inc, c, ef, ext, r, i = m.groups()
74
+ kind = _KINDS[top or c or ef or r]
75
+ arg = ext or i
76
+ return (
77
+ kind,
78
+ name.decode(),
79
+ inc.decode() if inc else None,
80
+ arg.decode() if arg else None,
81
+ )
82
+
83
+
84
+ def check_ext(ext: str) -> bytes:
85
+ """An external string id: 1-1024 bytes of UTF-8."""
86
+ if not isinstance(ext, str):
87
+ raise TypeError(f"external id must be str, got {type(ext).__name__}")
88
+ try:
89
+ b = ext.encode("utf-8")
90
+ except UnicodeEncodeError:
91
+ raise ValueError(f"external id {ext!r} is not valid UTF-8") from None
92
+ if not 1 <= len(b) <= EXT_MAX:
93
+ raise ValueError(f"external id: 1-{EXT_MAX} UTF-8 bytes, got {len(b)}")
94
+ return b
95
+
96
+
97
+ def check_id(i: object) -> int:
98
+ if isinstance(i, bool) or not isinstance(i, int):
99
+ raise TypeError(f"id must be int, got {type(i).__name__}")
100
+ if not 1 <= i <= ID_MAX:
101
+ raise ValueError(f"id {i} outside 1..2**63-1")
102
+ return i
103
+
104
+
105
+ # forward: b"F1" + id (8 bytes, big endian) + ext
106
+ # reverse: b"R1" + SHA-256(ext) (32 bytes) + ext
107
+
108
+
109
+ def encode_forward(i: int, ext: bytes) -> bytes:
110
+ return b"F1" + check_id(i).to_bytes(8, "big") + ext
111
+
112
+
113
+ def decode_forward(raw: bytes, ext: bytes) -> int:
114
+ if len(raw) < 11 or raw[:2] != b"F1":
115
+ raise MappingCorrupt(f"forward record malformed: {raw[:40]!r}")
116
+ i = int.from_bytes(raw[2:10], "big")
117
+ if not 1 <= i <= ID_MAX:
118
+ raise MappingCorrupt(f"forward record holds id {i}, outside 1..2**63-1")
119
+ if raw[10:] != ext:
120
+ raise MappingCorrupt(
121
+ f"forward record for {ext!r} holds another id: {raw[10:50]!r}"
122
+ )
123
+ return i
124
+
125
+
126
+ def encode_reverse(ext: bytes) -> bytes:
127
+ return b"R1" + hashlib.sha256(ext).digest() + ext
128
+
129
+
130
+ def decode_reverse(raw: bytes) -> bytes:
131
+ if len(raw) < 35 or raw[:2] != b"R1":
132
+ raise MappingCorrupt(f"reverse record malformed: {raw[:40]!r}")
133
+ ext = raw[34:]
134
+ if hashlib.sha256(ext).digest() != raw[2:34]:
135
+ raise MappingCorrupt("reverse record digest does not match its id")
136
+ if len(ext) > EXT_MAX:
137
+ raise MappingCorrupt(f"reverse record holds an id of {len(ext)} bytes")
138
+ try:
139
+ ext.decode("utf-8")
140
+ except UnicodeDecodeError:
141
+ raise MappingCorrupt(f"reverse record holds non-UTF-8 {ext[:40]!r}") from None
142
+ return ext
skeg/_descriptor.py ADDED
@@ -0,0 +1,121 @@
1
+ """The collection descriptor: canonical JSON, schema 1.
2
+
3
+ Decoding is strict. The size is checked before parsing. Duplicate keys,
4
+ floats, NaN, unknown or missing fields and an unknown schema are refused,
5
+ and so is any byte string that is not the canonical encoding of what it
6
+ decodes to, so a descriptor's SHA-256 identifies it. Unknown fields are
7
+ refused: schema 1 is closed, and a new field needs a new schema number.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from dataclasses import asdict, dataclass
14
+
15
+ from .config import Backend, Kind, Metric, Persistence, check_index_name
16
+ from .errors import DescriptorCorrupt
17
+
18
+ MAX_BYTES = 4096
19
+ SCHEMA = 1
20
+ INT_MAX = 2**31 - 1
21
+ ID_KINDS = ("string", "u64")
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Descriptor:
26
+ collection: str
27
+ vindex: str
28
+ incarnation: str
29
+ dim: int
30
+ kind: str
31
+ backend: str
32
+ persistence: str
33
+ l: int # noqa: E741 - the server's name
34
+ metric: str
35
+ id_kind: str
36
+ embedding_space: str
37
+
38
+
39
+ def _printable(field: str, v: object, top: int) -> None:
40
+ if not isinstance(v, str) or not 1 <= len(v) <= top:
41
+ raise DescriptorCorrupt(f"{field}: 1-{top} printable ASCII, got {v!r}")
42
+ if not all("!" <= ch <= "~" for ch in v):
43
+ raise DescriptorCorrupt(f"{field}: printable ASCII without spaces, got {v!r}")
44
+
45
+
46
+ def _int(field: str, v: object, low: int) -> None:
47
+ if isinstance(v, bool) or not isinstance(v, int) or not low <= v <= INT_MAX:
48
+ raise DescriptorCorrupt(f"{field}: an integer in {low}..{INT_MAX}, got {v!r}")
49
+
50
+
51
+ def _one_of(field: str, v: object, allowed: tuple[str, ...]) -> None:
52
+ if v not in allowed:
53
+ raise DescriptorCorrupt(f"{field}: one of {', '.join(allowed)}, got {v!r}")
54
+
55
+
56
+ def _check(d: Descriptor) -> None:
57
+ for field in ("collection", "vindex"):
58
+ try:
59
+ check_index_name(getattr(d, field))
60
+ except (TypeError, ValueError) as e:
61
+ raise DescriptorCorrupt(f"{field}: {e}") from None
62
+ _printable("incarnation", d.incarnation, 128)
63
+ _printable("embedding_space", d.embedding_space, 255)
64
+ _int("dim", d.dim, 1)
65
+ _int("l", d.l, 0)
66
+ _one_of("kind", d.kind, tuple(m.value for m in Kind))
67
+ _one_of("backend", d.backend, tuple(m.value for m in Backend))
68
+ _one_of("persistence", d.persistence, tuple(m.value for m in Persistence))
69
+ _one_of("metric", d.metric, tuple(m.value for m in Metric))
70
+ _one_of("id_kind", d.id_kind, ID_KINDS)
71
+
72
+
73
+ def encode(d: Descriptor) -> bytes:
74
+ _check(d)
75
+ out = json.dumps(
76
+ {"schema": SCHEMA, **asdict(d)}, sort_keys=True, separators=(",", ":")
77
+ )
78
+ return out.encode("ascii")
79
+
80
+
81
+ def _pairs(pairs: list[tuple[str, object]]) -> dict[str, object]:
82
+ out: dict[str, object] = {}
83
+ for k, v in pairs:
84
+ if k in out:
85
+ raise DescriptorCorrupt(f"duplicate key {k!r}")
86
+ out[k] = v
87
+ return out
88
+
89
+
90
+ def _no_float(s: str) -> object:
91
+ raise DescriptorCorrupt(f"a float in a descriptor: {s!r}")
92
+
93
+
94
+ def decode(raw: bytes) -> Descriptor:
95
+ if len(raw) > MAX_BYTES:
96
+ raise DescriptorCorrupt(f"descriptor of {len(raw)} bytes, over {MAX_BYTES}")
97
+ try:
98
+ obj = json.loads(
99
+ raw.decode("ascii"),
100
+ object_pairs_hook=_pairs,
101
+ parse_float=_no_float,
102
+ parse_constant=_no_float,
103
+ )
104
+ except (UnicodeDecodeError, ValueError) as e:
105
+ raise DescriptorCorrupt(f"descriptor is not JSON: {e}") from None
106
+ if not isinstance(obj, dict):
107
+ raise DescriptorCorrupt("descriptor is not a JSON object")
108
+ schema = obj.pop("schema", None)
109
+ if isinstance(schema, bool) or schema != SCHEMA or type(schema) is not int:
110
+ raise DescriptorCorrupt(f"unknown descriptor schema {schema!r}")
111
+ names = set(Descriptor.__dataclass_fields__)
112
+ for k in obj:
113
+ if k not in names:
114
+ raise DescriptorCorrupt(f"unknown field {k!r} in schema {SCHEMA}")
115
+ for k in names:
116
+ if k not in obj:
117
+ raise DescriptorCorrupt(f"missing field {k!r}")
118
+ d = Descriptor(**obj) # type: ignore[arg-type]
119
+ if encode(d) != raw:
120
+ raise DescriptorCorrupt("descriptor is not in canonical form")
121
+ return d
skeg/_id_map.py ADDED
@@ -0,0 +1,155 @@
1
+ """String ids to vector ids: the mapper as a state machine, without I/O.
2
+
3
+ Each machine is a generator that yields the store operation it needs
4
+ (`Get`, `Incr`, `Set`) and receives its reply; `run` drives one against a
5
+ store (a `RespClient` or its `bound()` view): each op knows its command. Tests step two machines by
6
+ hand to interleave them.
7
+
8
+ `assign(ext)`, one row per step:
9
+
10
+ | step | op | reply | next |
11
+ |------|------------------------|-------------------|------------------------------|
12
+ | 1 | GET forward(ext) | record | done: its id (ext compared) |
13
+ | | | none | 2 |
14
+ | 2 | INCR election(ext) | 1 | 3: this caller won |
15
+ | | | n > 1 | 5: someone else won |
16
+ | 3 | INCR counter | 1..2**63-1 | 4 (the id, never reused) |
17
+ | | | overflow refused | IdSpaceExhausted |
18
+ | 4 | SET reverse(id) | | then SET forward(ext): done |
19
+ | 5 | GET forward(ext), wait | record | done: its id |
20
+ | | | none, polls left | 5 |
21
+ | | | none, no polls | MappingIncomplete |
22
+
23
+ A failed op is thrown into the machine; it ends with that error, except
24
+ the server's overflow refusal on the counter. The server's INCR is i64 and
25
+ refuses past 2**63-1 without applying, which is the mapper's last id: the
26
+ counter stops there. A reply past it (a store that does not refuse) is
27
+ refused by the client too. Election and counter are
28
+ spent, so a retry is a loser: it waits for the forward record, and without
29
+ it reports the mapping incomplete. Only the election winner writes.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import time
35
+ from collections.abc import Callable, Generator
36
+ from dataclasses import dataclass
37
+ from typing import Any, Protocol
38
+
39
+ from ._collection_keys import ID_MAX, Keys, decode_forward, decode_reverse
40
+ from ._collection_keys import encode_forward, encode_reverse
41
+ from .errors import IdSpaceExhausted, MappingCorrupt, MappingIncomplete, ServerError
42
+
43
+
44
+ class Store(Protocol):
45
+ def get(self, key: bytes) -> bytes | None: ...
46
+ def set(self, key: bytes, value: bytes) -> None: ...
47
+ def incr(self, key: bytes) -> int: ...
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Get:
52
+ key: bytes
53
+ wait: bool = False # the runner sleeps first
54
+
55
+ def do(self, store: Store) -> object:
56
+ return store.get(self.key)
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class Incr:
61
+ key: bytes
62
+
63
+ def do(self, store: Store) -> object:
64
+ return store.incr(self.key)
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class Set:
69
+ key: bytes
70
+ value: bytes
71
+
72
+ def do(self, store: Store) -> object:
73
+ store.set(self.key, self.value)
74
+ return None
75
+
76
+
77
+ class Op(Protocol):
78
+ def do(self, store: Any) -> object: ...
79
+
80
+
81
+ Machine = Generator[Op, object, object]
82
+
83
+
84
+ def _count(n: object, what: str) -> int:
85
+ if isinstance(n, bool) or not isinstance(n, int) or n < 1:
86
+ raise MappingCorrupt(f"{what} replied {n!r}, not a count from 1")
87
+ return n
88
+
89
+
90
+ def assign(keys: Keys, ext: bytes, *, polls: int) -> Machine:
91
+ """The id of `ext`, elected and written if new. `polls` bounds the wait
92
+ of a loser for the winner's forward record."""
93
+ raw = yield Get(keys.forward(ext))
94
+ if raw is not None:
95
+ return decode_forward(raw, ext) # type: ignore[arg-type]
96
+ if _count((yield Incr(keys.election(ext))), "election") == 1:
97
+ try:
98
+ i = _count((yield Incr(keys.counter)), "counter")
99
+ except ServerError as e:
100
+ if e.error_code == "INTEGER_OVERFLOW":
101
+ raise IdSpaceExhausted("id counter at 2**63-1: no id left") from e
102
+ raise
103
+ if i > ID_MAX:
104
+ raise IdSpaceExhausted(f"id counter at {i}, past 2**63-1")
105
+ yield Set(keys.reverse(i), encode_reverse(ext))
106
+ yield Set(keys.forward(ext), encode_forward(i, ext))
107
+ return i
108
+ for n in range(polls + 1):
109
+ raw = yield Get(keys.forward(ext), wait=n > 0)
110
+ if raw is not None:
111
+ return decode_forward(raw, ext) # type: ignore[arg-type]
112
+ raise MappingIncomplete(
113
+ f"external id {ext!r}: the mapping did not appear within the wait; "
114
+ f"its writer may still be running ({keys.forward(ext)!r} not written)"
115
+ )
116
+
117
+
118
+ def lookup(keys: Keys, ext: bytes) -> Machine:
119
+ """The id of `ext`, or None when it has no mapping."""
120
+ raw = yield Get(keys.forward(ext))
121
+ return None if raw is None else decode_forward(raw, ext) # type: ignore[arg-type]
122
+
123
+
124
+ def resolve(keys: Keys, i: int) -> Machine:
125
+ """The external id of vector id `i`. The reverse is written before the
126
+ forward record and the vector, so a hit without one is corruption."""
127
+ raw = yield Get(keys.reverse(i))
128
+ if raw is None:
129
+ raise MappingCorrupt(f"vector id {i} has no reverse record")
130
+ return decode_reverse(raw) # type: ignore[arg-type]
131
+
132
+
133
+ def run(
134
+ machine: Machine,
135
+ store: Any,
136
+ *,
137
+ interval: float = 0.05,
138
+ sleep: Callable[[float], None] = time.sleep,
139
+ ) -> object:
140
+ op = next(machine)
141
+ while True:
142
+ try:
143
+ if isinstance(op, Get) and op.wait:
144
+ sleep(interval)
145
+ reply = op.do(store)
146
+ except Exception as e: # the machine decides what an error means
147
+ try:
148
+ op = machine.throw(e)
149
+ except StopIteration as done:
150
+ return done.value
151
+ continue
152
+ try:
153
+ op = machine.send(reply)
154
+ except StopIteration as done:
155
+ return done.value