isolate-tx 0.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.
- isolate_tx/__init__.py +55 -0
- isolate_tx/_async.py +276 -0
- isolate_tx/_client.py +493 -0
- isolate_tx/_errors.py +149 -0
- isolate_tx/_http.py +81 -0
- isolate_tx/_version.py +1 -0
- isolate_tx/py.typed +0 -0
- isolate_tx-0.1.0.dist-info/METADATA +342 -0
- isolate_tx-0.1.0.dist-info/RECORD +11 -0
- isolate_tx-0.1.0.dist-info/WHEEL +4 -0
- isolate_tx-0.1.0.dist-info/licenses/LICENSE +21 -0
isolate_tx/__init__.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Python client for Isolate, a transaction server for concurrent AI agents.
|
|
2
|
+
|
|
3
|
+
Quick example::
|
|
4
|
+
|
|
5
|
+
from isolate_tx import Isolate
|
|
6
|
+
|
|
7
|
+
iso = Isolate() # $ISOLATE_URL or http://localhost:7070
|
|
8
|
+
|
|
9
|
+
def approve(tx):
|
|
10
|
+
budget = int(tx.read("refunds/account-42") or "0")
|
|
11
|
+
if budget < 7000:
|
|
12
|
+
return False
|
|
13
|
+
tx.write("refunds/account-42", str(budget - 7000))
|
|
14
|
+
tx.after_commit("issue-refund", {"amount": 7000})
|
|
15
|
+
return True
|
|
16
|
+
|
|
17
|
+
approved = iso.run(approve, agent="refund-agent", isolation="serializable")
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from ._async import AsyncIsolate, AsyncTransaction
|
|
21
|
+
from ._client import CommitResult, Isolate, Transaction
|
|
22
|
+
from ._errors import (
|
|
23
|
+
Fenced,
|
|
24
|
+
InDoubt,
|
|
25
|
+
InvalidRequest,
|
|
26
|
+
IsolateConnectionError,
|
|
27
|
+
IsolateError,
|
|
28
|
+
TooManyTransactions,
|
|
29
|
+
TransactionNotActive,
|
|
30
|
+
TransactionNotFound,
|
|
31
|
+
TxAborted,
|
|
32
|
+
Unauthorized,
|
|
33
|
+
UnknownEffect,
|
|
34
|
+
)
|
|
35
|
+
from ._version import __version__
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"Isolate",
|
|
39
|
+
"AsyncIsolate",
|
|
40
|
+
"Transaction",
|
|
41
|
+
"AsyncTransaction",
|
|
42
|
+
"CommitResult",
|
|
43
|
+
"IsolateError",
|
|
44
|
+
"TxAborted",
|
|
45
|
+
"TransactionNotActive",
|
|
46
|
+
"TransactionNotFound",
|
|
47
|
+
"InvalidRequest",
|
|
48
|
+
"Unauthorized",
|
|
49
|
+
"UnknownEffect",
|
|
50
|
+
"TooManyTransactions",
|
|
51
|
+
"InDoubt",
|
|
52
|
+
"Fenced",
|
|
53
|
+
"IsolateConnectionError",
|
|
54
|
+
"__version__",
|
|
55
|
+
]
|
isolate_tx/_async.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"""Asyncio client: :class:`AsyncIsolate` and :class:`AsyncTransaction`.
|
|
2
|
+
|
|
3
|
+
Why threads instead of an async HTTP library: the package has zero runtime dependencies, and
|
|
4
|
+
the standard library has no async HTTP client. Each call runs the blocking :mod:`urllib` request
|
|
5
|
+
in a worker thread via :func:`asyncio.to_thread`, so the event loop is never blocked. Server
|
|
6
|
+
round trips are short next to LLM calls, so the thread hop costs little in practice.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import functools
|
|
13
|
+
import inspect
|
|
14
|
+
from types import TracebackType
|
|
15
|
+
from typing import (
|
|
16
|
+
Any,
|
|
17
|
+
Awaitable,
|
|
18
|
+
Callable,
|
|
19
|
+
Dict,
|
|
20
|
+
Iterable,
|
|
21
|
+
Mapping,
|
|
22
|
+
Optional,
|
|
23
|
+
Type,
|
|
24
|
+
TypeVar,
|
|
25
|
+
Union,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
from . import _client
|
|
29
|
+
from ._client import ACTIVE, CommitResult, Isolate, Transaction, _backoff_delay
|
|
30
|
+
from ._errors import TooManyTransactions, TxAborted
|
|
31
|
+
|
|
32
|
+
T = TypeVar("T")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AsyncTransaction:
|
|
36
|
+
"""Async view of a :class:`Transaction`. Use with ``async with iso.transaction(...) as tx``.
|
|
37
|
+
|
|
38
|
+
Commits when the block exits normally (result in :attr:`result`), aborts if it raises.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, tx: Transaction) -> None:
|
|
42
|
+
self._tx = tx
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def sync(self) -> Transaction:
|
|
46
|
+
"""The underlying synchronous :class:`Transaction`."""
|
|
47
|
+
return self._tx
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def tx_id(self) -> Optional[str]:
|
|
51
|
+
"""Server-assigned transaction id (a string), once begun."""
|
|
52
|
+
return self._tx.tx_id
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def snapshot_ts(self) -> Optional[str]:
|
|
56
|
+
"""Snapshot timestamp (a string), once begun."""
|
|
57
|
+
return self._tx.snapshot_ts
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def result(self) -> Optional[CommitResult]:
|
|
61
|
+
"""The :class:`CommitResult` after a successful commit, else ``None``."""
|
|
62
|
+
return self._tx.result
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def status(self) -> str:
|
|
66
|
+
"""Client-side state: ``"NEW"``, ``"ACTIVE"``, ``"COMMITTED"`` or ``"ABORTED"``."""
|
|
67
|
+
return self._tx.status
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def agent(self) -> str:
|
|
71
|
+
"""The agent name this transaction runs as."""
|
|
72
|
+
return self._tx.agent
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def retry_of(self) -> Optional[str]:
|
|
76
|
+
"""The ``txId`` of the attempt this one retries, if any."""
|
|
77
|
+
return self._tx.retry_of
|
|
78
|
+
|
|
79
|
+
async def begin(self) -> "AsyncTransaction":
|
|
80
|
+
"""Begin on the server. Called for you by ``async with``."""
|
|
81
|
+
await asyncio.to_thread(self._tx.begin)
|
|
82
|
+
return self
|
|
83
|
+
|
|
84
|
+
async def read(self, key: str) -> Optional[str]:
|
|
85
|
+
"""Read one key at the snapshot; ``None`` if absent."""
|
|
86
|
+
return await asyncio.to_thread(self._tx.read, key)
|
|
87
|
+
|
|
88
|
+
async def read_many(self, keys: Iterable[str]) -> Dict[str, Optional[str]]:
|
|
89
|
+
"""Read several keys in one round trip."""
|
|
90
|
+
return await asyncio.to_thread(self._tx.read_many, list(keys))
|
|
91
|
+
|
|
92
|
+
async def read_json(self, key: str, default: Any = None) -> Any:
|
|
93
|
+
"""Read a key and decode it as JSON; ``default`` if absent."""
|
|
94
|
+
return await asyncio.to_thread(self._tx.read_json, key, default)
|
|
95
|
+
|
|
96
|
+
async def write(self, key: str, value: Optional[str]) -> None:
|
|
97
|
+
"""Buffer a write (``None`` deletes)."""
|
|
98
|
+
await asyncio.to_thread(self._tx.write, key, value)
|
|
99
|
+
|
|
100
|
+
async def write_many(self, writes: Mapping[str, Optional[str]]) -> None:
|
|
101
|
+
"""Buffer several writes in one round trip."""
|
|
102
|
+
await asyncio.to_thread(self._tx.write_many, dict(writes))
|
|
103
|
+
|
|
104
|
+
async def write_json(self, key: str, obj: Any) -> None:
|
|
105
|
+
"""Encode ``obj`` as JSON and buffer it."""
|
|
106
|
+
await asyncio.to_thread(self._tx.write_json, key, obj)
|
|
107
|
+
|
|
108
|
+
async def delete(self, key: str) -> None:
|
|
109
|
+
"""Buffer a delete of ``key``."""
|
|
110
|
+
await asyncio.to_thread(self._tx.delete, key)
|
|
111
|
+
|
|
112
|
+
async def after_commit(self, name: str, payload: Any) -> None:
|
|
113
|
+
"""Queue an effect delivered only after commit (str payload as-is, else ``json.dumps``)."""
|
|
114
|
+
await asyncio.to_thread(self._tx.after_commit, name, payload)
|
|
115
|
+
|
|
116
|
+
async def record_tokens(self, tokens: int) -> int:
|
|
117
|
+
"""Add tokens spent in this attempt; returns the running total."""
|
|
118
|
+
return await asyncio.to_thread(self._tx.record_tokens, tokens)
|
|
119
|
+
|
|
120
|
+
async def commit(self) -> CommitResult:
|
|
121
|
+
"""Validate and commit; raises :class:`TxAborted` on conflict."""
|
|
122
|
+
return await asyncio.to_thread(self._tx.commit)
|
|
123
|
+
|
|
124
|
+
async def abort(self) -> None:
|
|
125
|
+
"""Throw the work away. Safe to call more than once."""
|
|
126
|
+
await asyncio.to_thread(self._tx.abort)
|
|
127
|
+
|
|
128
|
+
async def info(self) -> Dict[str, Any]:
|
|
129
|
+
"""Server-side status (``GET /v1/tx/{txId}``)."""
|
|
130
|
+
return await asyncio.to_thread(self._tx.info)
|
|
131
|
+
|
|
132
|
+
async def __aenter__(self) -> "AsyncTransaction":
|
|
133
|
+
return await self.begin()
|
|
134
|
+
|
|
135
|
+
async def __aexit__(
|
|
136
|
+
self,
|
|
137
|
+
exc_type: Optional[Type[BaseException]],
|
|
138
|
+
exc: Optional[BaseException],
|
|
139
|
+
tb: Optional[TracebackType],
|
|
140
|
+
) -> None:
|
|
141
|
+
await asyncio.to_thread(self._tx.__exit__, exc_type, exc, tb)
|
|
142
|
+
|
|
143
|
+
def __repr__(self) -> str:
|
|
144
|
+
return f"Async{self._tx!r}"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class AsyncIsolate:
|
|
148
|
+
"""Asyncio client for an Isolate server. Same arguments and defaults as :class:`Isolate`.
|
|
149
|
+
|
|
150
|
+
Implemented with :func:`asyncio.to_thread` over the synchronous client to keep zero
|
|
151
|
+
runtime dependencies.
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
def __init__(
|
|
155
|
+
self,
|
|
156
|
+
url: Optional[str] = None,
|
|
157
|
+
api_key: Optional[str] = None,
|
|
158
|
+
timeout: float = 30.0,
|
|
159
|
+
) -> None:
|
|
160
|
+
self._sync = Isolate(url, api_key=api_key, timeout=timeout)
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def sync(self) -> Isolate:
|
|
164
|
+
"""The underlying synchronous :class:`Isolate` client."""
|
|
165
|
+
return self._sync
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def url(self) -> str:
|
|
169
|
+
"""The server base URL."""
|
|
170
|
+
return self._sync.url
|
|
171
|
+
|
|
172
|
+
def __repr__(self) -> str:
|
|
173
|
+
return f"AsyncIsolate({self.url!r})"
|
|
174
|
+
|
|
175
|
+
def transaction(self, agent: str, **options: Any) -> AsyncTransaction:
|
|
176
|
+
"""Create a transaction for ``async with``. Options as in :meth:`Isolate.transaction`."""
|
|
177
|
+
return AsyncTransaction(self._sync.transaction(agent, **options))
|
|
178
|
+
|
|
179
|
+
async def begin(self, agent: str, **options: Any) -> AsyncTransaction:
|
|
180
|
+
"""Begin a transaction now and return it (for use without ``async with``)."""
|
|
181
|
+
return await self.transaction(agent, **options).begin()
|
|
182
|
+
|
|
183
|
+
async def run(
|
|
184
|
+
self,
|
|
185
|
+
fn: Callable[[AsyncTransaction], Union[Awaitable[T], T]],
|
|
186
|
+
*,
|
|
187
|
+
agent: str,
|
|
188
|
+
isolation: Optional[str] = None,
|
|
189
|
+
policy: Optional[str] = None,
|
|
190
|
+
expected_tokens: Optional[int] = None,
|
|
191
|
+
lock_timeout_ms: Optional[int] = None,
|
|
192
|
+
idle_timeout_ms: Optional[int] = None,
|
|
193
|
+
max_attempts: int = 8,
|
|
194
|
+
backoff_base: float = 0.01,
|
|
195
|
+
backoff_cap: float = 1.0,
|
|
196
|
+
) -> T:
|
|
197
|
+
"""Async :meth:`Isolate.run`: ``await fn(tx)``, commit, retry retryable aborts with backoff.
|
|
198
|
+
|
|
199
|
+
``fn`` is usually an ``async def``; a plain function also works.
|
|
200
|
+
"""
|
|
201
|
+
if max_attempts < 1:
|
|
202
|
+
raise ValueError("max_attempts must be >= 1")
|
|
203
|
+
retry_of: Optional[str] = None
|
|
204
|
+
attempt = 0
|
|
205
|
+
while True:
|
|
206
|
+
attempt += 1
|
|
207
|
+
atx = self.transaction(
|
|
208
|
+
agent,
|
|
209
|
+
isolation=isolation,
|
|
210
|
+
policy=policy,
|
|
211
|
+
expected_tokens=expected_tokens,
|
|
212
|
+
lock_timeout_ms=lock_timeout_ms,
|
|
213
|
+
idle_timeout_ms=idle_timeout_ms,
|
|
214
|
+
retry_of=retry_of,
|
|
215
|
+
)
|
|
216
|
+
tx = atx.sync
|
|
217
|
+
try:
|
|
218
|
+
await atx.begin()
|
|
219
|
+
value = fn(atx)
|
|
220
|
+
if inspect.isawaitable(value):
|
|
221
|
+
value = await value
|
|
222
|
+
if tx._abort_error is not None:
|
|
223
|
+
raise tx._abort_error
|
|
224
|
+
if tx.status == ACTIVE:
|
|
225
|
+
await atx.commit()
|
|
226
|
+
return value
|
|
227
|
+
except TxAborted as exc:
|
|
228
|
+
if not exc.retryable or attempt >= max_attempts:
|
|
229
|
+
raise
|
|
230
|
+
retry_of = tx.tx_id or retry_of
|
|
231
|
+
except TooManyTransactions:
|
|
232
|
+
if attempt >= max_attempts:
|
|
233
|
+
raise
|
|
234
|
+
finally:
|
|
235
|
+
if tx.status == ACTIVE:
|
|
236
|
+
await asyncio.to_thread(tx._abort_quietly)
|
|
237
|
+
await asyncio.sleep(
|
|
238
|
+
_backoff_delay(attempt, backoff_base, backoff_cap, _client._random)
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
def transactional(
|
|
242
|
+
self,
|
|
243
|
+
agent: Optional[str] = None,
|
|
244
|
+
*,
|
|
245
|
+
max_attempts: int = 8,
|
|
246
|
+
**options: Any,
|
|
247
|
+
) -> Callable[[Callable[..., Awaitable[T]]], Callable[..., Awaitable[T]]]:
|
|
248
|
+
"""Decorator form of :meth:`run` for ``async def fn(tx, ...)``; ``tx`` is injected."""
|
|
249
|
+
|
|
250
|
+
def decorator(fn: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:
|
|
251
|
+
name: str = agent or str(getattr(fn, "__name__", "agent"))
|
|
252
|
+
|
|
253
|
+
@functools.wraps(fn)
|
|
254
|
+
async def wrapper(*args: Any, **kwargs: Any) -> T:
|
|
255
|
+
return await self.run(
|
|
256
|
+
lambda tx: fn(tx, *args, **kwargs),
|
|
257
|
+
agent=name,
|
|
258
|
+
max_attempts=max_attempts,
|
|
259
|
+
**options,
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
return wrapper
|
|
263
|
+
|
|
264
|
+
return decorator
|
|
265
|
+
|
|
266
|
+
async def get(self, key: str) -> Optional[str]:
|
|
267
|
+
"""Latest committed value of ``key``, or ``None``."""
|
|
268
|
+
return await asyncio.to_thread(self._sync.get, key)
|
|
269
|
+
|
|
270
|
+
async def stats(self) -> Dict[str, Any]:
|
|
271
|
+
"""Server statistics (``GET /v1/stats``)."""
|
|
272
|
+
return await asyncio.to_thread(self._sync.stats)
|
|
273
|
+
|
|
274
|
+
async def health(self) -> Dict[str, Any]:
|
|
275
|
+
"""Health check (``GET /healthz``)."""
|
|
276
|
+
return await asyncio.to_thread(self._sync.health)
|