dwave-cloud-client 0.13.2__tar.gz → 0.13.3__tar.gz

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 (75) hide show
  1. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/PKG-INFO +11 -2
  2. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/api/client.py +124 -9
  3. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/api/resources.py +32 -5
  4. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/client/base.py +61 -35
  5. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/config/models.py +3 -1
  6. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/exceptions.py +4 -0
  7. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/package_info.py +1 -1
  8. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/solver.py +20 -3
  9. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave_cloud_client.egg-info/PKG-INFO +11 -2
  10. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_client.py +27 -3
  11. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_mock_solver_loading.py +10 -0
  12. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_mock_submission.py +125 -1
  13. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/LICENSE +0 -0
  14. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/README.rst +0 -0
  15. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/__init__.py +0 -0
  16. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/__init__.py +0 -0
  17. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/api/__init__.py +0 -0
  18. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/api/constants.py +0 -0
  19. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/api/exceptions.py +0 -0
  20. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/api/models.py +0 -0
  21. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/auth/__init__.py +0 -0
  22. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/auth/_creds.py +0 -0
  23. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/auth/config.py +0 -0
  24. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/auth/creds.py +0 -0
  25. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/auth/flows.py +0 -0
  26. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/auth/server.py +0 -0
  27. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/cli.py +0 -0
  28. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/client/__init__.py +0 -0
  29. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/client/hybrid.py +0 -0
  30. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/client/qpu.py +0 -0
  31. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/client/sw.py +0 -0
  32. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/coders.py +0 -0
  33. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/computation.py +0 -0
  34. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/concurrency.py +0 -0
  35. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/config/__init__.py +0 -0
  36. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/config/constants.py +0 -0
  37. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/config/exceptions.py +0 -0
  38. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/config/loaders.py +0 -0
  39. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/events.py +0 -0
  40. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/regions.py +0 -0
  41. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/testing/__init__.py +0 -0
  42. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/testing/mocks.py +0 -0
  43. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/upload.py +0 -0
  44. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/utils/__init__.py +0 -0
  45. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/utils/cli.py +0 -0
  46. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/utils/coders.py +0 -0
  47. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/utils/decorators.py +0 -0
  48. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/utils/dist.py +0 -0
  49. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/utils/exception.py +0 -0
  50. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/utils/http.py +0 -0
  51. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/utils/logging.py +0 -0
  52. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/utils/qubo.py +0 -0
  53. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave/cloud/utils/time.py +0 -0
  54. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave_cloud_client.egg-info/SOURCES.txt +0 -0
  55. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave_cloud_client.egg-info/dependency_links.txt +0 -0
  56. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave_cloud_client.egg-info/entry_points.txt +0 -0
  57. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave_cloud_client.egg-info/not-zip-safe +0 -0
  58. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave_cloud_client.egg-info/requires.txt +0 -0
  59. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/dwave_cloud_client.egg-info/top_level.txt +0 -0
  60. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/pyproject.toml +0 -0
  61. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/setup.cfg +0 -0
  62. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/setup.py +0 -0
  63. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_cli.py +0 -0
  64. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_coders.py +0 -0
  65. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_concurrency.py +0 -0
  66. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_config.py +0 -0
  67. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_events.py +0 -0
  68. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_exceptions.py +0 -0
  69. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_mock_unstructured_submission.py +0 -0
  70. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_regions.py +0 -0
  71. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_solver.py +0 -0
  72. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_solver_utils.py +0 -0
  73. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_testing.py +0 -0
  74. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_upload.py +0 -0
  75. {dwave_cloud_client-0.13.2 → dwave_cloud_client-0.13.3}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: dwave-cloud-client
3
- Version: 0.13.2
3
+ Version: 0.13.3
4
4
  Summary: A minimal client for interacting with D-Wave cloud resources.
5
5
  Home-page: https://github.com/dwavesystems/dwave-cloud-client
6
6
  Author: D-Wave Systems Inc.
@@ -48,6 +48,15 @@ Requires-Dist: dwave-optimization<0.5,>=0.1.0; extra == "nlm"
48
48
  Requires-Dist: numpy>=1.20.0; extra == "nlm"
49
49
  Provides-Extra: mocks
50
50
  Requires-Dist: dwave-networkx>=0.8.10; extra == "mocks"
51
+ Dynamic: author
52
+ Dynamic: classifier
53
+ Dynamic: description
54
+ Dynamic: home-page
55
+ Dynamic: license
56
+ Dynamic: provides-extra
57
+ Dynamic: requires-dist
58
+ Dynamic: requires-python
59
+ Dynamic: summary
51
60
 
52
61
  .. image:: https://badge.fury.io/py/dwave-cloud-client.svg
53
62
  :target: https://badge.fury.io/py/dwave-cloud-client
@@ -20,8 +20,10 @@ import logging
20
20
  import numbers
21
21
  import os
22
22
  import warnings
23
+ import zlib
23
24
  from collections import deque, namedtuple, abc
