lork 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.
- lork/__init__.py +37 -0
- lork/client/__init__.py +45 -0
- lork/client/client.py +413 -0
- lork/client/exceptions.py +44 -0
- lork/client/futures.py +84 -0
- lork/client/py.typed +1 -0
- lork/py.typed +1 -0
- lork/schemas.py +148 -0
- lork/server/__init__.py +6 -0
- lork/server/app.py +380 -0
- lork/server/futures.py +101 -0
- lork/server/models.py +141 -0
- lork/server/sessions.py +325 -0
- lork/trainer.py +396 -0
- lork/wire.py +290 -0
- lork-0.1.0.dist-info/METADATA +198 -0
- lork-0.1.0.dist-info/RECORD +20 -0
- lork-0.1.0.dist-info/WHEEL +5 -0
- lork-0.1.0.dist-info/licenses/LICENSE +182 -0
- lork-0.1.0.dist-info/top_level.txt +1 -0
lork/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""lork: Open-source low-level LoRA fine-tuning primitives and client SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
from lork.wire import (
|
|
8
|
+
OptimParams,
|
|
9
|
+
SampleParams,
|
|
10
|
+
TrainerInitConfig,
|
|
11
|
+
WireBatch,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from lork.schemas import ForwardBackwardBatch
|
|
16
|
+
from lork.trainer import LoraTrainer
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ForwardBackwardBatch",
|
|
20
|
+
"LoraTrainer",
|
|
21
|
+
"OptimParams",
|
|
22
|
+
"SampleParams",
|
|
23
|
+
"TrainerInitConfig",
|
|
24
|
+
"WireBatch",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def __getattr__(name: str) -> Any:
|
|
29
|
+
if name == "LoraTrainer":
|
|
30
|
+
from lork.trainer import LoraTrainer
|
|
31
|
+
|
|
32
|
+
return LoraTrainer
|
|
33
|
+
if name == "ForwardBackwardBatch":
|
|
34
|
+
from lork.schemas import ForwardBackwardBatch
|
|
35
|
+
|
|
36
|
+
return ForwardBackwardBatch
|
|
37
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
lork/client/__init__.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Lightweight synchronous Python SDK for lork."""
|
|
2
|
+
|
|
3
|
+
from lork.client.client import ServiceClient, TrainingClient, validate_batch
|
|
4
|
+
from lork.client.exceptions import (
|
|
5
|
+
AmbiguousSubmissionError,
|
|
6
|
+
AuthError,
|
|
7
|
+
LorkError,
|
|
8
|
+
LorkTimeoutError,
|
|
9
|
+
RemoteOpError,
|
|
10
|
+
ServerBusyError,
|
|
11
|
+
SessionNotFoundError,
|
|
12
|
+
ValidationError,
|
|
13
|
+
)
|
|
14
|
+
from lork.client.futures import APIFuture
|
|
15
|
+
from lork.wire import (
|
|
16
|
+
ForwardBackwardResult,
|
|
17
|
+
OptimParams,
|
|
18
|
+
OptimStepResult,
|
|
19
|
+
SampleParams,
|
|
20
|
+
SampleResult,
|
|
21
|
+
StateResult,
|
|
22
|
+
WireBatch,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"APIFuture",
|
|
27
|
+
"AmbiguousSubmissionError",
|
|
28
|
+
"AuthError",
|
|
29
|
+
"ForwardBackwardResult",
|
|
30
|
+
"LorkError",
|
|
31
|
+
"LorkTimeoutError",
|
|
32
|
+
"OptimParams",
|
|
33
|
+
"OptimStepResult",
|
|
34
|
+
"RemoteOpError",
|
|
35
|
+
"SampleParams",
|
|
36
|
+
"SampleResult",
|
|
37
|
+
"ServerBusyError",
|
|
38
|
+
"ServiceClient",
|
|
39
|
+
"SessionNotFoundError",
|
|
40
|
+
"StateResult",
|
|
41
|
+
"TrainingClient",
|
|
42
|
+
"ValidationError",
|
|
43
|
+
"WireBatch",
|
|
44
|
+
"validate_batch",
|
|
45
|
+
]
|
lork/client/client.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
"""Synchronous Python SDK for lork with safe retries and zero heavy ML imports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import random
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
from typing import Any, Literal
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
from pydantic import ValidationError as PydanticValidationError
|
|
13
|
+
|
|
14
|
+
from lork.client.exceptions import (
|
|
15
|
+
AmbiguousSubmissionError,
|
|
16
|
+
AuthError,
|
|
17
|
+
LorkError,
|
|
18
|
+
ServerBusyError,
|
|
19
|
+
SessionNotFoundError,
|
|
20
|
+
ValidationError,
|
|
21
|
+
)
|
|
22
|
+
from lork.client.futures import APIFuture
|
|
23
|
+
from lork.wire import (
|
|
24
|
+
CreateSessionRequest,
|
|
25
|
+
ErrorEnvelope,
|
|
26
|
+
ForwardBackwardResult,
|
|
27
|
+
ForwardBackwardWireRequest,
|
|
28
|
+
FutureStatusResponse,
|
|
29
|
+
FutureSubmittedResponse,
|
|
30
|
+
OptimParams,
|
|
31
|
+
OptimStepResult,
|
|
32
|
+
OptimStepWireRequest,
|
|
33
|
+
SampleParams,
|
|
34
|
+
SampleResult,
|
|
35
|
+
SampleWireRequest,
|
|
36
|
+
SessionCreatedResult,
|
|
37
|
+
StateResult,
|
|
38
|
+
StateWireRequest,
|
|
39
|
+
WireBatch,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
logger = logging.getLogger("lork.client")
|
|
43
|
+
|
|
44
|
+
_PRE_SEND_EXCEPTIONS = (
|
|
45
|
+
httpx.ConnectError,
|
|
46
|
+
httpx.ConnectTimeout,
|
|
47
|
+
httpx.PoolTimeout,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def validate_batch(batch: dict[str, Any] | WireBatch) -> WireBatch:
|
|
52
|
+
"""Validate nested-list batch shapes client-side before sending over HTTP."""
|
|
53
|
+
if isinstance(batch, WireBatch):
|
|
54
|
+
return batch
|
|
55
|
+
try:
|
|
56
|
+
return WireBatch.model_validate(batch)
|
|
57
|
+
except PydanticValidationError as exc:
|
|
58
|
+
raise ValidationError(str(exc)) from exc
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _parse_error_body(response: httpx.Response) -> tuple[str, str]:
|
|
62
|
+
try:
|
|
63
|
+
envelope = ErrorEnvelope.model_validate(response.json())
|
|
64
|
+
return envelope.error.code, envelope.error.message
|
|
65
|
+
except (ValueError, PydanticValidationError):
|
|
66
|
+
return f"http_{response.status_code}", response.text or response.reason_phrase
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _has_structured_error_envelope(response: httpx.Response) -> bool:
|
|
70
|
+
try:
|
|
71
|
+
ErrorEnvelope.model_validate(response.json())
|
|
72
|
+
except (ValueError, PydanticValidationError):
|
|
73
|
+
return False
|
|
74
|
+
return True
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _parse_retry_after(header_val: str | None) -> float | None:
|
|
78
|
+
if header_val is None:
|
|
79
|
+
return None
|
|
80
|
+
try:
|
|
81
|
+
parsed = float(header_val.strip())
|
|
82
|
+
except ValueError:
|
|
83
|
+
return None
|
|
84
|
+
return max(0.0, parsed)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class TrainingClient:
|
|
88
|
+
"""Session-scoped training client wrapping one remote LoRA session."""
|
|
89
|
+
|
|
90
|
+
def __init__(self, service_client: ServiceClient, session_id: str) -> None:
|
|
91
|
+
self._client = service_client
|
|
92
|
+
self.session_id = session_id
|
|
93
|
+
self._closed = False
|
|
94
|
+
|
|
95
|
+
def __enter__(self) -> TrainingClient:
|
|
96
|
+
return self
|
|
97
|
+
|
|
98
|
+
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
99
|
+
self.close()
|
|
100
|
+
|
|
101
|
+
def close(self) -> None:
|
|
102
|
+
"""Delete the remote session, freeing server resources."""
|
|
103
|
+
if self._closed:
|
|
104
|
+
return
|
|
105
|
+
self._closed = True
|
|
106
|
+
self._client.delete_session(self.session_id)
|
|
107
|
+
|
|
108
|
+
def forward_backward(
|
|
109
|
+
self,
|
|
110
|
+
batch: dict[str, Any] | WireBatch,
|
|
111
|
+
loss_fn: str | list[list[float]] = "cross_entropy",
|
|
112
|
+
return_logprobs: bool = True,
|
|
113
|
+
) -> APIFuture[ForwardBackwardResult]:
|
|
114
|
+
"""Submit forward_backward asynchronously; never retries ambiguous failures."""
|
|
115
|
+
validated_batch = validate_batch(batch)
|
|
116
|
+
try:
|
|
117
|
+
wire_req = ForwardBackwardWireRequest.model_validate(
|
|
118
|
+
{
|
|
119
|
+
"batch": validated_batch,
|
|
120
|
+
"loss_fn": loss_fn,
|
|
121
|
+
"return_logprobs": return_logprobs,
|
|
122
|
+
}
|
|
123
|
+
)
|
|
124
|
+
except PydanticValidationError as exc:
|
|
125
|
+
raise ValidationError(str(exc)) from exc
|
|
126
|
+
|
|
127
|
+
submitted = self._client._post_op(
|
|
128
|
+
f"/v1/sessions/{self.session_id}/forward_backward",
|
|
129
|
+
payload=wire_req.model_dump(),
|
|
130
|
+
idempotent=False,
|
|
131
|
+
)
|
|
132
|
+
return APIFuture(
|
|
133
|
+
client=self._client,
|
|
134
|
+
future_id=submitted.future_id,
|
|
135
|
+
parser=ForwardBackwardResult.model_validate,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def optim_step(
|
|
139
|
+
self,
|
|
140
|
+
optim_params: OptimParams | dict[str, Any],
|
|
141
|
+
) -> APIFuture[OptimStepResult]:
|
|
142
|
+
"""Submit optim_step with an SDK-generated UUID step_id (safe to retry)."""
|
|
143
|
+
step_id = f"step_{uuid.uuid4().hex}"
|
|
144
|
+
try:
|
|
145
|
+
wire_req = OptimStepWireRequest.model_validate(
|
|
146
|
+
{"step_id": step_id, "optim_params": optim_params}
|
|
147
|
+
)
|
|
148
|
+
except PydanticValidationError as exc:
|
|
149
|
+
raise ValidationError(str(exc)) from exc
|
|
150
|
+
|
|
151
|
+
submitted = self._client._post_op(
|
|
152
|
+
f"/v1/sessions/{self.session_id}/optim_step",
|
|
153
|
+
payload=wire_req.model_dump(),
|
|
154
|
+
idempotent=True,
|
|
155
|
+
)
|
|
156
|
+
return APIFuture(
|
|
157
|
+
client=self._client,
|
|
158
|
+
future_id=submitted.future_id,
|
|
159
|
+
parser=OptimStepResult.model_validate,
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
def sample(
|
|
163
|
+
self,
|
|
164
|
+
prompts: list[str],
|
|
165
|
+
params: SampleParams | dict[str, Any],
|
|
166
|
+
) -> APIFuture[SampleResult]:
|
|
167
|
+
"""Submit autoregressive sampling asynchronously."""
|
|
168
|
+
try:
|
|
169
|
+
wire_req = SampleWireRequest.model_validate(
|
|
170
|
+
{"prompts": prompts, "params": params}
|
|
171
|
+
)
|
|
172
|
+
except PydanticValidationError as exc:
|
|
173
|
+
raise ValidationError(str(exc)) from exc
|
|
174
|
+
|
|
175
|
+
submitted = self._client._post_op(
|
|
176
|
+
f"/v1/sessions/{self.session_id}/sample",
|
|
177
|
+
payload=wire_req.model_dump(),
|
|
178
|
+
idempotent=False,
|
|
179
|
+
)
|
|
180
|
+
return APIFuture(
|
|
181
|
+
client=self._client,
|
|
182
|
+
future_id=submitted.future_id,
|
|
183
|
+
parser=SampleResult.model_validate,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def save_state(self, name: str) -> APIFuture[StateResult]:
|
|
187
|
+
"""Submit save_state asynchronously."""
|
|
188
|
+
try:
|
|
189
|
+
wire_req = StateWireRequest.model_validate({"name": name})
|
|
190
|
+
except PydanticValidationError as exc:
|
|
191
|
+
raise ValidationError(str(exc)) from exc
|
|
192
|
+
|
|
193
|
+
submitted = self._client._post_op(
|
|
194
|
+
f"/v1/sessions/{self.session_id}/save_state",
|
|
195
|
+
payload=wire_req.model_dump(),
|
|
196
|
+
idempotent=False,
|
|
197
|
+
)
|
|
198
|
+
return APIFuture(
|
|
199
|
+
client=self._client,
|
|
200
|
+
future_id=submitted.future_id,
|
|
201
|
+
parser=StateResult.model_validate,
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
def load_state(self, name: str) -> APIFuture[StateResult]:
|
|
205
|
+
"""Submit load_state asynchronously."""
|
|
206
|
+
try:
|
|
207
|
+
wire_req = StateWireRequest.model_validate({"name": name})
|
|
208
|
+
except PydanticValidationError as exc:
|
|
209
|
+
raise ValidationError(str(exc)) from exc
|
|
210
|
+
|
|
211
|
+
submitted = self._client._post_op(
|
|
212
|
+
f"/v1/sessions/{self.session_id}/load_state",
|
|
213
|
+
payload=wire_req.model_dump(),
|
|
214
|
+
idempotent=False,
|
|
215
|
+
)
|
|
216
|
+
return APIFuture(
|
|
217
|
+
client=self._client,
|
|
218
|
+
future_id=submitted.future_id,
|
|
219
|
+
parser=StateResult.model_validate,
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class ServiceClient:
|
|
224
|
+
"""Top-level HTTP client for connecting to a lork server."""
|
|
225
|
+
|
|
226
|
+
def __init__(
|
|
227
|
+
self,
|
|
228
|
+
base_url: str,
|
|
229
|
+
api_key: str,
|
|
230
|
+
timeout: float = 60.0,
|
|
231
|
+
max_retries: int = 3,
|
|
232
|
+
backoff_base: float = 0.1,
|
|
233
|
+
) -> None:
|
|
234
|
+
if not api_key.strip():
|
|
235
|
+
raise ValidationError("api_key must not be empty")
|
|
236
|
+
if max_retries < 0:
|
|
237
|
+
raise ValidationError("max_retries must be >= 0")
|
|
238
|
+
self.base_url = base_url.rstrip("/")
|
|
239
|
+
self._timeout = timeout
|
|
240
|
+
self._max_retries = max_retries
|
|
241
|
+
self._backoff_base = backoff_base
|
|
242
|
+
self._http = httpx.Client(
|
|
243
|
+
base_url=self.base_url,
|
|
244
|
+
headers={"Authorization": f"Bearer {api_key}"},
|
|
245
|
+
timeout=timeout,
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
def __enter__(self) -> ServiceClient:
|
|
249
|
+
return self
|
|
250
|
+
|
|
251
|
+
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
|
252
|
+
self.close()
|
|
253
|
+
|
|
254
|
+
def close(self) -> None:
|
|
255
|
+
"""Close the underlying HTTP connection pool."""
|
|
256
|
+
self._http.close()
|
|
257
|
+
|
|
258
|
+
def create_training_client(
|
|
259
|
+
self,
|
|
260
|
+
base_model: str,
|
|
261
|
+
rank: int,
|
|
262
|
+
alpha: float,
|
|
263
|
+
target_modules: list[str],
|
|
264
|
+
device: str | None = None,
|
|
265
|
+
dtype: Literal["float32", "bfloat16", "float16"] | None = None,
|
|
266
|
+
) -> TrainingClient:
|
|
267
|
+
"""Create a remote training session, await initialization, and return TrainingClient."""
|
|
268
|
+
try:
|
|
269
|
+
req = CreateSessionRequest(
|
|
270
|
+
base_model=base_model,
|
|
271
|
+
rank=rank,
|
|
272
|
+
alpha=alpha,
|
|
273
|
+
target_modules=target_modules,
|
|
274
|
+
device=device,
|
|
275
|
+
dtype=dtype,
|
|
276
|
+
)
|
|
277
|
+
req.to_trainer_config(default_device=device or "cpu")
|
|
278
|
+
except PydanticValidationError as exc:
|
|
279
|
+
raise ValidationError(str(exc)) from exc
|
|
280
|
+
|
|
281
|
+
submitted = self._post_op(
|
|
282
|
+
"/v1/sessions",
|
|
283
|
+
payload=req.model_dump(),
|
|
284
|
+
idempotent=False,
|
|
285
|
+
)
|
|
286
|
+
fut: APIFuture[SessionCreatedResult] = APIFuture(
|
|
287
|
+
client=self,
|
|
288
|
+
future_id=submitted.future_id,
|
|
289
|
+
parser=SessionCreatedResult.model_validate,
|
|
290
|
+
)
|
|
291
|
+
created = fut.result()
|
|
292
|
+
return TrainingClient(service_client=self, session_id=created.session_id)
|
|
293
|
+
|
|
294
|
+
def delete_session(self, session_id: str) -> None:
|
|
295
|
+
"""Delete an existing remote session."""
|
|
296
|
+
self._request(
|
|
297
|
+
"DELETE",
|
|
298
|
+
f"/v1/sessions/{session_id}",
|
|
299
|
+
idempotent=True,
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
def _post_op(
|
|
303
|
+
self,
|
|
304
|
+
path: str,
|
|
305
|
+
payload: dict[str, Any],
|
|
306
|
+
*,
|
|
307
|
+
idempotent: bool,
|
|
308
|
+
) -> FutureSubmittedResponse:
|
|
309
|
+
data = self._request("POST", path, json_body=payload, idempotent=idempotent)
|
|
310
|
+
return FutureSubmittedResponse.model_validate(data)
|
|
311
|
+
|
|
312
|
+
def _get_future(self, future_id: str, wait: float = 0.0) -> FutureStatusResponse:
|
|
313
|
+
req_timeout = max(self._timeout, wait + 10.0)
|
|
314
|
+
data = self._request(
|
|
315
|
+
"GET",
|
|
316
|
+
f"/v1/futures/{future_id}",
|
|
317
|
+
params={"wait": wait},
|
|
318
|
+
idempotent=True,
|
|
319
|
+
timeout_override=req_timeout,
|
|
320
|
+
)
|
|
321
|
+
return FutureStatusResponse.model_validate(data)
|
|
322
|
+
|
|
323
|
+
def _sleep_for_retry(self, attempt: int, retry_after: float | None = None) -> None:
|
|
324
|
+
if retry_after is not None:
|
|
325
|
+
delay = retry_after
|
|
326
|
+
else:
|
|
327
|
+
jitter = random.uniform(0.8, 1.2)
|
|
328
|
+
delay = self._backoff_base * (2**attempt) * jitter
|
|
329
|
+
time.sleep(delay)
|
|
330
|
+
|
|
331
|
+
def _raise_for_http_error(self, response: httpx.Response) -> None:
|
|
332
|
+
code, message = _parse_error_body(response)
|
|
333
|
+
status_code = response.status_code
|
|
334
|
+
if status_code == 401:
|
|
335
|
+
raise AuthError(f"{code}: {message}")
|
|
336
|
+
if status_code in (400, 403, 422):
|
|
337
|
+
raise ValidationError(f"{code}: {message}")
|
|
338
|
+
if status_code == 404:
|
|
339
|
+
raise SessionNotFoundError(f"{code}: {message}")
|
|
340
|
+
if status_code in (429, 503):
|
|
341
|
+
raise ServerBusyError(f"{code}: {message}")
|
|
342
|
+
raise LorkError(f"HTTP {status_code} ({code}): {message}")
|
|
343
|
+
|
|
344
|
+
def _request(
|
|
345
|
+
self,
|
|
346
|
+
method: str,
|
|
347
|
+
path: str,
|
|
348
|
+
*,
|
|
349
|
+
json_body: dict[str, Any] | None = None,
|
|
350
|
+
params: dict[str, Any] | None = None,
|
|
351
|
+
idempotent: bool,
|
|
352
|
+
timeout_override: float | None = None,
|
|
353
|
+
) -> dict[str, Any]:
|
|
354
|
+
for attempt in range(self._max_retries + 1):
|
|
355
|
+
try:
|
|
356
|
+
response = self._http.request(
|
|
357
|
+
method,
|
|
358
|
+
path,
|
|
359
|
+
json=json_body,
|
|
360
|
+
params=params,
|
|
361
|
+
timeout=timeout_override if timeout_override is not None else self._timeout,
|
|
362
|
+
)
|
|
363
|
+
except _PRE_SEND_EXCEPTIONS as exc:
|
|
364
|
+
logger.debug("pre_send_error method=%s path=%s attempt=%d", method, path, attempt)
|
|
365
|
+
if attempt < self._max_retries:
|
|
366
|
+
self._sleep_for_retry(attempt)
|
|
367
|
+
continue
|
|
368
|
+
raise LorkError(f"Connection failed for {method} {path}: {exc}") from exc
|
|
369
|
+
except httpx.HTTPError as exc:
|
|
370
|
+
logger.debug("transport_error method=%s path=%s attempt=%d", method, path, attempt)
|
|
371
|
+
if not idempotent:
|
|
372
|
+
raise AmbiguousSubmissionError(
|
|
373
|
+
f"Ambiguous failure on non-idempotent {method} {path}: {exc}",
|
|
374
|
+
cause=exc,
|
|
375
|
+
) from exc
|
|
376
|
+
if attempt < self._max_retries:
|
|
377
|
+
self._sleep_for_retry(attempt)
|
|
378
|
+
continue
|
|
379
|
+
raise LorkError(
|
|
380
|
+
f"Request failed after retries for {method} {path}: {exc}"
|
|
381
|
+
) from exc
|
|
382
|
+
|
|
383
|
+
logger.debug(
|
|
384
|
+
"http_response method=%s path=%s status=%d attempt=%d",
|
|
385
|
+
method,
|
|
386
|
+
path,
|
|
387
|
+
response.status_code,
|
|
388
|
+
attempt,
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
status_code = response.status_code
|
|
392
|
+
if status_code in (429, 500, 502, 503, 504):
|
|
393
|
+
can_retry_status = idempotent or status_code == 429 or (
|
|
394
|
+
status_code == 503 and _has_structured_error_envelope(response)
|
|
395
|
+
)
|
|
396
|
+
if not can_retry_status:
|
|
397
|
+
raise AmbiguousSubmissionError(
|
|
398
|
+
f"Ambiguous HTTP {status_code} on non-idempotent {method} {path}",
|
|
399
|
+
cause=LorkError(f"HTTP {status_code}: {response.text}"),
|
|
400
|
+
)
|
|
401
|
+
if attempt < self._max_retries:
|
|
402
|
+
retry_after = _parse_retry_after(response.headers.get("Retry-After"))
|
|
403
|
+
self._sleep_for_retry(attempt, retry_after=retry_after)
|
|
404
|
+
continue
|
|
405
|
+
self._raise_for_http_error(response)
|
|
406
|
+
|
|
407
|
+
if status_code >= 400:
|
|
408
|
+
self._raise_for_http_error(response)
|
|
409
|
+
|
|
410
|
+
payload: dict[str, Any] = response.json()
|
|
411
|
+
return payload
|
|
412
|
+
|
|
413
|
+
raise LorkError(f"Exhausted retries for {method} {path}")
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Typed exception hierarchy for the lork Python SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class LorkError(Exception):
|
|
7
|
+
"""Base exception for all lork SDK errors."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AuthError(LorkError):
|
|
11
|
+
"""Raised when authentication fails (HTTP 401)."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ValidationError(LorkError):
|
|
15
|
+
"""Raised when request parameters or batch shapes are invalid (HTTP 422/403 or client-side)."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SessionNotFoundError(LorkError):
|
|
19
|
+
"""Raised when a session or future does not exist or was evicted (HTTP 404)."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ServerBusyError(LorkError):
|
|
23
|
+
"""Raised when the server is at capacity or rate-limited (HTTP 429/503)."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class RemoteOpError(LorkError):
|
|
27
|
+
"""Raised when an async server operation fails during execution."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, code: str, remote_message: str) -> None:
|
|
30
|
+
self.code = code
|
|
31
|
+
self.remote_message = remote_message
|
|
32
|
+
super().__init__(f"{code}: {remote_message}")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AmbiguousSubmissionError(LorkError):
|
|
36
|
+
"""Raised when a non-idempotent POST fails after bytes may have reached the server."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, message: str, cause: BaseException) -> None:
|
|
39
|
+
self.cause = cause
|
|
40
|
+
super().__init__(message)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class LorkTimeoutError(LorkError):
|
|
44
|
+
"""Raised when waiting for an APIFuture exceeds the caller's timeout."""
|
lork/client/futures.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Long-polling future wrapper for async server operations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Generic, TypeVar
|
|
8
|
+
|
|
9
|
+
from lork.client.exceptions import LorkTimeoutError, RemoteOpError
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from lork.client.client import ServiceClient
|
|
13
|
+
from lork.wire import FutureStatusResponse
|
|
14
|
+
|
|
15
|
+
T = TypeVar("T")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class APIFuture(Generic[T]):
|
|
19
|
+
"""Handle to an in-flight asynchronous server operation."""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
client: ServiceClient,
|
|
24
|
+
future_id: str,
|
|
25
|
+
parser: Callable[[dict[str, Any]], T],
|
|
26
|
+
) -> None:
|
|
27
|
+
self._client = client
|
|
28
|
+
self.future_id = future_id
|
|
29
|
+
self._parser = parser
|
|
30
|
+
self._done = False
|
|
31
|
+
self._result: T | None = None
|
|
32
|
+
self._error: RemoteOpError | None = None
|
|
33
|
+
|
|
34
|
+
def _apply_status(self, status_resp: FutureStatusResponse) -> bool:
|
|
35
|
+
if status_resp.status == "done":
|
|
36
|
+
self._result = self._parser(status_resp.result or {})
|
|
37
|
+
self._done = True
|
|
38
|
+
return True
|
|
39
|
+
if status_resp.status == "error":
|
|
40
|
+
err = status_resp.error
|
|
41
|
+
code = err.code if err is not None else "remote_error"
|
|
42
|
+
msg = err.message if err is not None else "Remote operation failed"
|
|
43
|
+
self._error = RemoteOpError(code=code, remote_message=msg)
|
|
44
|
+
self._done = True
|
|
45
|
+
return True
|
|
46
|
+
return False
|
|
47
|
+
|
|
48
|
+
def done(self) -> bool:
|
|
49
|
+
"""Return True if the remote operation has completed (success or error)."""
|
|
50
|
+
if self._done:
|
|
51
|
+
return True
|
|
52
|
+
status_resp = self._client._get_future(self.future_id, wait=0.0)
|
|
53
|
+
return self._apply_status(status_resp)
|
|
54
|
+
|
|
55
|
+
def result(
|
|
56
|
+
self,
|
|
57
|
+
timeout: float | None = None,
|
|
58
|
+
poll_wait: float = 25.0,
|
|
59
|
+
) -> T:
|
|
60
|
+
"""Long-poll until the operation finishes, or raise LorkTimeoutError."""
|
|
61
|
+
if self._done:
|
|
62
|
+
if self._error is not None:
|
|
63
|
+
raise self._error
|
|
64
|
+
assert self._result is not None
|
|
65
|
+
return self._result
|
|
66
|
+
|
|
67
|
+
deadline = None if timeout is None else (time.monotonic() + timeout)
|
|
68
|
+
while True:
|
|
69
|
+
if deadline is not None:
|
|
70
|
+
remaining = deadline - time.monotonic()
|
|
71
|
+
if remaining <= 0.0:
|
|
72
|
+
raise LorkTimeoutError(
|
|
73
|
+
f"Timed out waiting for future {self.future_id}"
|
|
74
|
+
)
|
|
75
|
+
wait_seconds = max(0.0, min(poll_wait, 30.0, remaining))
|
|
76
|
+
else:
|
|
77
|
+
wait_seconds = max(0.0, min(poll_wait, 30.0))
|
|
78
|
+
|
|
79
|
+
status_resp = self._client._get_future(self.future_id, wait=wait_seconds)
|
|
80
|
+
if self._apply_status(status_resp):
|
|
81
|
+
if self._error is not None:
|
|
82
|
+
raise self._error
|
|
83
|
+
assert self._result is not None
|
|
84
|
+
return self._result
|
lork/client/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
lork/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|