kvgit 0.5.0__cp310-abi3-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.
kvgit/__init__.py ADDED
@@ -0,0 +1,93 @@
1
+ """kvgit: versioned key-value store."""
2
+
3
+ from ._open import open
4
+ from ._store import (
5
+ EMPTY_HASH as EMPTY_ROOT,
6
+ ROOT_COMMIT,
7
+ CorruptHeadRecoverer,
8
+ recover_by_commit_scan,
9
+ )
10
+ from ._types import (
11
+ DiffResult,
12
+ MergeChoice,
13
+ MergePolicy,
14
+ MergeResult,
15
+ Resolution,
16
+ TagInfo,
17
+ )
18
+ from .content_types import MergeFn, counter, last_writer_wins, text_merge
19
+ from .errors import (
20
+ BranchExistsError,
21
+ BranchMovedError,
22
+ ConcurrencyError,
23
+ CorruptHeadError,
24
+ GcBusy,
25
+ IntegrityError,
26
+ KvgitError,
27
+ MergeConflict,
28
+ StorageVersionError,
29
+ TagExistsError,
30
+ UnknownBranchError,
31
+ UnknownCommitError,
32
+ UnknownTagError,
33
+ )
34
+ from .merges import (
35
+ CantMark,
36
+ TextMergeFn,
37
+ make_text_merge,
38
+ ours,
39
+ text,
40
+ text_merge_result,
41
+ theirs,
42
+ )
43
+ from .namespaced import Namespaced
44
+ from .refs import Branches, Tags
45
+ from .repo import Commit, RawSnapshot, Repo, Snapshot
46
+ from .worktree import Status, Worktree
47
+
48
+ __all__ = [
49
+ "EMPTY_ROOT",
50
+ "ROOT_COMMIT",
51
+ "BranchExistsError",
52
+ "BranchMovedError",
53
+ "Branches",
54
+ "CantMark",
55
+ "Commit",
56
+ "ConcurrencyError",
57
+ "CorruptHeadError",
58
+ "CorruptHeadRecoverer",
59
+ "DiffResult",
60
+ "GcBusy",
61
+ "IntegrityError",
62
+ "KvgitError",
63
+ "MergeChoice",
64
+ "MergeConflict",
65
+ "MergeFn",
66
+ "MergePolicy",
67
+ "MergeResult",
68
+ "Namespaced",
69
+ "RawSnapshot",
70
+ "Repo",
71
+ "Resolution",
72
+ "Snapshot",
73
+ "Status",
74
+ "StorageVersionError",
75
+ "TagExistsError",
76
+ "TagInfo",
77
+ "Tags",
78
+ "TextMergeFn",
79
+ "UnknownBranchError",
80
+ "UnknownCommitError",
81
+ "UnknownTagError",
82
+ "Worktree",
83
+ "counter",
84
+ "last_writer_wins",
85
+ "make_text_merge",
86
+ "open",
87
+ "ours",
88
+ "recover_by_commit_scan",
89
+ "text",
90
+ "text_merge",
91
+ "text_merge_result",
92
+ "theirs",
93
+ ]
kvgit/_codec.py ADDED
@@ -0,0 +1,191 @@
1
+ """How a repository turns values into stored bytes and back."""
2
+
3
+ import inspect
4
+ import pickle
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from ._store import CHUNK_PREFIX
9
+ from .codecs._hash import hash_bytes
10
+ from .kv.base import KVStore
11
+
12
+ CodecSpec = str | tuple[Callable[..., bytes], Callable[..., Any]]
13
+ """``"pickle"``, ``"scientific"``, ``"bytes"``, or an ``(encoder, decoder)`` pair."""
14
+
15
+
16
+ class _ChunkSink:
17
+ """Accumulates content-addressed chunks emitted during one commit.
18
+
19
+ Built fresh per commit and shared across every value encoded in it,
20
+ so dedup extends to the same buffer appearing under several keys.
21
+ """
22
+
23
+ def __init__(self) -> None:
24
+ self.chunks: dict[str, bytes] = {}
25
+ # per-encode key tracking — set externally between encode calls
26
+ self.current_key: str | None = None
27
+ self.refs_by_key: dict[str, list[str]] = {}
28
+
29
+ def put(self, data) -> str:
30
+ ref = hash_bytes(data)
31
+ if ref not in self.chunks:
32
+ # Materialize once on first sight; later puts of the same
33
+ # chunk hash are free (same ref returned, no new bytes).
34
+ self.chunks[ref] = bytes(data) if isinstance(data, memoryview) else data
35
+ if self.current_key is not None:
36
+ self.refs_by_key.setdefault(self.current_key, []).append(ref)
37
+ return ref
38
+
39
+
40
+ class _ChunkReader:
41
+ """Fetches chunks from the store by content-addressed key."""
42
+
43
+ def __init__(self, kv: KVStore) -> None:
44
+ self._kv = kv
45
+
46
+ def get(self, ref: str) -> bytes:
47
+ raw = self._kv.get(CHUNK_PREFIX + ref)
48
+ if raw is None:
49
+ raise KeyError(f"chunk not found: {ref!r}")
50
+ return raw
51
+
52
+ def get_many(self, refs):
53
+ prefixed = [CHUNK_PREFIX + r for r in refs]
54
+ raw = self._kv.get_many(*prefixed)
55
+ # Strip the prefix back off so callers see the codec-level refs.
56
+ return {k[len(CHUNK_PREFIX) :]: v for k, v in raw.items()}
57
+
58
+ def prefetch(self, refs) -> None:
59
+ # Backends with async fetch could override; the in-process
60
+ # backends have nothing useful to do here.
61
+ return None
62
+
63
+
64
+ class _CountingReader:
65
+ """A chunk reader that tallies the bytes of the chunks it returns."""
66
+
67
+ def __init__(self, reader: _ChunkReader) -> None:
68
+ self._reader = reader
69
+ self.nbytes = 0
70
+
71
+ def get(self, ref: str) -> bytes:
72
+ raw = self._reader.get(ref)
73
+ self.nbytes += len(raw)
74
+ return raw
75
+
76
+ def get_many(self, refs):
77
+ found = self._reader.get_many(refs)
78
+ self.nbytes += sum(len(v) for v in found.values())
79
+ return found
80
+
81
+ def prefetch(self, refs) -> None:
82
+ self._reader.prefetch(refs)
83
+
84
+
85
+ def _is_chunk_aware(fn) -> bool:
86
+ """Whether an encoder/decoder takes a required sink/reader argument.
87
+
88
+ Chunk-aware encoders/decoders (built with ``kvgit.codecs.compose``)
89
+ have exactly two **required** positional parameters: the value/blob
90
+ and the sink/reader. ``pickle.dumps`` and friends have optional
91
+ second arguments (``protocol=...``) and stay one-argument.
92
+ """
93
+ try:
94
+ sig = inspect.signature(fn)
95
+ except (TypeError, ValueError):
96
+ return False
97
+ required = [
98
+ p
99
+ for p in sig.parameters.values()
100
+ if p.kind
101
+ in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD)
102
+ and p.default is inspect.Parameter.empty
103
+ ]
104
+ return len(required) >= 2
105
+
106
+
107
+ def _bytes_encode(value: Any) -> bytes:
108
+ if not isinstance(value, bytes):
109
+ raise TypeError(
110
+ f"codec 'bytes' stores bytes values only, got {type(value).__name__}"
111
+ )
112
+ return value
113
+
114
+
115
+ def _bytes_decode(raw: bytes) -> bytes:
116
+ return raw
117
+
118
+
119
+ def _resolve(spec: CodecSpec) -> tuple[Callable[..., bytes], Callable[..., Any]]:
120
+ if isinstance(spec, tuple):
121
+ if len(spec) != 2 or not all(callable(f) for f in spec):
122
+ raise ValueError("a codec pair is (encoder, decoder)")
123
+ return spec
124
+ if spec == "pickle":
125
+ return pickle.dumps, pickle.loads
126
+ if spec == "bytes":
127
+ return _bytes_encode, _bytes_decode
128
+ if spec == "scientific":
129
+ from .codecs import _resolve_named
130
+
131
+ return _resolve_named("scientific")
132
+ raise ValueError(
133
+ f"unknown codec {spec!r}: use 'pickle', 'scientific', 'bytes', "
134
+ "or an (encoder, decoder) pair"
135
+ )
136
+
137
+
138
+ class Codec:
139
+ """A repository's encoder and decoder, bound to its store.
140
+
141
+ Arity is detected: a one-argument ``encoder(value) -> bytes`` /
142
+ ``decoder(bytes) -> value`` pair, or a chunk-aware
143
+ ``encoder(value, sink)`` / ``decoder(bytes, reader)`` pair from
144
+ :mod:`kvgit.codecs`, whose large buffers are stored once as
145
+ content-addressed chunks.
146
+ """
147
+
148
+ def __init__(self, spec: CodecSpec, store: KVStore) -> None:
149
+ self.encoder, self.decoder = _resolve(spec)
150
+ self.encoder_chunked = _is_chunk_aware(self.encoder)
151
+ self.decoder_chunked = _is_chunk_aware(self.decoder)
152
+ self._reader = _ChunkReader(store) if self.decoder_chunked else None
153
+
154
+ def new_sink(self) -> _ChunkSink | None:
155
+ """A sink for one commit's chunks, or None for a plain codec."""
156
+ return _ChunkSink() if self.encoder_chunked else None
157
+
158
+ def encode(self, key: str, value: Any, sink: _ChunkSink | None) -> bytes:
159
+ if sink is not None:
160
+ sink.current_key = key
161
+ try:
162
+ return self.encoder(value, sink)
163
+ finally:
164
+ sink.current_key = None
165
+ return self.encoder(value)
166
+
167
+ def decode(self, raw: bytes) -> Any:
168
+ if self.decoder_chunked:
169
+ return self.decoder(raw, self._reader)
170
+ return self.decoder(raw)
171
+
172
+ def decode_sized(self, raw: bytes) -> tuple[Any, int]:
173
+ """A value, and the bytes it was decoded from: its blob plus any
174
+ chunks a chunked decoder read, which the value usually keeps."""
175
+ if self.decoder_chunked:
176
+ reader = _CountingReader(self._reader) # type: ignore[arg-type]
177
+ return self.decoder(raw, reader), len(raw) + reader.nbytes
178
+ return self.decoder(raw), len(raw)
179
+
180
+ def encode_merged(self, value: Any) -> bytes:
181
+ """Encode a value a merge function produced.
182
+
183
+ A merge runs below any commit's chunk sink, so there is nowhere to
184
+ land chunks: a chunk-aware codec's merge output is stored as plain
185
+ pickle (which its decoder reads) until the key is next written.
186
+ Every other codec encodes merge output exactly as it encodes a
187
+ write, so a ``bytes`` store stays bytes.
188
+ """
189
+ if self.encoder_chunked:
190
+ return pickle.dumps(value)
191
+ return self.encoder(value)
kvgit/_core.pyd ADDED
Binary file
kvgit/_core.pyi ADDED
@@ -0,0 +1,176 @@
1
+ from typing import Any
2
+
3
+ class MetaEntry:
4
+ """Per-key metadata stored beside a blob pointer in a keyset."""
5
+
6
+ size: int | None
7
+ created_at: float | int | None
8
+ chunks: list[str] | None
9
+ def __init__(
10
+ self,
11
+ size: int | None,
12
+ created_at: float | int | None = None,
13
+ chunks: list[str] | None = None,
14
+ ) -> None: ...
15
+
16
+ class KeysetEntry:
17
+ """One entry in a keyset: a blob pointer and its metadata."""
18
+
19
+ @property
20
+ def blob(self) -> str: ...
21
+ @property
22
+ def meta(self) -> MetaEntry: ...
23
+ def __init__(self, blob: str, meta: MetaEntry) -> None: ...
24
+
25
+ def encode_entry(entry: KeysetEntry) -> bytes:
26
+ """An entry's bytes, as both packages write them."""
27
+
28
+ def decode_entry(raw: bytes) -> KeysetEntry:
29
+ """The entry stored as ``raw``."""
30
+
31
+ def version() -> str:
32
+ """The version of the core, which is the version of the package."""
33
+
34
+ def empty_hash() -> str:
35
+ """The root of the empty keyset."""
36
+
37
+ def commit_hash(
38
+ parents: list[str], root: str, time: float, info: dict | None = None
39
+ ) -> str:
40
+ """The 40-hex hash naming a commit."""
41
+
42
+ class TreeOp:
43
+ """A tree operation in progress: ``resume`` returns ``("get", keys)``
44
+ while it needs nodes, to be answered with the stored values of those
45
+ keys, and ``("done", result)`` once it is finished."""
46
+
47
+ @staticmethod
48
+ def get_many(
49
+ prefix: str, bucket_max: int, root: str, keys: list[str], entries: bool = False
50
+ ) -> TreeOp: ...
51
+ @staticmethod
52
+ def walk(
53
+ prefix: str, bucket_max: int, root: str, skip: set[str], entries: bool = False
54
+ ) -> TreeOp: ...
55
+ @staticmethod
56
+ def diff(
57
+ prefix: str, bucket_max: int, a: str, b: str, entries: bool = False
58
+ ) -> TreeOp: ...
59
+ @staticmethod
60
+ def update(
61
+ prefix: str,
62
+ bucket_max: int,
63
+ root: str,
64
+ updates: list[tuple[str, Any]],
65
+ removals: list[str],
66
+ unwritten: dict[str, bytes] | None = None,
67
+ entries: bool = False,
68
+ ) -> TreeOp: ...
69
+ def resume(self, reply: dict[str, bytes] | None = None) -> tuple[str, Any]: ...
70
+
71
+ MAX_MARK_BYTES: int
72
+ """The most bytes, all sides together, the text merge will mark."""
73
+
74
+ def text_merge(
75
+ old: bytes | None,
76
+ ours: bytes | None,
77
+ theirs: bytes | None,
78
+ ours_label: str,
79
+ theirs_label: str,
80
+ cant_mark: type[Exception],
81
+ ) -> tuple[bytes, bool]:
82
+ """The three-way text merge of a value's sides, and whether it marked
83
+ a conflict. Values that can't be marked raise ``cant_mark``; a label
84
+ holding a line break raises ``ValueError``."""
85
+
86
+ def check_text_labels(ours_label: str, theirs_label: str) -> None:
87
+ """Raise ``ValueError`` if either label holds a line break."""
88
+
89
+ def check_branch_name(name: str) -> None:
90
+ """Raise ``ValueError`` for a name that can't be a branch."""
91
+
92
+ def check_tag_name(name: str) -> None:
93
+ """Raise ``ValueError`` for a name that can't be a tag."""
94
+
95
+ def cacheable(key: str) -> bool:
96
+ """Whether ``key`` is one the store never rewrites."""
97
+
98
+ class ContentCache:
99
+ """A repository's memory of write-once keys, shared by every
100
+ operation given it; see ``kvgit.cache``."""
101
+
102
+ def __init__(self, max_bytes: int) -> None: ...
103
+ @property
104
+ def max_bytes(self) -> int: ...
105
+ @property
106
+ def size_bytes(self) -> int: ...
107
+ @property
108
+ def hits(self) -> int: ...
109
+ @property
110
+ def misses(self) -> int: ...
111
+ @property
112
+ def clears(self) -> int: ...
113
+ def __len__(self) -> int: ...
114
+ def clear(self) -> None: ...
115
+ def lookup(self, keys: list[str]) -> dict[str, bytes]: ...
116
+ def count(self, hits: int, misses: int) -> None: ...
117
+ def remember(self, items: dict[str, bytes]) -> None: ...
118
+ def forget(self, keys: list[str]) -> None: ...
119
+ def saw_lease(self, record: bytes | None) -> None: ...
120
+
121
+ class Op:
122
+ """An operation of the core in progress, started by name with its
123
+ arguments as a dict, or by ``Op.commit``. ``resume`` returns the next
124
+ request as a tuple, to be answered by the next call, until it
125
+ returns ``("done", outcome, notes)``; see ``kvgit._drive``."""
126
+
127
+ def __init__(self, name: str, args: dict[str, Any]) -> None: ...
128
+ @staticmethod
129
+ def commit(
130
+ branch: str,
131
+ base: str,
132
+ current: str,
133
+ updates: list[tuple[str, KeysetEntry]],
134
+ removals: list[str],
135
+ chunks: list[str],
136
+ info: dict | None,
137
+ on_moved: str,
138
+ on_conflict: str,
139
+ merge_fns: dict[str, Any],
140
+ merge_prefixes: list[tuple[str, Any]],
141
+ default_merge: Any,
142
+ recover: bool,
143
+ stamped: bool,
144
+ roots: list[tuple[str, str]],
145
+ generations: list[tuple[str, int]],
146
+ ) -> Op: ...
147
+ @staticmethod
148
+ def merge(
149
+ branch: str,
150
+ ours: str,
151
+ theirs: str,
152
+ from_: str | None,
153
+ fast_forward: bool,
154
+ info: dict | None,
155
+ on_conflict: str,
156
+ merge_fns: dict[str, Any],
157
+ merge_prefixes: list[tuple[str, Any]],
158
+ default_merge: Any,
159
+ post_check: bool,
160
+ recover: bool,
161
+ stamped: bool,
162
+ roots: list[tuple[str, str]],
163
+ generations: list[tuple[str, int]],
164
+ ) -> Op: ...
165
+ @staticmethod
166
+ def resolve(
167
+ ours: list[tuple[str, tuple[str, int] | None, tuple[str, int] | None]],
168
+ theirs: list[tuple[str, tuple[str, int] | None, tuple[str, int] | None]],
169
+ merge_fns: dict[str, Any],
170
+ merge_prefixes: list[tuple[str, Any]],
171
+ default_merge: Any,
172
+ ) -> Op: ...
173
+ def use_cache(self, cache: ContentCache) -> None: ...
174
+ def resume(
175
+ self, wall: float, reply: Any = None, failed: bool = False
176
+ ) -> tuple[Any, ...]: ...
kvgit/_drive.py ADDED
@@ -0,0 +1,219 @@
1
+ """Run an operation of the core against a store.
2
+
3
+ The core never touches a store: an operation hands back each thing it
4
+ needs as a request, and this performs it and hands back the answer. A
5
+ request that raises is answered as failed; the operation unwinds,
6
+ undoing what it wrote, and the exception is raised once it is done.
7
+ """
8
+
9
+ import hashlib
10
+ import logging
11
+ from collections.abc import Callable, Generator, Sequence
12
+ from typing import Any
13
+
14
+ from ._types import MergeChoice
15
+ from .errors import (
16
+ BranchExistsError,
17
+ BranchMovedError,
18
+ ConcurrencyError,
19
+ CorruptHeadError,
20
+ GcBusy,
21
+ IntegrityError,
22
+ MergeConflict,
23
+ StorageVersionError,
24
+ TagExistsError,
25
+ UnknownBranchError,
26
+ UnknownCommitError,
27
+ UnknownTagError,
28
+ )
29
+ from .kv.base import KVStore
30
+
31
+ logger = logging.getLogger("kvgit")
32
+
33
+ BLOB_PREFIX = "kvgit:blob:"
34
+
35
+ _NOTES = {
36
+ "from_backup": "Branch '%s': HEAD corrupt, recovered from prev HEAD",
37
+ "from_recoverer": "Branch '%s': HEAD corrupt, recovered via injected recoverer",
38
+ "recoverer_missed": "Branch '%s': recoverer returned %r, which is not a commit "
39
+ "in this store; treating the branch as unrecoverable",
40
+ "healed": "Branch '%s': corrupt HEAD replaced with recovered commit",
41
+ "lease_overrun": "a sweep ran %.1fs past its %.1fs GC lease between "
42
+ "renewals. Raise lease_ttl.",
43
+ }
44
+
45
+ # The logger each note goes to, where it isn't "kvgit".
46
+ _LOGGERS = {"lease_overrun": "kvgit.orphans"}
47
+
48
+
49
+ def drive(op: Any, store: KVStore, **env: Any) -> Any:
50
+ """Perform `op`'s requests until it is done, and return its outcome;
51
+ see :func:`steps` for ``env``."""
52
+ run = steps(op, store, **env)
53
+ while True:
54
+ try:
55
+ next(run)
56
+ except StopIteration as done:
57
+ return done.value
58
+
59
+
60
+ def steps(
61
+ op: Any,
62
+ store: KVStore,
63
+ *,
64
+ held: dict[str, bytes] | None = None,
65
+ merge_fns: Sequence[Callable[..., Any]] = (),
66
+ post_check: Callable[[str, bytes], bool] | None = None,
67
+ recoverer: Callable[[KVStore, str], Any] | None = None,
68
+ owner: Callable[[], str] | None = None,
69
+ clock: Callable[[], float],
70
+ sleep: Callable[[float], None],
71
+ now: Callable[[], float] | None = None,
72
+ ) -> Generator[Any, None, Any]:
73
+ """Perform `op`'s requests, yielding each part of the answer it emits
74
+ early, and return its outcome.
75
+
76
+ ``held`` holds the bytes the operation writes by key without
77
+ reading them; values merge functions make join it. ``merge_fns`` are
78
+ the functions the operation names by number, and ``post_check`` the
79
+ check it runs over the values they make. ``clock`` is the wall
80
+ clock leases expire by; ``now``, the clock commit, tag and sweep
81
+ times are read from, is ``clock`` unless given.
82
+ """
83
+ held = {} if held is None else held
84
+ # A store seen through a content cache: the operation reads through
85
+ # the cache itself, and its requests go to the store underneath.
86
+ cache = getattr(store, "_core_cache", None)
87
+ if cache is not None:
88
+ op.use_cache(cache)
89
+ store = store.backend # type: ignore[attr-defined]
90
+ errors: dict[str, Exception] = {}
91
+ raised: BaseException | None = None
92
+ reply: Any = None
93
+ failed = False
94
+ while True:
95
+ request = op.resume(clock(), reply, failed)
96
+ kind = request[0]
97
+ if kind == "done":
98
+ _, outcome, notes = request
99
+ for note, *args in notes:
100
+ logging.getLogger(_LOGGERS.get(note, "kvgit")).warning(
101
+ _NOTES[note], *args
102
+ )
103
+ if outcome[0] == "ok":
104
+ return outcome[1]
105
+ if raised is not None:
106
+ raise raised
107
+ raise _error(outcome[1], outcome[2], errors)
108
+ reply, failed = None, False
109
+ if kind == "emit":
110
+ # Outside the handler below, so a caller that stops iterating
111
+ # closes this generator rather than failing the request.
112
+ yield request[1]
113
+ continue
114
+ try:
115
+ if kind == "get":
116
+ reply = _read(store, request[1], held)
117
+ elif kind == "scan":
118
+ reply = list(store.keys(request[1]))
119
+ elif kind == "cas":
120
+ _, expect, writes, removes = request
121
+ values = {k: held[k] if v is None else v for k, v in writes}
122
+ reply = store.cas_many(dict(expect), values, removes)
123
+ elif kind == "wait":
124
+ sleep(request[1])
125
+ elif kind == "merge":
126
+ reply = _merge(store, request[1], merge_fns, held, errors)
127
+ elif kind == "now":
128
+ reply = (now if now is not None else clock)()
129
+ elif kind == "owner":
130
+ reply = owner() if owner is not None else None
131
+ elif kind == "check":
132
+ reply = [
133
+ key
134
+ for key, blob, made in request[1]
135
+ if post_check is not None
136
+ and not post_check(key, held[blob] if made is None else made)
137
+ ]
138
+ elif kind == "recover":
139
+ guess = recoverer(store, request[1]) if recoverer else None
140
+ if guess is not None and not isinstance(guess, str):
141
+ logger.warning(_NOTES["recoverer_missed"], request[1], guess)
142
+ guess = None
143
+ reply = guess
144
+ except BaseException as e: # noqa: BLE001 — raised once the op unwinds
145
+ raised = raised or e
146
+ failed = True
147
+
148
+
149
+ def _read(store: KVStore, keys: list[str], held: dict[str, bytes]) -> dict[str, bytes]:
150
+ """The values of ``keys``: the bytes held here first, being the
151
+ same content-keyed bytes the store would answer, then the store's."""
152
+ found = {k: held[k] for k in keys if k in held}
153
+ rest = [k for k in keys if k not in found]
154
+ if rest:
155
+ found.update(store.get_many(rest))
156
+ return found
157
+
158
+
159
+ def _merge(
160
+ store: KVStore,
161
+ asks: list[tuple[int, str, str | None, str | None, str | None]],
162
+ merge_fns: Sequence[Callable[..., Any]],
163
+ held: dict[str, bytes],
164
+ errors: dict[str, Exception],
165
+ ) -> list[Any]:
166
+ """Run each merge function asked for on its key's three sides."""
167
+ blobs = {b for _, _, *sides in asks for b in sides if b is not None}
168
+ values = _read(store, list(blobs), held) if blobs else {}
169
+ answers: list[Any] = []
170
+ for rule, key, *sides in asks:
171
+ old, ours, theirs = (None if b is None else values.get(b) for b in sides)
172
+ try:
173
+ result = merge_fns[rule](old, ours, theirs)
174
+ except Exception as e: # noqa: BLE001 — a caller's function: a conflict
175
+ errors[key] = e
176
+ answers.append(("failed", str(e)))
177
+ continue
178
+ if result is MergeChoice.OURS:
179
+ answers.append("ours")
180
+ elif result is MergeChoice.THEIRS:
181
+ answers.append("theirs")
182
+ else:
183
+ blob = BLOB_PREFIX + hashlib.sha256(result).hexdigest()
184
+ held[blob] = result
185
+ answers.append(("value", blob, len(result)))
186
+ return answers
187
+
188
+
189
+ _ERRORS: dict[str, Callable[[str], Exception]] = {
190
+ "unknown_branch": UnknownBranchError,
191
+ "corrupt_head": CorruptHeadError,
192
+ "unknown_tag": UnknownTagError,
193
+ "unknown_commit": UnknownCommitError,
194
+ "branch_exists": BranchExistsError,
195
+ "tag_exists": TagExistsError,
196
+ "concurrency": ConcurrencyError,
197
+ "gc_busy": GcBusy,
198
+ "storage_version": StorageVersionError,
199
+ "integrity": IntegrityError,
200
+ }
201
+
202
+
203
+ def _error(
204
+ kind: str, fields: dict[str, Any], errors: dict[str, Exception]
205
+ ) -> Exception:
206
+ """The exception the core's error `kind` is raised as."""
207
+ if kind == "branch_moved":
208
+ return BranchMovedError(fields["branch"], fields["base"], fields["head"])
209
+ if kind in _ERRORS:
210
+ return _ERRORS[kind](fields["message"])
211
+ if kind == "merge_conflict":
212
+ from .merges import CantMark
213
+
214
+ failures = {
215
+ key: errors.get(key) or CantMark(reason)
216
+ for key, reason in fields["failures"].items()
217
+ }
218
+ return MergeConflict(set(fields["keys"]), failures)
219
+ return ValueError(fields["message"])