24
- from typing import Optional, TypedDict, Union, TYPE_CHECKING
25
+ from collections.abc import Iterable
26
+ from typing import IO, Optional, TypedDict, TYPE_CHECKING, Union
25
27
 
26
28
  import orjson
27
29
  import requests
@@ -131,13 +133,113 @@ class LoggingSession(BaseUrlSession):
131
133
  return response
132
134
 
133
135
 
134
- class VersionedAPISession(LoggingSession):
135
- """A `requests.Session` subclass (technically, further specialized
136
- :class:`.LoggingSession`) that enforces conformance of API response
136
+ class PayloadCompressingSession(LoggingSession):
137
+ """A :class:`requests.Session` subclass (technically, a further specialized
138
+ :class:`.LoggingSession`) that adds support for payload compression on the
139
+ fly.
140
+
141
+ Args:
142
+ compress (bool, default=False):
143
+ Preemptively compress HTTP request body. When compression is enabled,
144
+ the payload is always compressed in 32KiB chunks and streamed to
145
+ minimize memory overhead.
146
+
147
+ .. note::
148
+ With compression enabled, the request body is transferred using chunked
149
+ encoding (``Transfer-Encoding: chunked``) and content is compressed using
150
+ the `DEFLATE <https://www.rfc-editor.org/rfc/rfc1951.txt>`_ compression
151
+ algorithm (``Content-Encoding: deflate``).
152
+
153
+ .. versionadded:: 0.13.3
154
+ Preemptive payload compression support added to :class:`.DWaveAPIClient`.
155
+
156
+ """
157
+
158
+ _compress: bool = False
159
+
160
+ def __init__(self, compress: bool = False, **kwargs):
161
+ self._compress = compress
162
+ super().__init__(**kwargs)
163
+
164
+ def set_payload_compress(self, compress: bool = True) -> bool:
165
+ """Modify payload compression on upload for current session.
166
+
167
+ Args:
168
+ compress (bool, default=True):
169
+ Enable request body compression with DEFLATE on upload requests.
170
+ Make sure the server supports compression on inbound requests,
171
+ as most servers don't.
172
+
173
+ Returns:
174
+ bool:
175
+ Previous compression setting.
176
+ """
177
+ previous = self._compress
178
+ self._compress = compress
179
+ return previous
180
+
181
+ @staticmethod
182
+ def _iter_compressed(data: Union[bytes, IO, Iterable[bytes]],
183
+ chunk_size: Optional[int] = None):
184
+ if chunk_size is None:
185
+ # match zlib window size
186
+ chunk_size = 2**15
187
+
188
+ if isinstance(data, bytes):
189
+ data = io.BytesIO(data)
190
+
191
+ if hasattr(data, 'read'):
192
+ def get_chunks(f, chunk_size):
193
+ while chunk := f.read(chunk_size):
194
+ yield chunk
195
+ chunks = get_chunks(data, chunk_size)
196
+
197
+ else:
198
+ # assume data is iterable
199
+ chunks = data
200
+
201
+ zbuf = zlib.compressobj()
202
+
203
+ for chunk in chunks:
204
+ if isinstance(chunk, str):
205
+ chunk = chunk.encode("utf-8")
206
+ if c := zbuf.compress(chunk):
207
+ yield c
208
+
209
+ yield zbuf.flush()
210
+
211
+ def request(self, *args, **kwargs):
212
+ compress = kwargs.pop('compress', self._compress)
213
+
214
+ # set compression for current request (assumes Session is not thread-safe)
215
+ old = self._compress
216
+ try:
217
+ self._compress = compress
218
+ return super().request(*args, **kwargs)
219
+ finally:
220
+ self._compress = old
221
+
222
+ def send(self, request: requests.PreparedRequest, **kwargs) -> requests.Response:
223
+ # Note: compress body on `send()` (rather than on `request()`) as by now
224
+ # json, form, and multipart data are all converted to bytes. We only need
225
+ # to handle bytes, files and iterators at this point.
226
+ if self._compress and request.body:
227
+ request.body = self._iter_compressed(request.body)
228
+ # update the prepared request for chunked upload
229
+ request.headers['Content-Encoding'] = 'deflate'
230
+ request.headers['Transfer-Encoding'] = 'chunked'
231
+ request.headers.pop('Content-Length', None)
232
+
233
+ return super().send(request, **kwargs)
234
+
235
+
236
+ class VersionedAPISession(PayloadCompressingSession):
237
+ """A :class:`requests.Session` subclass (technically, further specialized
238
+ :class:`.PayloadCompressingSession`) that enforces conformance of API response
137
239
  version with supported version range(s).
138
240
 
139
- Response format version is requested via `Accept` header field, and
140
- format/version of the response is checked via `Content-Type`.
241
+ Response format version is requested via ``Accept`` header field, and
242
+ format/version of the response is checked via ``Content-Type``.
141
243
 
142
244
  Args:
143
245
  strict_mode:
@@ -249,7 +351,7 @@ def _create_default_cache_store(**kwargs) -> abc.Mapping:
249
351
 
250
352
 
251
353
  class CachingSession(VersionedAPISession):
