munarium-client 1.1.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.
Files changed (56) hide show
  1. munarium_client/__init__.py +390 -0
  2. munarium_client/_chunks.py +70 -0
  3. munarium_client/_errors.py +300 -0
  4. munarium_client/_grpc_common.py +642 -0
  5. munarium_client/_options.py +53 -0
  6. munarium_client/_proto/__init__.py +0 -0
  7. munarium_client/_proto/mmp/__init__.py +0 -0
  8. munarium_client/_proto/mmp/v1/__init__.py +0 -0
  9. munarium_client/_proto/mmp/v1/admin_pb2.py +65 -0
  10. munarium_client/_proto/mmp/v1/admin_pb2.pyi +142 -0
  11. munarium_client/_proto/mmp/v1/admin_pb2_grpc.py +314 -0
  12. munarium_client/_proto/mmp/v1/command_pb2.py +70 -0
  13. munarium_client/_proto/mmp/v1/command_pb2.pyi +175 -0
  14. munarium_client/_proto/mmp/v1/command_pb2_grpc.py +398 -0
  15. munarium_client/_proto/mmp/v1/common_pb2.py +53 -0
  16. munarium_client/_proto/mmp/v1/common_pb2.pyi +103 -0
  17. munarium_client/_proto/mmp/v1/common_pb2_grpc.py +24 -0
  18. munarium_client/_proto/mmp/v1/ingest_pb2.py +54 -0
  19. munarium_client/_proto/mmp/v1/ingest_pb2.pyi +101 -0
  20. munarium_client/_proto/mmp/v1/ingest_pb2_grpc.py +184 -0
  21. munarium_client/_proto/mmp/v1/ledger_pb2.py +60 -0
  22. munarium_client/_proto/mmp/v1/ledger_pb2.pyi +201 -0
  23. munarium_client/_proto/mmp/v1/ledger_pb2_grpc.py +24 -0
  24. munarium_client/_proto/mmp/v1/provider_pb2.py +54 -0
  25. munarium_client/_proto/mmp/v1/provider_pb2.pyi +114 -0
  26. munarium_client/_proto/mmp/v1/provider_pb2_grpc.py +226 -0
  27. munarium_client/_proto/mmp/v1/query_pb2.py +74 -0
  28. munarium_client/_proto/mmp/v1/query_pb2.pyi +147 -0
  29. munarium_client/_proto/mmp/v1/query_pb2_grpc.py +441 -0
  30. munarium_client/_proto/mmp/v1/retrieval_pb2.py +57 -0
  31. munarium_client/_proto/mmp/v1/retrieval_pb2.pyi +124 -0
  32. munarium_client/_proto/mmp/v1/retrieval_pb2_grpc.py +270 -0
  33. munarium_client/_proto/mmp/v1/runbook_pb2.py +87 -0
  34. munarium_client/_proto/mmp/v1/runbook_pb2.pyi +266 -0
  35. munarium_client/_proto/mmp/v1/runbook_pb2_grpc.py +485 -0
  36. munarium_client/_proto/mmp/v1/server_api_pb2.py +50 -0
  37. munarium_client/_proto/mmp/v1/server_api_pb2.pyi +53 -0
  38. munarium_client/_proto/mmp/v1/server_api_pb2_grpc.py +5378 -0
  39. munarium_client/_proto/mmp/v1/session_pb2.py +67 -0
  40. munarium_client/_proto/mmp/v1/session_pb2.pyi +214 -0
  41. munarium_client/_proto/mmp/v1/session_pb2_grpc.py +227 -0
  42. munarium_client/_retry.py +24 -0
  43. munarium_client/_server_api.py +298 -0
  44. munarium_client/_specs.py +1100 -0
  45. munarium_client/_sse.py +228 -0
  46. munarium_client/grpc_transport.py +1245 -0
  47. munarium_client/models.py +1242 -0
  48. munarium_client/py.typed +0 -0
  49. munarium_client/rest.py +478 -0
  50. munarium_client/rest_planes.py +1350 -0
  51. munarium_client/server_api.py +3158 -0
  52. munarium_client-1.1.0.dist-info/METADATA +184 -0
  53. munarium_client-1.1.0.dist-info/RECORD +56 -0
  54. munarium_client-1.1.0.dist-info/WHEEL +4 -0
  55. munarium_client-1.1.0.dist-info/licenses/LICENSE +202 -0
  56. munarium_client-1.1.0.dist-info/licenses/NOTICE +15 -0
