wherobots-python-sdk 0.8.0__py3-none-any.whl → 0.9.1__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.
wherobots/__init__.py CHANGED
@@ -26,6 +26,8 @@ from wherobots.exceptions import (
26
26
  WherobotsJobError,
27
27
  WherobotsNotAuthenticatedError,
28
28
  WherobotsS3Error,
29
+ WherobotsTaskRunError,
30
+ WherobotsTaskRunTimeoutError,
29
31
  WherobotsTimeoutError,
30
32
  WherobotsValidationError,
31
33
  )
@@ -94,6 +96,8 @@ __all__ = [
94
96
  "WherobotsValidationError",
95
97
  "WherobotsS3Error",
96
98
  "WherobotsConfigError",
99
+ "WherobotsTaskRunError",
100
+ "WherobotsTaskRunTimeoutError",
97
101
  "WherobotsTimeoutError",
98
102
  "WherobotsNotAuthenticatedError",
99
103
  "WherobotsFilesNotEnabledError",
wherobots/__version__.py CHANGED
@@ -1,5 +1,5 @@
1
1
  """Version information."""
2
2
 
3
- __version__ = "0.8.0"
3
+ __version__ = "0.9.1"
4
4
  __author__ = "Wherobots"
5
5
  __email__ = "support@wherobots.com"
wherobots/api/base.py CHANGED
@@ -5,8 +5,8 @@
5
5
  workload-identity token mounted in Wherobots notebook and job pods.
6
6
  * Client attribution via the advisory ``X-Wherobots-Client`` header,
7
7
  set once on the session so every outgoing request carries it.
8
- * Automatic retry with exponential back-off for transient errors
9
- (429 Too Many Requests, 503 Service Unavailable, connection errors).
8
+ * Automatic retry of GET requests with exponential back-off for transient
9
+ errors (429 Too Many Requests, 5xx server errors, connection errors).
10
10
  * Unified error handling that maps HTTP failures into
11
11
  ``WherobotsAPIError``.
12
12
  """
@@ -32,13 +32,15 @@ from wherobots.utils.logger import get_logger
32
32
  if TYPE_CHECKING:
33
33
  from collections.abc import Mapping
34
34
 
35
+ from wherobots.models import ErrorInfo
36
+
35
37
  logger = get_logger("api")
36
38
 
37
- # Default retry policy: 3 retries with back-off on 429 / 502 / 503 and
38
- # connection-level failures.
39
+ # Default retry policy for GET: 3 retries with back-off on 429 / 500 / 502 /
40
+ # 503 / 504 and connection-level failures. POST is never retried.
39
41
  _DEFAULT_RETRIES = 3
40
42
  _DEFAULT_BACKOFF_FACTOR = 0.5
41
- _RETRIABLE_STATUS_CODES = (429, 502, 503)
43
+ _RETRIABLE_STATUS_CODES = (429, 500, 502, 503, 504)
42
44
 
43
45
 
44
46
  def json_object(response: requests.Response) -> dict[str, object]:
@@ -86,7 +88,25 @@ def _error_details(body: object) -> tuple[str | None, str | None]:
86
88
  except WherobotsAPIError:
87
89
  # Failures outside the API's error handler, such as the gateway's, have their own shape.
88
90
  return str(body.get("detail", body)), None
89
- return "; ".join(error.message for error in parsed.errors), parsed.request_id
91
+ return "\n".join(_describe(error) for error in parsed.errors), parsed.request_id
92
+
93
+
94
+ def _describe(error: ErrorInfo) -> str:
95
+ """Write one API error as its message, then each other field it sets on its own line.
96
+
97
+ The message is often only the HTTP reason phrase, such as "Bad Request", so the other
98
+ fields carry what went wrong and what to do about it.
99
+ """
100
+ fields = (
101
+ ("details", error.details),
102
+ ("field", error.field),
103
+ ("code", error.code),
104
+ ("path", error.path),
105
+ ("suggestion", error.suggestion),
106
+ ("documentation_url", error.documentation_url),
107
+ ("data", error.data),
108
+ )
109
+ return "\n".join([error.message, *(f" {name}: {value}" for name, value in fields if value)])
90
110
 
91
111
 
92
112
  class BaseClient:
wherobots/api/tasks.py CHANGED
@@ -7,11 +7,21 @@ organization can run. Each run is a task run, addressable by its own id, so
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ import time
10
11
  from datetime import UTC
12
+ from http import HTTPStatus
11
13
  from typing import TYPE_CHECKING
12
14
 
15
+ import requests
16
+
13
17
  from wherobots.api import _operations as operations
14
- from wherobots.enums import Region, TaskRunState
18
+ from wherobots.enums import Region, TaskKind, TaskRunState
19
+ from wherobots.exceptions import (
20
+ WherobotsAPIError,
21
+ WherobotsTaskRunError,
22
+ WherobotsTaskRunTimeoutError,
23
+ WherobotsValidationError,
24
+ )
15
25
  from wherobots.models import (
16
26
  CreateTaskRunPayload,
17
27
  OffsetPage,
@@ -32,6 +42,20 @@ if TYPE_CHECKING:
32
42
 
33
43
  logger = get_logger("api.tasks")
34
44
 
45
+ # Waiting for task runs (ADR-0005). Each wait between polls is this much longer than the
46
+ # last, up to _MAX_POLL_INTERVAL.
47
+ _BACKOFF = 1.5
48
+ _MAX_POLL_INTERVAL = 30.0
49
+ # A platform task's results can be briefly unavailable after it succeeds (see the
50
+ # ``TaskRun.results`` docs); fetch it this many more times before giving up.
51
+ _RESULTS_REFETCHES = 3
52
+ # UNKNOWN is usually passing, but a script run can end in it; after this long in a row it
53
+ # counts as final.
54
+ _UNKNOWN_GRACE_SECONDS = 600.0
55
+ # A status check that fails with a transient error (see _is_transient) is skipped, and the
56
+ # wait carries on; this many failures in a row end it.
57
+ _MAX_FAILED_CHECKS = 5
58
+
35
59
 
36
60
  def _region_name(region: Region | str) -> str:
37
61
  return region.value if isinstance(region, Region) else region
@@ -136,6 +160,35 @@ class Tasks:
136
160
  )
137
161
  return operations.create_task_run(self._client, task_name, payload)
138
162
 
163
+ def run_and_wait(
164
+ self,
165
+ task_name: str,
166
+ inputs: Mapping[str, object] | None = None,
167
+ *,
168
+ region: Region | str | None = None,
169
+ name: str | None = None,
170
+ max_wait_seconds: float | None = None,
171
+ ) -> TaskRun:
172
+ """Start a run of a task and wait for it to finish.
173
+
174
+ ``run`` followed by ``TaskRuns.wait_for_completion``; see those for the
175
+ arguments. Read a single-output task's result with ``TaskRun.output``. For other
176
+ wait options, call the two separately.
177
+
178
+ Returns:
179
+ The finished run.
180
+
181
+ Raises:
182
+ WherobotsAPIError: On HTTP or JSON-parsing failures.
183
+ WherobotsTaskRunError: The run did not succeed. ``.run`` holds the finished run.
184
+ WherobotsTaskRunTimeoutError: ``max_wait_seconds`` passed. The run keeps
185
+ going; ``.run`` holds it as last fetched.
186
+ """
187
+ summary = self.run(task_name, inputs, region=region, name=name)
188
+ return TaskRuns(self._client).wait_for_completion(
189
+ summary.task_run_id, max_wait_seconds=max_wait_seconds
190
+ )
191
+
139
192
 
140
193
  class TaskRuns:
141
194
  """Runs of the organization's tasks.
@@ -198,6 +251,133 @@ class TaskRuns:
198
251
  """
199
252
  return operations.get_task_run(self._client, task_run_id)
200
253
 
254
+ def wait_for_completion(
255
+ self,
256
+ task_run_id: str,
257
+ *,
258
+ poll_interval: float = 5.0,
259
+ max_wait_seconds: float | None = None,
260
+ raise_on_failure: bool = True,
261
+ ) -> TaskRun:
262
+ """Poll a run until it finishes and return it.
263
+
264
+ Works for any task. Polls start ``poll_interval`` apart and back off to 30
265
+ seconds apart (or ``poll_interval``, if longer); state changes are logged at
266
+ INFO. Neither a timeout nor an interrupt cancels the run: it keeps going on the
267
+ server, and calling this again resumes the wait. Use ``cancel`` to stop it.
268
+
269
+ ``UNKNOWN`` is not treated as finished until the run has reported it for 10
270
+ minutes in a row, because the server also uses it while a run starts. A state
271
+ this SDK predates is never treated as finished; the wait logs a warning once and
272
+ keeps polling, so set ``max_wait_seconds`` to bound it.
273
+
274
+ When a run succeeds with its results briefly unavailable, it is fetched up to
275
+ three more times, within ``max_wait_seconds``, before it is returned without
276
+ them. Script tasks never return results and are not refetched.
277
+
278
+ A status check that fails with a rate limit (429), a server error (5xx) or a
279
+ connection error is logged at WARNING and skipped, and the wait carries on;
280
+ only a check that succeeds can end it. Five such failures in a row raise the
281
+ last one. Other errors, such as a 404 or a response the SDK can't decode, raise
282
+ at once.
283
+
284
+ Args:
285
+ task_run_id: The run's id.
286
+ poll_interval: Seconds before the first re-check, greater than zero.
287
+ max_wait_seconds: Stop waiting after this many seconds; ``None`` waits as
288
+ long as the run takes. The last check can return just after the
289
+ deadline; if it finds the run finished, the run is returned rather than
290
+ a timeout, so a finished result is never thrown away.
291
+ raise_on_failure: Raise if the run ends in any state but ``SUCCEEDED``;
292
+ ``False`` returns the run instead.
293
+
294
+ Returns:
295
+ The finished run.
296
+
297
+ Raises:
298
+ WherobotsAPIError: On HTTP or JSON-parsing failures.
299
+ WherobotsTaskRunError: The run did not succeed and ``raise_on_failure`` is
300
+ set. ``.run`` holds the finished run.
301
+ WherobotsTaskRunTimeoutError: ``max_wait_seconds`` passed. The run keeps
302
+ going; ``.run`` holds it as last fetched. A ``WherobotsTimeoutError``.
303
+ WherobotsValidationError: ``poll_interval`` is not greater than zero.
304
+ """
305
+ if poll_interval <= 0:
306
+ msg = f"poll_interval must be greater than zero, not {poll_interval}"
307
+ raise WherobotsValidationError(msg)
308
+ wait = _Wait(poll_interval, max_wait_seconds)
309
+ label = "Task" # the task's name, once the first check returns it
310
+ try:
311
+ run = self.get(task_run_id)
312
+ label = run.task_name
313
+ logger.info("%s run %s: %s", run.task_name, task_run_id, run.state)
314
+ # Only a check that succeeded can end the wait, so a run kept from before a
315
+ # failed check, such as one in UNKNOWN, is never taken as final.
316
+ failed_checks = 0
317
+ while failed_checks or not wait.is_over(run):
318
+ wait.sleep(run)
319
+ previous = run.state
320
+ run, failed_checks = self._check(task_run_id, run, failed_checks)
321
+ if run.state != previous:
322
+ logger.info("%s run %s: %s", run.task_name, task_run_id, run.state)
323
+ run = self._refetch_missing_results(run, wait)
324
+ except KeyboardInterrupt as interrupt:
325
+ interrupt.add_note(
326
+ f"{label} run {task_run_id} keeps running. Resume with "
327
+ f"wb.task_runs.wait_for_completion({task_run_id!r}) or stop it with "
328
+ f"wb.task_runs.cancel({task_run_id!r})."
329
+ )
330
+ raise
331
+ if raise_on_failure and run.state != TaskRunState.SUCCEEDED:
332
+ msg = f"{run.task_name} run {task_run_id} ended {run.state}"
333
+ if run.error_message:
334
+ msg += f": {run.error_message}"
335
+ raise WherobotsTaskRunError(msg, run)
336
+ return run
337
+
338
+ def _check(self, task_run_id: str, last: TaskRun, failed_checks: int) -> tuple[TaskRun, int]:
339
+ """Fetch the run again, keeping *last* if the check fails with a transient error.
340
+
341
+ Returns:
342
+ The run, and how many checks in a row have now failed.
343
+
344
+ Raises:
345
+ WherobotsAPIError: The check failed with a non-transient error, or this is
346
+ the ``_MAX_FAILED_CHECKS``-th transient failure in a row.
347
+ """
348
+ try:
349
+ return self.get(task_run_id), 0
350
+ except WherobotsAPIError as error:
351
+ if not _is_transient(error) or failed_checks + 1 >= _MAX_FAILED_CHECKS:
352
+ raise
353
+ logger.warning(
354
+ "%s run %s: status check failed (%s); checking again",
355
+ last.task_name,
356
+ task_run_id,
357
+ error,
358
+ )
359
+ return last, failed_checks + 1
360
+
361
+ def _refetch_missing_results(self, run: TaskRun, wait: _Wait) -> TaskRun:
362
+ """Fetch a succeeded run again while its results are unavailable, within the deadline.
363
+
364
+ Script tasks never return results, so only other runs are fetched again. A run
365
+ whose ``type`` is missing counts as one that can.
366
+ """
367
+ for _ in range(_RESULTS_REFETCHES):
368
+ if not (
369
+ run.state == TaskRunState.SUCCEEDED
370
+ and run.type != TaskKind.SCRIPTTASK
371
+ and not run.results
372
+ ):
373
+ break
374
+ remaining = wait.remaining()
375
+ if remaining == 0:
376
+ break
377
+ wait.nap(remaining)
378
+ run = self.get(run.task_run_id)
379
+ return run
380
+
201
381
  def logs(self, task_run_id: str, since: str | None = None) -> TaskRunLogs:
202
382
  """Fetch a page of a run's logs (``GET /task-runs/{id}/logs``).
203
383
 
@@ -242,3 +422,82 @@ class TaskRuns:
242
422
  """
243
423
  operations.cancel_task_run(self._client, task_run_id)
244
424
  logger.info("Cancel requested for task run %s", task_run_id)
425
+
426
+
427
+ def _is_transient(error: WherobotsAPIError) -> bool:
428
+ """Whether a failed check is worth retrying: a rate limit, server error or lost connection.
429
+
430
+ A response the SDK can't decode also has no status code, but it's a contract error
431
+ that retrying won't fix, so it isn't transient.
432
+ """
433
+ if error.status_code is not None:
434
+ return (
435
+ error.status_code == HTTPStatus.TOO_MANY_REQUESTS
436
+ or error.status_code >= HTTPStatus.INTERNAL_SERVER_ERROR
437
+ )
438
+ return isinstance(error.__cause__, (requests.ConnectionError, requests.Timeout))
439
+
440
+
441
+ class _Wait:
442
+ """The clock and stopping rules for one ``TaskRuns.wait_for_completion`` call."""
443
+
444
+ def __init__(self, poll_interval: float, max_wait_seconds: float | None) -> None:
445
+ """Start the clock; see ``TaskRuns.wait_for_completion`` for the arguments."""
446
+ self._max_wait_seconds = max_wait_seconds
447
+ self._deadline = None if max_wait_seconds is None else time.monotonic() + max_wait_seconds
448
+ self._interval = poll_interval
449
+ self._max_interval = max(poll_interval, _MAX_POLL_INTERVAL)
450
+ self._unknown_since: float | None = None
451
+ self._warned: set[str] = set()
452
+
453
+ def remaining(self) -> float | None:
454
+ """Seconds left before the deadline, never below zero; ``None`` without one."""
455
+ return None if self._deadline is None else max(0.0, self._deadline - time.monotonic())
456
+
457
+ def is_over(self, run: TaskRun) -> bool:
458
+ """Whether *run* has finished, counting a long enough run of ``UNKNOWN``."""
459
+ state = run.state
460
+ if state.is_finished:
461
+ return True
462
+ if state != TaskRunState.UNKNOWN:
463
+ self._unknown_since = None
464
+ if not state.is_active and state.name not in TaskRunState.__members__:
465
+ self._warn_once(run)
466
+ return False
467
+ now = time.monotonic()
468
+ if self._unknown_since is None:
469
+ self._unknown_since = now
470
+ return now - self._unknown_since >= _UNKNOWN_GRACE_SECONDS
471
+
472
+ def sleep(self, run: TaskRun) -> None:
473
+ """Sleep until the next poll, backing off, or raise if the deadline has passed.
474
+
475
+ Raises:
476
+ WherobotsTaskRunTimeoutError: ``max_wait_seconds`` passed.
477
+ """
478
+ remaining = self.remaining()
479
+ if remaining == 0:
480
+ msg = (
481
+ f"Timed out after {self._max_wait_seconds:g} s waiting for {run.task_name} run "
482
+ f"{run.task_run_id}, which is {run.state}. It keeps running; wait again or "
483
+ "cancel it"
484
+ )
485
+ raise WherobotsTaskRunTimeoutError(msg, run)
486
+ self.nap(remaining)
487
+ self._interval = min(self._interval * _BACKOFF, self._max_interval)
488
+
489
+ def nap(self, remaining: float | None) -> None:
490
+ """Sleep the current interval, cut short at the deadline, without backing off."""
491
+ time.sleep(self._interval if remaining is None else min(self._interval, remaining))
492
+
493
+ def _warn_once(self, run: TaskRun) -> None:
494
+ state = str(run.state)
495
+ if state not in self._warned:
496
+ self._warned.add(state)
497
+ logger.warning(
498
+ "%s run %s is in state %s, which this SDK does not know; still waiting. "
499
+ "Upgrade wherobots if this never ends.",
500
+ run.task_name,
501
+ run.task_run_id,
502
+ state,
503
+ )
@@ -8,8 +8,11 @@ _TERMINAL_JOB_STATUSES = frozenset({"COMPLETED", "FAILED", "CANCELLED", "TIMED_O
8
8
  # Mirrors the server's TaskRunState.active_states.
9
9
  _ACTIVE_TASK_RUN_STATES = frozenset({"PENDING", "SUBMITTED", "RUNNING", "CANCELLING"})
10
10
  _FINISHED_TASK_RUN_STATES = frozenset(
11
- {"SUCCEEDED", "FAILED", "TIMED_OUT", "CANCELLED", "UNKNOWN", "SKIPPED", "MISSED", "REJECTED"}
11
+ {"SUCCEEDED", "FAILED", "TIMED_OUT", "CANCELLED", "SKIPPED", "MISSED", "REJECTED"}
12
12
  )
13
+ # Neither: the server reports UNKNOWN for a phase it cannot map yet, including while a run
14
+ # starts, and keeps checking it, but a script run can also end in UNKNOWN (ADR-0005).
15
+ _UNSETTLED_TASK_RUN_STATES = frozenset({"UNKNOWN"})
13
16
 
14
17
 
15
18
  class JobStatusBehavior:
@@ -29,6 +32,15 @@ class TaskRunStateBehavior:
29
32
  """Return ``True`` while the run may still change state."""
30
33
  return str(self) in _ACTIVE_TASK_RUN_STATES
31
34
 
35
+ @property
36
+ def is_finished(self) -> bool:
37
+ """Return ``True`` once the run has reached a state it will not leave.
38
+
39
+ ``UNKNOWN`` and a state this SDK predates are neither active nor finished, so
40
+ waiting on them keeps polling rather than stopping early.
41
+ """
42
+ return str(self) in _FINISHED_TASK_RUN_STATES
43
+
32
44
 
33
45
  def is_terminal_status(status: str | None) -> bool:
34
46
  """Return True if *status* is a known terminal state.
wherobots/exceptions.py CHANGED
@@ -2,7 +2,10 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import Any # noqa: TID251
5
+ from typing import TYPE_CHECKING, Any # noqa: TID251
6
+
7
+ if TYPE_CHECKING:
8
+ from wherobots.models import TaskRun
6
9
 
7
10
 
8
11
  class WherobotsJobError(Exception):
@@ -47,6 +50,42 @@ class WherobotsTimeoutError(WherobotsJobError):
47
50
  """Raised when a job exceeds the specified timeout."""
48
51
 
49
52
 
53
+ class WherobotsTaskRunError(WherobotsJobError):
54
+ """Raised when a task run did not succeed, or has no single output to return.
55
+
56
+ Attributes:
57
+ run: The run as last fetched, when the error is about a finished run.
58
+ """
59
+
60
+ def __init__(self, message: str, run: TaskRun | None = None) -> None:
61
+ """Build the error.
62
+
63
+ Args:
64
+ message: What went wrong.
65
+ run: The run as last fetched, if there is one.
66
+ """
67
+ self.run = run
68
+ super().__init__(message)
69
+
70
+
71
+ class WherobotsTaskRunTimeoutError(WherobotsTimeoutError):
72
+ """Raised when waiting for a task run timed out. The run itself keeps going.
73
+
74
+ Attributes:
75
+ run: The run as last fetched; wait on or cancel ``run.task_run_id``.
76
+ """
77
+
78
+ def __init__(self, message: str, run: TaskRun) -> None:
79
+ """Build the error.
80
+
81
+ Args:
82
+ message: What timed out.
83
+ run: The run as last fetched.
84
+ """
85
+ self.run = run
86
+ super().__init__(message)
87
+
88
+
50
89
  class WherobotsNotAuthenticatedError(WherobotsAPIError):
51
90
  """Raised when the Wherobots API does not accept the credentials."""
52
91
 
@@ -31,6 +31,7 @@ from wherobots.models._handwritten import (
31
31
  RunViewBehavior,
32
32
  StorageIntegrationBehavior,
33
33
  TaskRunBehavior,
34
+ TaskRunDetailBehavior,
34
35
  )
35
36
 
36
37
 
@@ -574,7 +575,7 @@ class TaskExample(WireModel):
574
575
 
575
576
 
576
577
  @dc.dataclass(frozen=True, kw_only=True)
577
- class TaskRun(TaskRunBehavior, WireModel):
578
+ class TaskRun(TaskRunDetailBehavior, WireModel):
578
579
  """A task run, as returned by ``GET /task-runs/{taskRunId}``.
579
580
 
580
581
  Attributes:
@@ -613,7 +614,7 @@ class TaskRun(TaskRunBehavior, WireModel):
613
614
 
614
615
  batch_kind: BatchKind | None = dc.field(default=None, metadata={"wire": "batchKind"})
615
616
  batch_time: datetime | None = dc.field(default=None, metadata={"wire": "batchTime"})
616
- cached: bool = dc.field(default=False, metadata={"wire": "cached"})
617
+ cached: bool | None = dc.field(default=False, metadata={"wire": "cached"})
617
618
  cancel_requested_at: datetime | None = dc.field(
618
619
  default=None, metadata={"wire": "cancelRequestedAt"}
619
620
  )
@@ -11,7 +11,7 @@ from datetime import UTC, datetime, timedelta
11
11
  from typing import TYPE_CHECKING, Generic, NoReturn, TypeVar
12
12
 
13
13
  from wherobots.enums import FileEntryType, JobStatus, StorageSourceType, TaskRunState
14
- from wherobots.exceptions import WherobotsAPIError
14
+ from wherobots.exceptions import WherobotsAPIError, WherobotsTaskRunError
15
15
 
16
16
  if TYPE_CHECKING:
17
17
  from wherobots.models._generated import (
@@ -202,6 +202,45 @@ class TaskRunBehavior:
202
202
  return self.state.is_active
203
203
 
204
204
 
205
+ @dataclass(frozen=True, kw_only=True)
206
+ class TaskRunDetailBehavior(TaskRunBehavior):
207
+ """``TaskRun`` helpers that need the run's results."""
208
+
209
+ if TYPE_CHECKING:
210
+ results: dict[str, object] | None
211
+ task_name: str
212
+ task_run_id: str
213
+
214
+ @property
215
+ def output(self) -> object:
216
+ """The run's one result, for tasks with a single output.
217
+
218
+ Returns:
219
+ The value of the run's only entry in ``results``, whatever its type.
220
+
221
+ Raises:
222
+ WherobotsTaskRunError: The run has not succeeded, has no results, or has
223
+ several outputs (read ``results`` for those).
224
+ """
225
+ label = f"{self.task_name} run {self.task_run_id}"
226
+ if self.state != TaskRunState.SUCCEEDED:
227
+ msg = f"{label} has no output: it is {self.state}"
228
+ raise WherobotsTaskRunError(msg)
229
+ if not self.results:
230
+ msg = (
231
+ f"{label} succeeded but has no results. Script tasks never return results; "
232
+ "a platform task's results can be briefly unavailable, so fetch the run "
233
+ "again with wb.task_runs.get() rather than running the task again"
234
+ )
235
+ raise WherobotsTaskRunError(msg)
236
+ if len(self.results) > 1:
237
+ names = ", ".join(sorted(self.results))
238
+ msg = f"{label} has {len(self.results)} outputs ({names}); read them from results"
239
+ raise WherobotsTaskRunError(msg)
240
+ (value,) = self.results.values()
241
+ return value
242
+
243
+
205
244
  @dataclass
206
245
  class UtilizationStats:
207
246
  """Aggregated utilization for a single metric (e.g. CPU or memory).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: wherobots-python-sdk
3
- Version: 0.8.0
3
+ Version: 0.9.1
4
4
  Summary: Python SDK for Wherobots (currently covers the Jobs REST API)
5
5
  Author-email: Wherobots <support@wherobots.com>
6
6
  License-Expression: Apache-2.0
@@ -477,8 +477,6 @@ A task is a named unit of work, such as RasterFlow inference, that your organiza
477
477
  your organization.
478
478
 
479
479
  ```python
480
- import time
481
-
482
480
  import wherobots
483
481
 
484
482
  with wherobots.Wherobots() as wb:
@@ -488,23 +486,35 @@ with wherobots.Wherobots() as wb:
488
486
  task = wb.tasks.get("my-task")
489
487
  print(task.input_schema) # JSON Schema the inputs must satisfy
490
488
 
491
- started = wb.tasks.run("my-task", {"aoi": "s3://bucket/aoi.geojson"}, name="nightly")
492
- run = wb.task_runs.get(started.task_run_id)
493
- while run.is_active:
494
- time.sleep(10)
495
- run = wb.task_runs.get(run.task_run_id)
489
+ # Start a run and wait for it; raises WherobotsTaskRunError if it does not succeed
490
+ run = wb.tasks.run_and_wait("my-task", {"aoi": "s3://bucket/aoi.geojson"}, name="nightly")
491
+ print(run.output) # the one result of a single-output task; run.results has them all
496
492
 
497
- print(run.state, run.results, run.error_message)
498
493
  print(wb.task_runs.logs(run.task_run_id).entries)
499
494
  print(wb.task_runs.cost(run.task_run_id).total_cost_usd)
495
+
496
+ # Or start a run now and wait for it later
497
+ started = wb.tasks.run("my-task", {"aoi": "s3://bucket/aoi.geojson"})
498
+ run = wb.task_runs.wait_for_completion(started.task_run_id, max_wait_seconds=3600)
500
499
  ```
501
500
 
502
501
  - `tasks.run` uses `region=` if passed, then the configured region, then your organization's
503
502
  default region.
504
503
  - Listings return an `OffsetPage`; pass `page.next_offset` as `offset=` for the next one.
505
- - `TaskRunState.is_active` is `True` for `PENDING`, `SUBMITTED`, `RUNNING` and `CANCELLING`. A
506
- state the SDK does not know yet is kept as its raw string and counts as not active, so a
507
- polling loop stops on it.
504
+ - `TaskRunState.is_active` is `True` for `PENDING`, `SUBMITTED`, `RUNNING` and `CANCELLING`, and
505
+ `is_finished` is `True` for every other state the SDK knows except `UNKNOWN`, which the server
506
+ also reports while a run starts. `wait_for_completion` polls through `UNKNOWN`, and treats it as
507
+ final after 10 minutes in a row. A state the SDK does not know yet is kept as its raw string and
508
+ is neither; `wait_for_completion` logs a warning once and keeps polling through it.
509
+ - `task_runs.wait_for_completion` polls 5 seconds apart at first, backing off to 30 seconds, and
510
+ logs each state change at INFO on the `wherobots` logger. A timeout (`max_wait_seconds`) raises
511
+ `WherobotsTaskRunTimeoutError` (a `WherobotsTimeoutError`) with the run in `.run`, and never
512
+ cancels it: call `wait_for_completion(err.run.task_run_id)` to resume, or `task_runs.cancel` to
513
+ stop it. Interrupting the wait leaves the run going too; the traceback names it. Pass `raise_on_failure=False` to get an unsuccessful run back
514
+ instead of an error.
515
+ - When a platform task succeeds before its results are readable, `wait_for_completion` fetches it
516
+ up to three more times, at the current poll interval. If `results` is still empty, `run.output` raises; fetch the run again
517
+ with `task_runs.get` rather than running the task again. Script tasks never return results.
508
518
  - A run's state can lag the run by up to 2 minutes.
509
519
  - `task_runs.logs` pages forward: pass the previous page's `next_since` as `since=`. It is `None`
510
520
  once the run has finished and every line has been returned.
@@ -1,31 +1,31 @@
1
- wherobots/__init__.py,sha256=MUFjzOBaVW2lzPw35F5SBlTChJBKl1n0-p16qUnIO9k,2759
2
- wherobots/__version__.py,sha256=IUwJHipKJOM1z0PQ22p_91Hx9HgjyI0FEj5SthJ5cGc,111
1
+ wherobots/__init__.py,sha256=s28_iftMhXVZiITWxeOfOVrlKSzKhrPz_ncqNch0H9M,2885
2
+ wherobots/__version__.py,sha256=j5YSDE59WY1m059xlCxEwebCt1XSrdGgzEmDZTt6JMo,111
3
3
  wherobots/_wire.py,sha256=MMDdcvNcD6lrxjwBhv7jVg8aIC6HpU7iP7Ldgv5Jf0M,7690
4
4
  wherobots/client.py,sha256=O7vZvKwdIlMZJtgh9g6pMAUX2oxRre1U1CptjAWcugw,37248
5
5
  wherobots/config.py,sha256=VQtCO5qtsUteKn0jhx37WHwXTDc5BByoAdEYKOyUHl8,8195
6
- wherobots/exceptions.py,sha256=lBzjRNtWRGyh0PgnIKAQr4x2liEhFvWoLn-Ndf91nCQ,2558
6
+ wherobots/exceptions.py,sha256=lzNRwtwpfyE052V-Lz2dsxOqQbYRmk2cyMpMBtE_Uhg,3648
7
7
  wherobots/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
8
  wherobots/sdk.py,sha256=AcLC_ZFqTl24Vthcu_EfK7FFUJEyftGJJkusEp-zayI,3481
9
9
  wherobots/api/__init__.py,sha256=VT1nx6K777qV-PX-7hrBfCWPL1h6WYc4ljj_-qqhdko,360
10
10
  wherobots/api/_operations.py,sha256=RMIO053q-ni1uAY3kKYHna7_PRyARtZAyaLnmhrkDvM,9990
11
- wherobots/api/base.py,sha256=nMyzOKXRCorUTpBUesmMdoPcj8kllPhE5IBxU7N1Dh4,11574
11
+ wherobots/api/base.py,sha256=dwSFT6BDycnEIr8r_-1YY3GLCU1V7kKbtDi8QmXPWeY,12348
12
12
  wherobots/api/drive.py,sha256=5-UAUczYNxN-MYnx1FESFG1XkjRt0AS0cEhs0vkI2W4,18508
13
13
  wherobots/api/files.py,sha256=EL2avIUCo17FzxyP3pfOhNWYyqbQeTFVj5Tj7alteos,22625
14
14
  wherobots/api/runs.py,sha256=wLqaQxkggLtUrpS-CCbwxTi-s7PiYEYXQfQsBETYb4Q,7328
15
- wherobots/api/tasks.py,sha256=8sJKs7twO-c8AhHNPrPs6YJQ-TACgVR4YiHGA7bcMrU,7991
15
+ wherobots/api/tasks.py,sha256=cxHeDUUFADmXcjOJbbUYDLwhiAFqm23vMSoOSEhDpd0,19423
16
16
  wherobots/api/workload_auth.py,sha256=zhJXROeYV47HJvEqzGAbd4oaqkuqXQGHZQRCHeDIYuE,4725
17
17
  wherobots/enums/__init__.py,sha256=s0Mpu2wT33F14IhnbgrAuPxPdEy0l0Rq2dN0YLvWpuI,905
18
18
  wherobots/enums/_generated.py,sha256=a4goEdSzxcGqD8Czj8XMxSOVqFj8j7n4WMK7Z8cyeI0,3587
19
- wherobots/enums/_handwritten.py,sha256=HO2nwzEsiYfomBK19PXE2xWlnazu14MrjXmfyR8mAdo,3631
19
+ wherobots/enums/_handwritten.py,sha256=4kgYytpYwZtI15Xz7IAsnIJDf0eHDvtGfxHfpzh7gKI,4197
20
20
  wherobots/models/__init__.py,sha256=d36zMWKtiLT4DqrpBde7ZC4Um1Thyqiy10oKTQ-4oY0,2345
21
- wherobots/models/_generated.py,sha256=z-OCRYS6ha1YSKzHRqvyTTZdLin2aGaCQR_t6EQGt38,34448
22
- wherobots/models/_handwritten.py,sha256=C9doF2H4M4xaTHxnjVg6t4hQ-7xD2A-iDIYqPMLE3k0,11913
21
+ wherobots/models/_generated.py,sha256=KMvq2l915mGuqr_fYVMJOY7_c_9gQVv4BXLFMh0fJl4,34488
22
+ wherobots/models/_handwritten.py,sha256=quDpfNK9c-opkO-uPrdNIvxIVeeVXbFhwtG69XprsUg,13459
23
23
  wherobots/utils/__init__.py,sha256=cTM2QNJDauQWyGBTJPE5yH4ULc4Ucg_4KFzemjM3HaA,193
24
24
  wherobots/utils/client_header.py,sha256=-zczKIl8QfFBs1uTLbzp6cGLEzit1qGgdWbV9MLYEcM,8083
25
25
  wherobots/utils/logger.py,sha256=eclhD9Vf2LsSm4engRzT3jE2v0wdHJH01OfeI3ml4HM,1103
26
26
  wherobots/utils/validation.py,sha256=mjWGGhNji1crdn1AhLZoTIfknSQm38X0MmgI4ow14T8,907
27
- wherobots_python_sdk-0.8.0.dist-info/licenses/LICENSE,sha256=U1EH466XmvxbqaWOY0cax49w0R87_6w6yJLyV14v4bc,10767
28
- wherobots_python_sdk-0.8.0.dist-info/METADATA,sha256=V2xf-dFbtkQkOOg1-CypaR78kuBhFEx89tlSad1ml4I,34199
29
- wherobots_python_sdk-0.8.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
30
- wherobots_python_sdk-0.8.0.dist-info/top_level.txt,sha256=oL-n-9GIG0rmUeukuytUqdN6yfROIsVh8bNrgZsOdxw,10
31
- wherobots_python_sdk-0.8.0.dist-info/RECORD,,
27
+ wherobots_python_sdk-0.9.1.dist-info/licenses/LICENSE,sha256=U1EH466XmvxbqaWOY0cax49w0R87_6w6yJLyV14v4bc,10767
28
+ wherobots_python_sdk-0.9.1.dist-info/METADATA,sha256=osMN-3QFOyj3OfX39sZ97Yq8oX7s5TySHbpbBB5zbfg,35518
29
+ wherobots_python_sdk-0.9.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
30
+ wherobots_python_sdk-0.9.1.dist-info/top_level.txt,sha256=oL-n-9GIG0rmUeukuytUqdN6yfROIsVh8bNrgZsOdxw,10
31
+ wherobots_python_sdk-0.9.1.dist-info/RECORD,,