252
- """A `requests.Session` subclass (technically, further specialized
354
+ """A :class:`requests.Session` subclass (technically, further specialized
253
355
  :class:`.VersionedAPISession`) that caches responses and uses conditional
254
356
  requests for smart cache updates.
255
357
 
@@ -484,8 +586,9 @@ class DWaveAPIClient:
484
586
  on demand, in each thread.
485
587
 
486
588
  Example:
487
- with DWaveAPIClient(endpoint='...', timeout=(5, 600)) as client:
488
- client.session.get('...')
589
+ >>> with DWaveAPIClient(endpoint='...', timeout=(5, 600)) as client: # doctest: +SKIP
590
+ >>> client.session.get('...')
591
+
489
592
  """
490
593
 
491
594
  DEFAULTS = {
@@ -511,6 +614,9 @@ class DWaveAPIClient:
511
614
  # number of most recent request records to keep in :attr:`.session.history`
512
615
  'history_size': 0,
513
616
 
617
+ # preemptive payload compression on upload requests, see :class:`PayloadCompressingSession`
618
+ 'compress': False,
619
+
514
620
  # response version strict mode validation, see :class:`VersionedAPISession`
515
621
  'version_strict_mode': True,
516
622
 
@@ -641,6 +747,7 @@ class DWaveAPIClient:
641
747
  session = CachingSession(
642
748
  base_url=endpoint,
643
749
  history_size=config['history_size'],
750
+ compress=config['compress'],
644
751
  strict_mode=config['version_strict_mode'],
645
752
  cache=config['cache'],
646
753
  )
@@ -728,8 +835,16 @@ class SolverAPIClient(DWaveAPIClient):
728
835
  self.DEFAULTS = super().DEFAULTS.copy()
729
836
  self.DEFAULTS.update(endpoint=dwave.cloud.config.constants.DEFAULT_SOLVER_API_ENDPOINT)
730
837
 
838
+ # add qpu data compression option
839
+ self.DEFAULTS.update(compress_qpu_problem_data=False)
840
+
731
841
  super().__init__(**config)
732
842
 
843
+ @classmethod
844
+ def from_config_model(cls, config: ClientConfig, **kwargs):
845
+ kwargs.setdefault('compress_qpu_problem_data', config.compress_qpu_problem_data)
846
+ return super().from_config_model(config, **kwargs)
847
+
733
848
 
734
849
  class MetadataAPIClient(DWaveAPIClient):
735
850
  """Client for D-Wave's Metadata API."""
@@ -17,7 +17,7 @@ from __future__ import annotations
17
17
  import io
18
18
  import orjson
19
19
  from collections import abc
20
- from typing import Union, Optional, get_type_hints, TYPE_CHECKING
20
+ from typing import Callable, Union, Optional, get_type_hints, TYPE_CHECKING
21
21
  from functools import wraps
22
22
 
23
23
  from pydantic import TypeAdapter
@@ -58,6 +58,31 @@ class accepts:
58
58
  return wrapper
59
59
 
60
60
 
61
+ class compress_if:
62
+ """Decorate :class:`ResourceBase` methods to enable compression on outbound
63
+ requests if predicate evaluates to truthy.
64
+ """
65
+
66
+ def __init__(self, compress: Union[bool, Callable] = True, **kwargs):
67
+ if not callable(compress):
68
+ compress = lambda *args, **kwargs: compress
69
+ self.compress = compress
70
+
71
+ def __call__(self, fn: abc.Callable):
72
+ @wraps(fn)
73
+ def wrapper(obj: 'ResourceBase', *args, **kwargs):
74
+ restore_to = False
75
+ try:
76
+ compress = self.compress(obj, *args, **kwargs)
77
+ restore_to = obj.session.set_payload_compress(compress=compress)
78
+ return fn(obj, *args, **kwargs)
79
+
80
+ finally:
81
+ obj.session.set_payload_compress(compress=restore_to)
82
+
83
+ return wrapper
84
+
85
+
61
86
  class ResourceBase:
62
87
  """A class for interacting with a Leap resource."""
63
88
 
@@ -268,6 +293,7 @@ class Problems(ResourceBase):
268
293
  return orjson.loads(response.content)
269
294
 
270
295
  @accepts(media_type='application/vnd.dwave.sapi.problems+json', version='>=2.1,<3')