@@ -0,0 +1,390 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Official Python client for munarium-server.
3
+
4
+ One plane surface, two transports (REST + gRPC), sync and async, typed
5
+ errors keyed on the problem-slug registry, and the head-conflict write loop
6
+ built in.
7
+
8
+ >>> from munarium_client import MunariumClient, ClientOptions
9
+ >>> client = MunariumClient.rest(ClientOptions("http://127.0.0.1:8080", token="devtoken"))
10
+ >>> v = client.commands.create_version()
11
+ >>> outcome = client.commands.propose_claim(v, subject="hero", key="eyes", value="green")
12
+
13
+ The invariants this client encodes:
14
+
15
+ 1. **Disputed != error.** A gate-blocked claim returns SUCCESS with
16
+ ``outcome.is_disputed`` plus findings (governance records, never drops).
17
+ 2. **Head conflicts are normal.** ``propose_claim_with_retry`` re-reads,
18
+ rebuilds, retries with a fresh idempotency key per attempt.
19
+ 3. **One pin bounds everything.** ``as_of_seq`` threads through every query.
20
+ 4. **Every retrieval answer carries a ProvenanceEnvelope** — required,
21
+ non-optional on :class:`munarium_client.models.SearchResult`.
22
+ 5. **Append-only.** No update/delete methods; corrections name
23
+ ``supersedes_id`` explicitly.
24
+ 6. **Idempotency keys** auto-generate per command and are caller-overridable.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import asyncio
30
+ from collections.abc import AsyncIterator, Callable
31
+ from typing import Any, cast
32
+
33
+ from . import models
34
+ from ._chunks import ChunkSource, chunks_from_bytes, chunks_from_list
35
+ from ._errors import (
36
+ ForbiddenError,
37
+ HeadConflictError,
38
+ IdempotencyMismatchError,
39
+ InvalidInputError,
40
+ MunariumError,
41
+ NotFoundError,
42
+ OverloadedError,
43
+ PolicyRejectionError,
44
+ ProviderError,
45
+ RateLimitedError,
46
+ RunLockedError,
47
+ ShapeViolationError,
48
+ StorageError,
49
+ TransportError,
50
+ UnauthenticatedError,
51
+ UnexpectedError,
52
+ UnsupportedError,
53
+ )
54
+ from ._options import TARGET_SERVER_VERSION, ClientOptions, WriteLoopOptions
55
+ from ._retry import sleep_async, sleep_sync
56
+ from ._server_api import ApiRequest, ApiResponse
57
+ from .server_api import AsyncServerApiClient, ServerApiClient
58
+
59
+ __all__ = [
60
+ "ApiRequest",
61
+ "ApiResponse",
62
+ "AsyncServerApiClient",
63
+ "ServerApiClient",
64
+ "TARGET_SERVER_VERSION",
65
+ "AsyncMunariumClient",
66
+ "ChunkSource",
67
+ "ClientOptions",
68
+ "ForbiddenError",
69
+ "HeadConflictError",
70
+ "IdempotencyMismatchError",
71
+ "InvalidInputError",
72
+ "MunariumClient",
73
+ "MunariumError",
74
+ "NotFoundError",
75
+ "OverloadedError",
76
+ "PolicyRejectionError",
77
+ "ProviderError",
78
+ "RateLimitedError",
79
+ "RunLockedError",
80
+ "ShapeViolationError",
81
+ "StorageError",
82
+ "TransportError",
83
+ "UnauthenticatedError",
84
+ "UnexpectedError",
85
+ "UnsupportedError",
86
+ "WriteLoopOptions",
87
+ "chunks_from_bytes",
88
+ "chunks_from_list",
89
+ "models",
90
+ ]
91
+
92
+
93
+ def _grpc_no_server_version() -> models.ServerVersion:
94
+ raise UnsupportedError(
95
+ "GET /version is a REST meta route — use the REST client, or gRPC server reflection"
96
+ )
97
+
98
+
99
+ class MunariumClient:
100
+ """Synchronous facade: eleven plane namespaces over one transport, plus
101
+ the ``server_version()`` meta route. Every REST-only method surfaces a
102
+ typed ``UnsupportedError`` on the gRPC transport — never silent."""
103
+
104
+ def __init__(
105
+ self,
106
+ commands: Any,
107
+ query: Any,
108
+ ingest: Any,
109
+ retrieval: Any,
110
+ runbooks: Any,
111
+ providers: Any,
112
+ sessions: Any,
113
+ tokens: Any,
114
+ reports: Any,
115
+ authoring: Any,
116
+ evidence: Any,
117
+ server_version: Callable[[], models.ServerVersion],
118
+ closer: Callable[[], None],
119
+ ) -> None:
120
+ self.commands = commands
121
+ self.query = query
122
+ self.ingest = ingest
123
+ self.retrieval = retrieval
124
+ self.runbooks = runbooks
125
+ self.providers = providers
126
+ self.sessions = sessions
127
+ self.tokens = tokens
128
+ self.reports = reports
129
+ self.authoring = authoring
130
+ self.evidence = evidence
131
+ self._server_version = server_version
132
+ self._closer = closer
133
+
134
+ @classmethod
135
+ def rest(cls, options: ClientOptions) -> MunariumClient:
136
+ from . import _specs
137
+ from . import rest_planes as p
138
+ from .rest import SyncRestTransport
139
+
140
+ t = SyncRestTransport(options)
141
+ return cls(
142
+ p.RestCommands(t),
143
+ p.RestQuery(t),
144
+ p.RestIngest(t),
145
+ p.RestRetrieval(t),
146
+ p.RestRunbooks(t),
147
+ p.RestProviders(t),
148
+ p.RestSessions(t),
149
+ p.RestTokens(t),
150
+ p.RestReports(t),
151
+ p.RestAuthoring(t),
152
+ p.RestEvidence(t),
153
+ lambda: t.run(_specs.server_version()),
154
+ t.close,
155
+ )
156
+
157
+ @classmethod
158
+ def grpc(cls, options: ClientOptions) -> MunariumClient:
159
+ from . import grpc_transport as g
160
+
161
+ core = g.sync_core(options)
162
+ return cls(
163
+ g.SyncGrpcCommands(core),
164
+ g.SyncGrpcQuery(core),
165
+ g.SyncGrpcIngest(core),
166
+ g.SyncGrpcRetrieval(core),
167
+ g.SyncGrpcRunbooks(core),
168
+ g.SyncGrpcProviders(core),
169
+ g.SyncGrpcSessions(core),
170
+ g.SyncGrpcTokens(core),
171
+ g.SyncGrpcReports(core),
172
+ g.SyncGrpcAuthoring(core),
173
+ g.SyncGrpcEvidence(),
174
+ _grpc_no_server_version,
175
+ core.channel.close,
176
+ )
177
+
178
+ def server_version(self) -> models.ServerVersion:
179
+ """GET /version — the server's name + workspace version,
180
+ unauthenticated. REST-only: gRPC has no version RPC (use server
181
+ reflection there)."""
182
+ return self._server_version()
183
+
184
+ def close(self) -> None:
185
+ self._closer()
186
+
187
+ def __enter__(self) -> MunariumClient:
188
+ return self
189
+
190
+ def __exit__(self, *exc: object) -> None:
191
+ self.close()
192
+
193
+ def propose_claim_with_retry(
194
+ self,
195
+ version_id: str,
196
+ build: Callable[[int], dict[str, Any]],
197
+ opts: WriteLoopOptions | None = None,
198
+ ) -> models.ClaimOutcome:
199
+ """The head-conflict write loop (invariant #2): read head, build the
200
+ claim kwargs via ``build(head)``, propose with ``expected_head`` and a
201
+ FRESH idempotency key; on ``HeadConflictError`` back off and rebuild
202
+ against the actual head. Never retries other errors."""
203
+ opts = opts or WriteLoopOptions()
204
+ head = self.query.head(version_id)
205
+ attempt = 0
206
+ while True:
207
+ attempt += 1
208
+ try:
209
+ return cast(
210
+ models.ClaimOutcome,
211
+ self.commands.propose_claim(version_id, expected_head=head, **build(head)),
212
+ )
213
+ except HeadConflictError as e:
214
+ if attempt >= opts.max_attempts:
215
+ raise
216
+ sleep_sync(attempt)
217
+ # actual == 0 = the transport carried no seqs; re-read.
218
+ head = e.actual if e.actual > 0 else self.query.head(version_id)
219
+
220
+
221
+ class AsyncMunariumClient:
222
+ """Asyncio facade. REST is natively async (httpx.AsyncClient); the gRPC
223
+ variant drives the thread-safe sync stubs via ``asyncio.to_thread``."""
224
+
225
+ def __init__(
226
+ self,
227
+ commands: Any,
228
+ query: Any,
229
+ ingest: Any,
230
+ retrieval: Any,
231
+ runbooks: Any,
232
+ providers: Any,
233
+ sessions: Any,
234
+ tokens: Any,
235
+ reports: Any,
236
+ authoring: Any,
237
+ evidence: Any,
238
+ server_version: Callable[[], Any],
239
+ closer: Callable[[], Any],
240
+ ) -> None:
241
+ self.commands = commands
242
+ self.query = query
243
+ self.ingest = ingest
244
+ self.retrieval = retrieval
245
+ self.runbooks = runbooks
246
+ self.providers = providers
247
+ self.sessions = sessions
248
+ self.tokens = tokens
249
+ self.reports = reports
250
+ self.authoring = authoring
251
+ self.evidence = evidence
252
+ self._server_version = server_version
253
+ self._closer = closer
254
+
255
+ @classmethod
256
+ def rest(cls, options: ClientOptions) -> AsyncMunariumClient:
257
+ from . import _specs
258
+ from . import rest_planes as p
259
+ from .rest import AsyncRestTransport
260
+
261
+ t = AsyncRestTransport(options)
262
+ return cls(
263
+ p.AsyncRestCommands(t),
264
+ p.AsyncRestQuery(t),
265
+ p.AsyncRestIngest(t),
266
+ p.AsyncRestRetrieval(t),
267
+ p.AsyncRestRunbooks(t),
268
+ p.AsyncRestProviders(t),
269
+ p.AsyncRestSessions(t),
270
+ p.AsyncRestTokens(t),
271
+ p.AsyncRestReports(t),
272
+ p.AsyncRestAuthoring(t),
273
+ p.AsyncRestEvidence(t),
274
+ lambda: t.run(_specs.server_version()),
275
+ t.close,
276
+ )
277
+
278
+ @classmethod
279
+ def grpc(cls, options: ClientOptions) -> AsyncMunariumClient:
280
+ from . import grpc_transport as g
281
+
282
+ core = g.sync_core(options)
283
+
284
+ async def close() -> None:
285
+ core.channel.close()
286
+
287
+ async def server_version() -> models.ServerVersion:
288
+ return _grpc_no_server_version()
289
+
290
+ return cls(
291
+ commands=_Threaded(g.SyncGrpcCommands(core)),
292
+ query=_Threaded(g.SyncGrpcQuery(core)),
293
+ ingest=_Threaded(g.SyncGrpcIngest(core)),
294
+ retrieval=_Threaded(g.SyncGrpcRetrieval(core)),
295
+ runbooks=_Threaded(g.SyncGrpcRunbooks(core)),
296
+ providers=_Threaded(g.SyncGrpcProviders(core)),
297
+ sessions=_ThreadedSessions(g.SyncGrpcSessions(core)),
298
+ tokens=_Threaded(g.SyncGrpcTokens(core)),
299
+ reports=_Threaded(g.SyncGrpcReports()),
300
+ authoring=_Threaded(g.SyncGrpcAuthoring()),
301
+ evidence=_Threaded(g.SyncGrpcEvidence()),
302
+ server_version=server_version,
303
+ closer=close,
304
+ )
305
+
306
+ async def server_version(self) -> models.ServerVersion:
307
+ """GET /version — the server's name + workspace version,
308
+ unauthenticated. REST-only: gRPC raises ``UnsupportedError``."""
309
+ return cast(models.ServerVersion, await self._server_version())
310
+
311
+ async def close(self) -> None:
312
+ result = self._closer()
313
+ if asyncio.iscoroutine(result):
314
+ await result
315
+
316
+ async def __aenter__(self) -> AsyncMunariumClient:
317
+ return self
318
+
319
+ async def __aexit__(self, *exc: object) -> None:
320
+ await self.close()
321
+
322
+ async def propose_claim_with_retry(
323
+ self,
324
+ version_id: str,
325
+ build: Callable[[int], dict[str, Any]],
326
+ opts: WriteLoopOptions | None = None,
327
+ ) -> models.ClaimOutcome:
328
+ opts = opts or WriteLoopOptions()
329
+ head = await self.query.head(version_id)
330
+ attempt = 0
331
+ while True:
332
+ attempt += 1
333
+ try:
334
+ return cast(
335
+ models.ClaimOutcome,
336
+ await self.commands.propose_claim(
337
+ version_id, expected_head=head, **build(head)
338
+ ),
339
+ )
340
+ except HeadConflictError as e:
341
+ if attempt >= opts.max_attempts:
342
+ raise
343
+ await sleep_async(attempt)
344
+ head = e.actual if e.actual > 0 else await self.query.head(version_id)
345
+
346
+
347
+ class _Threaded:
348
+ """Async adapter over a sync plane: every method call runs in a worker
349
+ thread (grpcio sync stubs are thread-safe). Wrappers are cached on
350
+ first access, so hot loops pay a plain attribute lookup."""
351
+
352
+ def __init__(self, inner: Any) -> None:
353
+ self._inner = inner
354
+
355
+ def __getattr__(self, name: str) -> Any:
356
+ fn = getattr(self._inner, name)
357
+
358
+ async def call(*args: Any, **kwargs: Any) -> Any:
359
+ return await asyncio.to_thread(fn, *args, **kwargs)
360
+
361
+ object.__setattr__(self, name, call)
362
+ return call
363
+
364
+
365
+ class _ThreadedSessions(_Threaded):
366
+ """The sessions plane's adapter: ``turn_stream`` must be an ASYNC
367
+ GENERATOR (so ``async for`` works on every async client), and on gRPC
368
+ it raises the typed ``UnsupportedError`` on the first iteration — the
369
+ same moment the REST twin surfaces its pre-stream failures."""
370
+
371
+ async def turn_stream(
372
+ self,
373
+ session_id: str,
374
+ *,
375
+ query: str,
376
+ top_k: int | None = None,
377
+ complete: bool | None = None,
378
+ model_override: models.ModelOverride | dict[str, Any] | None = None,
379
+ research_profile: str | None = None,
380
+ ) -> AsyncIterator[models.TurnStreamEvent]:
381
+ # The sync plane raises UnsupportedError; nothing is ever yielded.
382
+ for item in self._inner.turn_stream(
383
+ session_id,
384
+ query=query,
385
+ top_k=top_k,
386
+ complete=complete,
387
+ model_override=model_override,
388
+ research_profile=research_profile,
389
+ ):
390
+ yield item
@@ -0,0 +1,70 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Replayable chunk sources for content-addressed uploads.
3
+
4
+ An upload is idempotent by content address, so a transient failure is safe to
5
+ retry — but retrying needs a FRESH iterator. Callers therefore pass either
6
+ raw ``bytes`` or a zero-arg callable that builds the chunk iterable, and the
7
+ transports call it once per attempt.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import AsyncIterable, Callable, Iterable
13
+
14
+ from ._errors import InvalidInputError
15
+
16
+ #: bytes, or a factory producing a fresh chunk iterable per attempt.
17
+ ChunkSource = bytes | Callable[[], Iterable[bytes]] | Callable[[], AsyncIterable[bytes]]
18
+
19
+
20
+ def chunks_from_bytes(data: bytes, chunk_size: int = 64 * 1024) -> Callable[[], Iterable[bytes]]:
21
+ """A replayable source that re-slices in-memory bytes per attempt."""
22
+
23
+ def build() -> Iterable[bytes]:
24
+ return (data[i : i + chunk_size] for i in range(0, len(data), chunk_size))
25
+
26
+ return build
27
+
28
+
29
+ def chunks_from_list(chunks: list[bytes]) -> Callable[[], Iterable[bytes]]:
30
+ """A replayable source over a pre-split chunk list."""
31
+
32
+ def build() -> Iterable[bytes]:
33
+ return iter(chunks)
34
+
35
+ return build
36
+
37
+
38
+ def resolve_chunks(source: ChunkSource) -> bytes | Iterable[bytes] | AsyncIterable[bytes]:
39
+ """Build one attempt's content from a chunk source.
40
+
41
+ Rejects a bare iterator up front: a one-shot iterable would be exhausted
42
+ by the first attempt and the retry would silently upload ZERO bytes —
43
+ which, without a declared hash, the server happily stores and returns as
44
+ ``already_existed``. Callers pass bytes or a factory.
45
+ """
46
+ if isinstance(source, (bytes, bytearray, memoryview)):
47
+ return bytes(source)
48
+ if callable(source):
49
+ return source()
50
+ raise InvalidInputError(
51
+ "put_source needs a REPLAYABLE chunk source: pass bytes, or a zero-arg "
52
+ "callable returning a fresh iterable (see chunks_from_bytes / "
53
+ "chunks_from_list). A bare iterator cannot be re-read on retry.",
54
+ )
55
+
56
+
57
+ async def as_async_chunks(
58
+ built: bytes | Iterable[bytes] | AsyncIterable[bytes],
59
+ ) -> AsyncIterable[bytes]:
60
+ """Adapt any built source to the async iterable httpx's async transport
61
+ requires — a sync generator would trip an assertion deep inside httpx."""
62
+ if isinstance(built, (bytes, bytearray, memoryview)):
63
+ yield bytes(built)
64
+ return
65
+ if isinstance(built, AsyncIterable):
66
+ async for chunk in built:
67
+ yield chunk
68
+ return
69
+ for chunk in built:
70
+ yield chunk