296
+ @compress_if(lambda obj, **_: obj.client.config.get('compress_qpu_problem_data'))
271
297
  def submit_problem(self, *,
272
298
  data: models.ProblemData,
273
299
  params: dict,
@@ -284,20 +310,21 @@ class Problems(ResourceBase):
284
310
  job_dict = dict(data=data.model_dump(), params=params, solver=solver,
285
311
  type=type, label=label)
286
312
  data = orjson.dumps(job_dict, option=orjson.OPT_SERIALIZE_NUMPY)
287
- response = self.session.post(
288
- path, data=data, headers={'Content-Type': 'application/json'})
313
+ headers = {'Content-Type': 'application/json'}
314
+ response = self.session.post(path, data=data, headers=headers)
289
315
  rtype = get_type_hints(self.submit_problem)['return']
290
316
  return TypeAdapter(rtype).validate_python(orjson.loads(response.content))
291
317
 
292
318
  @accepts(media_type='application/vnd.dwave.sapi.problems+json', version='>=2.1,<3')
319
+ @compress_if(lambda obj, *_, **__: obj.client.config.get('compress_qpu_problem_data'))
293
320
  def submit_problems(self, problems: list[models.ProblemJob]) -> \
294
321
  list[Union[models.ProblemInitialStatus, models.ProblemSubmitError]]:
295
322
  """Asynchronous multi-problem submit, returning initial statuses."""
296
323
  path = ''
297
324
  # note: TypeAdapter().dump_json() is 2ms vs 50us by orjson.dumps(model.model_dump())
298
325
  data = orjson.dumps([job.model_dump() for job in problems])
299
- response = self.session.post(
300
- path, data=data, headers={'Content-Type': 'application/json'})
326
+ headers = {'Content-Type': 'application/json'}
327
+ response = self.session.post(path, data=data, headers=headers)
301
328
  rtype = get_type_hints(self.submit_problems)['return']
302
329
  return TypeAdapter(rtype).validate_python(orjson.loads(response.content))
303
330
 
@@ -65,6 +65,7 @@ from plucky import pluck
65
65
  from dwave.cloud import api
66
66
  from dwave.cloud.package_info import __packagename__, __version__
67
67
  from dwave.cloud.exceptions import * # TODO: fix
68
+ from dwave.cloud.exceptions import UseAfterCloseError
68
69
  from dwave.cloud.computation import Future
69
70
  from dwave.cloud.config import load_config, update_config, validate_config_v1
70
71
  from dwave.cloud.config import constants as config_constants
@@ -85,6 +86,16 @@ __all__ = ['Client']
85
86
  logger = logging.getLogger(__name__)
86
87
 
87
88
 
89
+ def _ensure_active(method):
90
+ def _method(obj, *args, **kwargs):
91
+ with obj._closed_lock:
92
+ if obj._closed:
93
+ raise UseAfterCloseError(
94
+ f"{method.__name__} cannot be called after client has been closed")
95
+ return method(obj, *args, **kwargs)
96
+ return _method
97
+
98
+
88
99
  class Client(object):
89
100
  """Base client class for all D-Wave API clients. Used by QPU, software and
90
101
  hybrid :term:`sampler` classes.
@@ -439,6 +450,9 @@ class Client(object):
439
450
  def __init__(self, **kwargs):
440
451
  logger.debug("Client init called with: %r", kwargs)
441
452
 
453
+ self._closed = False
454
+ self._closed_lock = threading.Lock()
455
+
442
456
  # derive instance-level defaults from class defaults and init defaults
443
457
  self.defaults = copy.deepcopy(self.DEFAULTS)
444
458
  user_defaults = kwargs.pop('defaults', None)
@@ -466,9 +480,6 @@ class Client(object):
466
480
  if not self.config.token:
467
481
  raise ValueError("API token not defined")
468
482
 
469
- # Create session for main thread only
470
- self.session = self.create_session()
471
-
472
483
  # Build the problem submission queue, start its workers
473
484
  self._submission_queue = queue.Queue()
474
485
  self._submission_workers = []
@@ -558,27 +569,7 @@ class Client(object):
558
569
 
559
570
  return session
560
571
 
561
- def close(self):
562
- """Perform a clean shutdown.
563
-
564
- Waits for all the currently scheduled work to finish, kills the workers,
565
- and closes the connection pool.
566
-
567
- .. note:: Ensure your code does not submit new work while the connection is closing.
568
-
569
- Where possible, it is recommended you use a context manager (a :code:`with Client.from_config(...) as`
570
- construct) to ensure your code properly closes all resources.
571
-
572
- Examples:
573
- This example creates a client (based on an auto-detected configuration file), executes
574
- some code (represented by a placeholder comment), and then closes the client.
575
-
576
- >>> from dwave.cloud import Client
577
- >>> client = Client.from_config() # doctest: +SKIP
578
- >>> # code that uses client
579
- >>> client.close() # doctest: +SKIP
580
-
581
- """
572
+ def _shutdown_threads(self, wait: bool = True):
582
573
  # Finish all the work that requires the connection
583
574
  logger.debug("Joining submission queue")
584
575
  self._submission_queue.join()
@@ -590,14 +581,13 @@ class Client(object):
590
581
  self._load_queue.join()
591
582
 
592
583
  logger.debug("Shutting down problem upload executor")
593
- self._upload_problem_executor.shutdown()
584
+ self._upload_problem_executor.shutdown(wait=True)
594
585
  logger.debug("Shutting down problem part upload executor")
595
- self._upload_part_executor.shutdown()
586
+ self._upload_part_executor.shutdown(wait=True)
596
587
  logger.debug("Shutting down problem encoder executor")
597
- self._encode_problem_executor.shutdown()
598
-
588
+ self._encode_problem_executor.shutdown(wait=True)
599
589
  logger.debug("Shutting down answer download executor")
600
- self._download_answer_executor.shutdown()
590
+ self._download_answer_executor.shutdown(wait=True)
601
591
 
602
592
  # Send kill-task to all worker threads
603
593
  # Note: threads can't be 'killed' in Python, they have to die by
@@ -612,12 +602,40 @@ class Client(object):
612
602
  self._load_queue.put(None)
613
603
 
614
604
  # Wait for threads to die
615
- for worker in chain(self._submission_workers, self._cancel_workers,
616
- self._poll_workers, self._load_workers):
617
- worker.join()
605
+ if wait:
606
+ for worker in chain(self._submission_workers, self._cancel_workers,
607
+ self._poll_workers, self._load_workers):
608
+ worker.join()
618
609
 
619
- # Close the main thread's sessions
620
- self.session.close()
610
+ def close(self):
611
+ """Perform a clean shutdown.
612
+
613
+ Waits for all the currently scheduled work to finish, kills the workers,
614
+ and closes the connection pool.
615
+
616
+ Where possible, it is recommended you use a context manager
617
+ (a :code:`with Client.from_config(...) as` construct) to ensure your
618
+ code properly closes all resources.
619
+
620
+ Examples:
621
+ This example creates a client, executes some code (represented by
622
+ a placeholder comment), and then closes the client.
623
+
624
+ >>> from dwave.cloud import Client
625
+ >>> client = Client.from_config() # doctest: +SKIP
626
+ >>> # code that uses client
627
+ >>> client.close() # doctest: +SKIP
628
+
629
+ """
630
+ with self._closed_lock:
631
+ if self._closed:
632
+ return
633
+
634
+ # this client can't be used anymore
635
+ # note: mark it closed early to prevent job submission while closing!
636
+ self._closed = True
637
+
638
+ self._shutdown_threads(wait=True)
621
639
 
622
640
  solvers_session = getattr(self, '_solvers_session', None)
623
641
  if solvers_session:
@@ -680,6 +698,7 @@ class Client(object):
680
698
  return {r.code: {"name": r.name, "endpoint": r.endpoint} for r in rs}
681
699
 
682
700
  @property
701
+ @_ensure_active
683
702
  def solvers_session(self) -> api.resources.Solvers:
684
703
  session = getattr(self, '_solvers_session', None)
685
704
 
@@ -1200,12 +1219,14 @@ class Client(object):
1200
1219
  except IndexError:
1201
1220
  raise SolverNotFoundError("Solver with the requested features not available")
1202
1221
 
1222
+ @_ensure_active
1203
1223
  def _submit(self, body, future):
1204
1224
  """Enqueue a problem for submission to the server.
1205
1225
 
1206
1226
  This method is thread safe.
1207
1227
  """
1208
1228
  self._submission_queue.put(self._submit.Message(body, future))
1229
+
1209
1230
  _submit.Message = namedtuple('Message', ['body', 'future'])
1210
1231
 
1211
1232
  def _do_submit_problems(self):
@@ -1407,6 +1428,7 @@ class Client(object):
1407
1428
  # lock in the future, otherwise deadlock occurs.
1408
1429
  future._set_exception(exc)
1409
1430
 
1431
+ @_ensure_active
1410
1432
  def _cancel(self, id_, future):
1411
1433
  """Enqueue a problem to be canceled.
1412
1434
 
@@ -1458,6 +1480,7 @@ class Client(object):
1458
1480
  finally:
1459
1481
  session.close()
1460
1482
 
1483
+ @_ensure_active
1461
1484
  def _poll(self, future: Future) -> None:
1462
1485
  """Enqueue a problem to poll the server for status."""
1463
1486
 
@@ -1566,8 +1589,8 @@ class Client(object):
1566
1589
  if not add(future):
1567
1590
  return
1568
1591
  else:
1569
- task_done()
1570
1592
  self._poll_queue.put(task)
1593
+ task_done()
1571
1594
  break
1572
1595
 
1573
1596
  # build a query string with ids of all futures in this frame
@@ -1634,6 +1657,7 @@ class Client(object):
1634
1657
  finally:
1635
1658
  session.close()
1636
1659
 
1660
+ @_ensure_active
1637
1661
  def _load(self, future):
1638
1662
  """Enqueue a problem to download results from the server.
1639
1663
 
@@ -1685,6 +1709,7 @@ class Client(object):
1685
1709
  finally:
1686
1710
  session.close()
1687
1711
 
1712
+ @_ensure_active
1688
1713
  def _download_answer_binary_ref(self, *, auth_method: str, url: str,
1689
1714
  output: Optional[io.IOBase] = None) -> concurrent.futures.Future:
1690
1715
  """Initiate binary-ref answer download, returning the binary data in
@@ -1724,6 +1749,7 @@ class Client(object):
1724
1749
 
1725
1750
  return output
1726
1751
 
1752
+ @_ensure_active
1727
1753
  def upload_problem_encoded(self, problem, problem_id=None, **kwargs):
1728
1754
  """Initiate multipart problem upload, returning the Problem ID in a
1729
1755
  :class:`~concurrent.futures.Future`.
@@ -155,6 +155,9 @@ class ClientConfig(BaseModel, GetterMixin):
155
155
  LongPollingSchedule]] = LongPollingSchedule()
156
156
  polling_timeout: Optional[float] = None
157
157
 
158
+ # [sapi client specific] preemptive compression on qpu problem upload
159
+ compress_qpu_problem_data: Optional[bool] = True
160
+
158
161
  # general http(s) connection params
159
162
  cert: Optional[Union[str, tuple[str, str]]] = None
160
163
  headers: Optional[abc.Mapping[str, str]] = None
@@ -163,7 +166,6 @@ class ClientConfig(BaseModel, GetterMixin):
163
166
  # specific connection options
164
167
  permissive_ssl: Optional[bool] = False
165
168
  connection_close: Optional[bool] = False
166
- compress_qpu_problem_data: Optional[bool] = True
167
169
 
168
170
  # api request retry params
169
171
  request_retry: Optional[RequestRetryConfig] = RequestRetryConfig()
@@ -77,6 +77,10 @@ class ProblemUploadError(Exception):
77
77
  """Problem multipart upload failed."""
78
78
 
79
79
 
80
+ class UseAfterCloseError(Exception):
81
+ """Use attempted after client/solver/connection was closed."""
82
+
83
+
80
84
  # for backward compatibility
81
85
  from dwave.cloud.api.exceptions import RequestTimeout
82
86
 
@@ -14,7 +14,7 @@
14
14
 
15
15
  __packagename__ = 'dwave-cloud-client'
16
16
  __title__ = 'D-Wave Cloud Client'
17
- __version__ = '0.13.2'
17
+ __version__ = '0.13.3'
18
18
  __author__ = 'D-Wave Systems Inc.'
19
19
  __description__ = 'A minimal client for interacting with D-Wave cloud resources.'
20
20
  __url__ = 'https://github.com/dwavesystems/dwave-cloud-client'
@@ -33,6 +33,7 @@ import concurrent.futures
33
33
  import copy
34
34
  import logging
35
35
  import orjson
36
+ import weakref
36
37
  from collections import abc
37
38
  from functools import partial
38
39
  from tempfile import SpooledTemporaryFile
@@ -113,9 +114,25 @@ class BaseSolver(object):
113
114
  _handled_problem_types = {}
114
115
  _handled_encoding_formats = {}
115
116
 
116
- def __init__(self, client, data):
117
- # client handles async api requests (via local thread pool)
118
- self.client = client
117
+ _client_ref = None
118
+
119
+ @property
120
+ def client(self):
121
+ """Returns a reference to client if it still exists, or None otherwise."""
122
+
123
+ client = None
124
+ if self._client_ref is not None:
125
+ client = self._client_ref()
126
+ if client is None:
127
+ raise RuntimeError('Client unavailable / closed')
128
+
129
+ return client
130
+
131
+ def __init__(self, client: Optional['dwave.cloud.Client'], data: dict):
132
+ # note: we use a weakref so that client can be closed and gc'ed
133
+ # while keeping solver instances alive
134
+ # dev note: allow None value for testing
135
+ self._client_ref = weakref.ref(client) if client is not None else None
119
136
 
120
137
  # data for each solver includes at least: id, description, properties,
121
138
  # status and avg_load
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: dwave-cloud-client
3
- Version: 0.13.2
3
+ Version: 0.13.3
4
4
  Summary: A minimal client for interacting with D-Wave cloud resources.
5
5
  Home-page: https://github.com/dwavesystems/dwave-cloud-client
6
6
  Author: D-Wave Systems Inc.
@@ -48,6 +48,15 @@ Requires-Dist: dwave-optimization<0.5,>=0.1.0; extra == "nlm"
48
48
  Requires-Dist: numpy>=1.20.0; extra == "nlm"
49
49
  Provides-Extra: mocks
50
50
  Requires-Dist: dwave-networkx>=0.8.10; extra == "mocks"
51
+ Dynamic: author
52
+ Dynamic: classifier
53
+ Dynamic: description
54
+ Dynamic: home-page
55
+ Dynamic: license
56
+ Dynamic: provides-extra
57
+ Dynamic: requires-dist
58
+ Dynamic: requires-python
59
+ Dynamic: summary
51
60
 
52
61
  .. image:: https://badge.fury.io/py/dwave-cloud-client.svg
53
62
  :target: https://badge.fury.io/py/dwave-cloud-client
@@ -20,8 +20,11 @@ test_mock_solver_loading.py duplicates some of these tests against a mock server
20
20
 
21
21
  import importlib
22
22
  import json
23
+ import sys
24
+ import threading
23
25
  import time
24
26
  import unittest
27
+ import weakref
25
28
  from collections import defaultdict
26
29
  from contextlib import contextmanager
27
30
  from unittest import mock
@@ -617,7 +620,8 @@ class ClientConstruction(unittest.TestCase):
617
620
  # http retry params from config file propagated to client object
618
621
  with mock.patch("dwave.cloud.config.loaders.load_profile_from_files", lambda *pa, **kw: conf):
619
622
  with dwave.cloud.Client.from_config() as client:
620
- retry = client.session.get_adapter('https://').max_retries
623
+ session = client.create_session()
624
+ retry = session.get_adapter('https://').max_retries
621
625
  self._verify_retry_config(retry, retry_opts)
622
626
 
623
627
  # test defaults
@@ -642,7 +646,8 @@ class ClientConstruction(unittest.TestCase):
642
646
 
643
647
  with mock.patch("dwave.cloud.config.loaders.load_profile_from_files", lambda *pa, **kw: conf):
644
648
  with dwave.cloud.Client.from_config(**retry_kwargs) as client:
645
- retry = client.session.get_adapter('https://').max_retries
649
+ session = client.create_session()
650
+ retry = session.get_adapter('https://').max_retries
646
651
  self._verify_retry_config(retry, retry_kwargs)
647
652
 
648
653
 
@@ -661,6 +666,25 @@ class VerifyLazyClientImport(unittest.TestCase):
661
666
  self.assertTrue(issubclass(getattr(mod, 'Client'), Client))
662
667
 
663
668
 
669
+ class VerifyClientCleanup(unittest.TestCase):
670
+
671
+ def test_client_close(self):
672
+ thread_cnt_base = threading.active_count()
673
+
674
+ client = Client(endpoint='endpoint', token='token')
675
+ ref = weakref.ref(client)
676
+
677
+ self.assertGreater(threading.active_count(), thread_cnt_base)
678
+ self.assertGreater(sys.getrefcount(client), 1)
679
+
680
+ client.close()
681
+ del client
682
+
683
+ # verify all threads closed and no client referrers
684
+ self.assertEqual(threading.active_count(), thread_cnt_base)
685
+ self.assertIsNone(ref())
686
+
687
+
664
688
  @mock.patch("dwave.cloud.regions.get_regions", get_default_regions)
665
689
  class ClientConfigIntegration(unittest.TestCase):
666
690
 
@@ -682,7 +706,7 @@ class ClientConfigIntegration(unittest.TestCase):
682
706
  with mock.patch("dwave.cloud.config.loaders.open", iterable_mock_open(config_body)):
683
707
  with Client.from_config('config_file', profile='custom') as client:
684
708
  # check permissive_ssl and timeouts custom params passed-thru
685
- self.assertFalse(client.session.verify)
709
+ self.assertTrue(client.config.permissive_ssl)
686
710
  self.assertEqual(client.config.request_timeout, request_timeout)
687
711
  self.assertEqual(client.config.polling_timeout, polling_timeout)
688
712
 
@@ -171,6 +171,16 @@ class MockSolverLoading(unittest.TestCase):
171
171
  self.assertEqual(solver.data['status'], ref.data['status'])
172
172
  self.assertEqual(solver.data['avg_load'], ref.data['avg_load'])
173
173
 
174
+ def test_client_ref(self):
175
+ with Client(endpoint=self.endpoint, token=self.token) as client:
176
+ solver = client.get_solver(self.solver1_name)
177
+ self.assertEqual(solver.client, client)
178
+
179
+ del client
180
+
181
+ with self.assertRaises(RuntimeError):
182
+ solver.client
183
+
174
184
  def test_load_all_solvers(self):
175
185
  refs = [solver_object(self.solver1_name), solver_object(self.solver2_name)]
176
186
 
@@ -17,6 +17,7 @@
17
17
  import threading
18
18
  import time
19
19
  import unittest
20
+ import weakref
20
21
  import zlib
21
22
  from concurrent.futures import TimeoutError, ThreadPoolExecutor
22
23
  from typing import Any
@@ -36,7 +37,7 @@ from dwave.cloud.client import Client
36
37
  from dwave.cloud.computation import Future
37
38
  from dwave.cloud.exceptions import (
38
39
  SolverFailureError, CanceledFutureError, SolverError,
39
- InvalidAPIResponseError)
40
+ InvalidAPIResponseError, UseAfterCloseError)
40
41
  from dwave.cloud.solver import Solver
41
42
  from dwave.cloud.utils.qubo import evaluate_ising
42
43
  from dwave.cloud.utils.time import utcrel
@@ -873,6 +874,7 @@ class TestComputationID(unittest.TestCase):
873
874
  self.assertEqual(f.sampleset.wait_id(), submission_id)
874
875
  self.assertEqual(f.sampleset.wait_id(timeout=1), submission_id)
875
876
 
877
+
876
878
  @mock.patch('time.sleep', lambda *x: None)
877
879
  class TestOffsetHandling(_QueryTest):
878
880
 
@@ -1116,6 +1118,128 @@ class TestComputationSamplesetCaching(unittest.TestCase):
1116
1118
  self.assertIsNone(response._sampleset())
1117
1119
 
1118
1120
 
1121
+ @mock.patch.object(Client, 'create_session', lambda _: mock.Mock())
1122
+ class TestClientClose(MockSubmissionBase, unittest.TestCase):
1123
+ # exception is raised when client is used after it's been closed
1124
+
1125
+ def test_submit_fails(self):
1126
+ with Client(**self.config) as client:
1127
+ solver = Solver(client, self.sapi.solver.data)
1128
+
1129
+ with self.subTest('problem submit fails'):
1130
+ with self.assertRaises(UseAfterCloseError):
1131
+ solver.sample_ising(*self.sapi.problem)
1132
+
1133
+ with self.subTest('problem data multipart upload fails'):
1134
+ with self.assertRaises(UseAfterCloseError):
1135
+ client.upload_problem_encoded('mock')
1136
+
1137
+ def test_retrieve_fails(self):
1138
+ with Client(**self.config) as client:
1139
+ solver = Solver(client, self.sapi.solver.data)
1140
+
1141
+ with self.subTest('problem status poll fails'):
1142
+ with self.assertRaises(UseAfterCloseError):
1143
+ solver._retrieve_problem('mock-id')
1144
+
1145
+ with self.subTest('qpu answer load fails'):
1146
+ with self.assertRaises(UseAfterCloseError):
1147
+ client.retrieve_answer('problem-id')
1148
+
1149
+ with self.subTest('binary answer download fails'):
1150
+ with self.assertRaises(UseAfterCloseError):
1151
+ solver._download_binary_ref(auth_method='mock', url='mock')
1152
+
1153
+ def test_cancel_fails(self):
1154
+ with Client(**self.config) as client:
1155
+ ...
1156
+
1157
+ with self.assertRaises(UseAfterCloseError):
1158
+ client._cancel('future-id', 'future')
1159
+
1160
+ def test_ref_cleanup(self):
1161
+ with Client(**self.config) as client:
1162
+ ref = weakref.ref(client)
1163
+ solver = Solver(client, self.sapi.solver.data)
1164
+
1165
+ del client
1166
+
1167
+ self.assertIsNone(ref())
1168
+
1169
+ def test_solvers_session_access_fails(self):
1170
+ with Client(**self.config) as client:
1171
+ self.assertIsNotNone(client.solvers_session)
1172
+
1173
+ # session is closed and disabled
1174
+ with self.assertRaises(UseAfterCloseError):
1175
+ client.solvers_session
1176
+
1177
+ # hence, get_solver fails as well
1178
+ with self.assertRaises(UseAfterCloseError):
1179
+ client.get_solver()
1180
+
1181
+
1182
+ @mock.patch('time.sleep', lambda *x: None)
1183
+ class TestClientUseWhileClosing(MockSubmissionBase, unittest.TestCase):
1184
+ # make sure client can't be used even while closing (not just after close)
1185
+
1186
+ poll_strategy = "long-polling"
1187
+ poll_params = dict(timeout=Client.DEFAULTS['poll_wait_time'])
1188
+
1189
+ def test_submit_while_closing(self):
1190
+ submission_id = 'test-id'
1191
+ submission_status = 'PENDING'
1192
+ release_status = threading.Event()
1193
+
1194
+ def create_mock_session(client):
1195
+ reply_body = [self.sapi.continue_reply(id=submission_id, status=submission_status)]
1196
+
1197
+ session = mock.Mock()
1198
+
1199
+ # make sure polling for status stalls until we set `release_status`
1200
+ def get(path, **kwargs):
1201
+ release_status.wait()
1202
+ return choose_reply(path, fix_status_paths({
1203
+ f'problems/?id={submission_id}': reply_body}, **self.poll_params))
1204
+
1205
+ session.get = get
1206
+ session.post = lambda path, **kwargs: choose_reply(path, {
1207
+ 'problems/': reply_body})
1208
+
1209
+ return session
1210
+
1211
+ with mock.patch.object(Client, 'create_session', create_mock_session):
1212
+ with Client(**self.config) as client:
1213
+ solver = Solver(client, self.sapi.solver.data)
1214
+
1215
+ future = solver.sample_ising(*self.sapi.problem)
1216
+
1217
+ # check the first job is in `pending`
1218
+ future.wait_id()
1219
+ self.assertEqual(future.id, submission_id)
1220
+ self.assertEqual(future.remote_status, submission_status)
1221
+
1222
+ # now close the client, but since client.close() is blocking,
1223
+ # do it in a background thread
1224
+ t = threading.Thread(target=client.close)
1225
+ t.start()
1226
+
1227
+ # try submitting another job while the client is closing
1228
+ with self.assertRaises(UseAfterCloseError):
1229
+ solver.sample_ising(*self.sapi.problem)
1230
+
1231
+ # verify client.close is still running
1232
+ t.join(timeout=0.1)
1233
+ self.assertTrue(t.is_alive())
1234
+
1235
+ # release the first job
1236
+ release_status.set()
1237
+
1238
+ # verify client is closed
1239
+ t.join()
1240
+ self.assertFalse(t.is_alive())
1241
+
1242
+
1119
1243
  class TestThreadSafety(unittest.TestCase):
1120
1244
 
1121
1245
  def test_result_loading(self):