Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 142
Expand file tree
/
Copy pathfuture.cc
More file actions
1377 lines (1211 loc) · 44 KB
/
Copy pathfuture.cc
File metadata and controls
1377 lines (1211 loc) · 44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 The TensorStore Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
// Other headers must be included after pybind11 to ensure header-order
// inclusion constraints are satisfied.
#include "python/tensorstore/future.h"
// Other headers
#include <stddef.h>
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <memory>
#include <optional>
#include <utility>
#include <vector>
#include "absl/functional/function_ref.h"
#include "absl/status/status.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "python/tensorstore/critical_section.h"
#include "python/tensorstore/define_heap_type.h"
#include "python/tensorstore/garbage_collection.h"
#include "python/tensorstore/gil_safe.h"
#include "python/tensorstore/python_imports.h"
#include "python/tensorstore/python_value_or_exception.h"
#include "python/tensorstore/tensorstore_module_components.h"
#include "python/tensorstore/type_name_override.h"
#include "tensorstore/internal/container/intrusive_linked_list.h"
#include "tensorstore/internal/global_initializer.h"
#include "tensorstore/serialization/fwd.h"
#include "tensorstore/util/executor.h"
#include "tensorstore/util/future.h"
#ifdef _WIN32
#include <windows.h>
#elif defined(__APPLE__)
#include <pthread.h>
#else
#include <semaphore.h>
#endif
#ifdef _WIN32
// This declaration was removed from the public headers in Python 3.13.
// https://github.com/python/cpython/pull/108605
extern "C" {
PyAPI_FUNC(void*) _PyOS_SigintEvent(void);
}
#endif
namespace tensorstore {
namespace internal_python {
namespace py = ::pybind11;
namespace {
enum class ScopedEventWaitResult {
kSuccess,
kInterrupt,
kTimeout,
};
// Define platform-dependent `ScopedEvent` class that supports waiting that is
// interrupted if the process receives a signal.
//
// Initially, the event is in the "unset" state. The `Set` method changes the
// event to the "set" state. The `Wait` method waits until the "set" state is
// reached, the process receives a signal, or the deadline is reached.
#ifdef _WIN32
class ScopedEvent {
public:
ScopedEvent() {
sigint_event = _PyOS_SigintEvent();
assert(sigint_event != nullptr);
handle = ::CreateEventA(/*lpEventAttributes=*/nullptr,
/*bManualReset=*/TRUE,
/*bInitialState=*/FALSE,
/*lpName=*/nullptr);
assert(handle != nullptr);
}
~ScopedEvent() { ::CloseHandle(handle); }
void Set() { ::SetEvent(handle); }
ScopedEventWaitResult Wait(absl::Time deadline) {
const HANDLE handles[2] = {handle, sigint_event};
DWORD timeout;
if (deadline == absl::InfiniteFuture()) {
timeout = INFINITE;
} else {
int64_t ms = absl::ToInt64Milliseconds(deadline - absl::Now());
ms = std::max(int64_t(0), ms);
timeout =
static_cast<DWORD>(std::min(ms, static_cast<int64_t>(INFINITE)));
}
DWORD res = ::WaitForMultipleObjectsEx(2, handles, /*bWaitAll=*/FALSE,
/*dwMilliseconds=*/timeout,
/*bAlertable=*/FALSE);
if (res == WAIT_OBJECT_0 + 1) {
::ResetEvent(sigint_event);
return ScopedEventWaitResult::kInterrupt;
} else if (res == WAIT_OBJECT_0) {
return ScopedEventWaitResult::kSuccess;
} else {
assert(res == WAIT_TIMEOUT);
return ScopedEventWaitResult::kTimeout;
}
}
HANDLE handle;
HANDLE sigint_event;
};
#elif defined(__APPLE__)
// POSIX unnamed semaphores are not implemented on Mac OS. Use
// `pthread_cond_wait`/`pthread_cond_timedwait` instead, as it is also
// interruptible by signals.
class ScopedEvent {
public:
ScopedEvent() {
{
[[maybe_unused]] int err = ::pthread_mutex_init(&mutex, nullptr);
assert(err == 0);
}
{
[[maybe_unused]] int err = ::pthread_cond_init(&cond, nullptr);
assert(err == 0);
}
}
~ScopedEvent() {
{
[[maybe_unused]] int err = ::pthread_cond_destroy(&cond);
assert(err == 0);
}
{
[[maybe_unused]] int err = ::pthread_mutex_destroy(&mutex);
assert(err == 0);
}
}
void Set() {
{
[[maybe_unused]] int err = ::pthread_mutex_lock(&mutex);
assert(err == 0);
}
set = true;
{
[[maybe_unused]] int err = ::pthread_mutex_unlock(&mutex);
assert(err == 0);
}
::pthread_cond_signal(&cond);
}
ScopedEventWaitResult Wait(absl::Time deadline) {
{
[[maybe_unused]] int err = ::pthread_mutex_lock(&mutex);
assert(err == 0);
}
bool set_value = set;
bool timeout = false;
if (!set_value) {
if (deadline == absl::InfiniteFuture()) {
::pthread_cond_wait(&cond, &mutex);
} else {
const auto tspec = ToTimespec(deadline);
timeout = ::pthread_cond_timedwait(&cond, &mutex, &tspec) == ETIMEDOUT;
}
set_value = set;
}
{
[[maybe_unused]] int err = ::pthread_mutex_unlock(&mutex);
assert(err == 0);
}
return set_value ? ScopedEventWaitResult::kSuccess
: (timeout ? ScopedEventWaitResult::kTimeout
: ScopedEventWaitResult::kInterrupt);
}
bool set{false};
::pthread_mutex_t mutex;
::pthread_cond_t cond;
};
#else
// Use POSIX semaphores
class ScopedEvent {
public:
ScopedEvent() {
[[maybe_unused]] int err = ::sem_init(&sem, /*pshared=*/0, 0);
assert(err == 0);
}
~ScopedEvent() {
[[maybe_unused]] int err = ::sem_destroy(&sem);
assert(err == 0);
}
void Set() {
[[maybe_unused]] int err = ::sem_post(&sem);
assert(err == 0);
}
ScopedEventWaitResult Wait(absl::Time deadline) {
if (deadline == absl::InfiniteFuture()) {
if (::sem_wait(&sem) == 0) return ScopedEventWaitResult::kSuccess;
assert(errno == EINTR);
} else {
const auto tspec = absl::ToTimespec(deadline);
if (::sem_timedwait(&sem, &tspec) == 0) {
return ScopedEventWaitResult::kSuccess;
}
assert(errno == EINTR || errno == ETIMEDOUT);
if (errno == ETIMEDOUT) return ScopedEventWaitResult::kTimeout;
}
return ScopedEventWaitResult::kInterrupt;
}
::sem_t sem;
};
#endif
class ScopedFutureCallbackRegistration {
public:
ScopedFutureCallbackRegistration(FutureCallbackRegistration registration)
: registration_(std::move(registration)) {}
~ScopedFutureCallbackRegistration() { registration_.Unregister(); }
private:
FutureCallbackRegistration registration_;
};
// A `CancelCallback` is a callback that is invoked when a `PythonFutureObject`
// is cancelled. It is stored in a linked list, since there may be multiple
// cancel callbacks for a single `PythonFutureObject`.
//
// At present this is only used by InterruptibleWaitImpl, and locking is done
// within the function.
struct CancelCallback : public PythonFutureObject::CancelCallbackBase {
using CancelCallbackBase = PythonFutureObject::CancelCallbackBase;
using Accessor =
internal::intrusive_linked_list::MemberAccessor<CancelCallbackBase>;
explicit CancelCallback(PythonFutureObject* base,
absl::FunctionRef<void()> callback)
: callback(callback) {
internal::intrusive_linked_list::InsertBefore(
Accessor{}, &base->cpp_data.cancel_callbacks, this);
}
~CancelCallback() {
internal::intrusive_linked_list::Remove(Accessor{}, this);
}
absl::FunctionRef<void()> callback;
};
} // namespace
using WeakFuturePtr = PythonFutureObject::WeakFuturePtr;
[[noreturn]] void ThrowCancelledError() {
PyErr_SetNone(python_imports.asyncio_cancelled_error_class.ptr());
throw py::error_already_set();
}
[[noreturn]] void ThrowTimeoutError() {
PyErr_SetNone(python_imports.builtins_timeout_error_class.ptr());
throw py::error_already_set();
}
pybind11::object GetCancelledError() {
return python_imports.asyncio_cancelled_error_class(py::none());
}
// Returns `true` if the Future was cancelled.
static inline bool StateIsCancelled(
internal_future::FutureStatePointer& state) {
return !state;
}
// Returns `true` if the underlying Future is ready (either with a value or
// an error) or already cancelled.
static inline bool StateIsDone(internal_future::FutureStatePointer& state) {
return !state || state->ready();
}
void InterruptibleWaitImpl(tensorstore::AnyFuture future, absl::Time deadline,
PythonFutureObject* python_future) {
if (future.ready()) return;
{
GilScopedRelease gil_release;
future.Force();
}
ScopedEvent event;
const auto notify_done = [&event] { event.Set(); };
std::optional<CancelCallback> cancel_callback;
if (python_future) {
absl::MutexLock lock(python_future->cpp_data.mutex);
cancel_callback.emplace(python_future, notify_done);
}
ScopedFutureCallbackRegistration registration{
future.UntypedExecuteWhenReady([&event](auto future) { event.Set(); })};
while (true) {
ScopedEventWaitResult wait_result;
{
GilScopedRelease gil_release;
wait_result = event.Wait(deadline);
}
switch (wait_result) {
case ScopedEventWaitResult::kSuccess:
if (python_future) {
absl::MutexLock lock(python_future->cpp_data.mutex);
cancel_callback = std::nullopt;
if (StateIsCancelled(python_future->cpp_data.state)) {
ThrowCancelledError();
}
}
return;
case ScopedEventWaitResult::kTimeout:
if (python_future) {
absl::MutexLock lock(python_future->cpp_data.mutex);
cancel_callback = std::nullopt;
}
ThrowTimeoutError();
case ScopedEventWaitResult::kInterrupt:
break;
}
if (PyErr_CheckSignals() == -1) {
if (python_future) {
absl::MutexLock lock(python_future->cpp_data.mutex);
cancel_callback = std::nullopt;
}
throw py::error_already_set();
}
}
}
bool PythonFutureObject::Cancel() {
std::vector<pybind11::object> done_callbacks;
{
absl::MutexLock lock(cpp_data.mutex);
if (StateIsDone(cpp_data.state)) return false;
cpp_data.state = {};
cpp_data.registration.Unregister();
done_callbacks = std::move(cpp_data.callbacks);
// Run cancel callbacks. Note that the only user of cancel callbacks
// is InterruptibleWaitImpl, which is safe to run with locks held.
for (CancelCallbackBase* callback = cpp_data.cancel_callbacks.next;
callback != &cpp_data.cancel_callbacks;) {
auto* next = callback->next;
static_cast<CancelCallback*>(callback)->callback();
callback = next;
}
}
RunCallbacks(std::move(done_callbacks));
return true;
}
void PythonFutureObject::Force() {
// Use copy of `state`, since `state` may be modified by another thread
// calling `Cancel` once GIL is released.
internal_future::FutureStatePointer state;
{
absl::MutexLock lock(cpp_data.mutex);
if (StateIsDone(cpp_data.state)) return;
state = cpp_data.state;
}
GilScopedRelease gil_release;
state->Force();
}
pybind11::object PythonFutureObject::GetAwaitable() {
// Logically, `done_callback` needs to capture `awaitable_future`. However,
// lambda captures don't interoperate with Python garbage collection.
// Instead, we create it as a capture-less function and then use a
// `PyMethod` object to capture `awaitable_future` as the `self` argument.
auto done_callback = py::cpp_function([](py::handle awaitable_future,
py::handle source_future) {
awaitable_future.attr("get_loop")().attr("call_soon_threadsafe")(
py::cpp_function([](py::handle source_future,
py::object awaitable_future) {
if (awaitable_future.attr("done")().ptr() == Py_True) {
return;
}
if (source_future.attr("cancelled")().ptr() == Py_True) {
awaitable_future.attr("cancel")();
return;
}
auto exc = source_future.attr("exception")();
if (!exc.is_none()) {
awaitable_future.attr("set_exception")(std::move(exc));
} else {
awaitable_future.attr("set_result")(source_future.attr("result")());
}
}),
source_future, awaitable_future);
});
py::object awaitable_future =
python_imports.asyncio_get_event_loop_function().attr("create_future")();
// Ensure the PythonFutureObject is cancelled if the awaitable future is
// cancelled.
auto cancel_callback = py::cpp_function(
[](py::handle source_future, py::handle awaitable_future) {
reinterpret_cast<PythonFutureObject*>(source_future.ptr())->Cancel();
});
auto bound_cancel_callback = py::reinterpret_steal<py::object>(
PyMethod_New(cancel_callback.ptr(), reinterpret_cast<PyObject*>(this)));
if (!bound_cancel_callback) throw py::error_already_set();
awaitable_future.attr("add_done_callback")(bound_cancel_callback);
// Ensure the awaitable future is marked ready once the PythonFutureObject
// becomes ready.
auto bound_done_callback = py::reinterpret_steal<py::object>(
PyMethod_New(done_callback.ptr(), awaitable_future.ptr()));
if (!bound_done_callback) throw py::error_already_set();
AddDoneCallback(bound_done_callback);
return awaitable_future.attr("__await__")();
}
pybind11::object PythonFutureObject::GetResult(absl::Time deadline) {
internal_future::FutureStatePointer state;
{
absl::MutexLock lock(cpp_data.mutex);
state = cpp_data.state;
}
if (StateIsCancelled(state)) ThrowCancelledError();
auto any_future = internal_future::FutureAccess::Construct<AnyFuture>(state);
InterruptibleWaitImpl(any_future, deadline, this);
return vtable->get_result(*state);
}
pybind11::object PythonFutureObject::GetException(absl::Time deadline) {
internal_future::FutureStatePointer state;
{
absl::MutexLock lock(cpp_data.mutex);
if (StateIsCancelled(cpp_data.state)) ThrowCancelledError();
state = cpp_data.state;
}
auto any_future = internal_future::FutureAccess::Construct<AnyFuture>(state);
InterruptibleWaitImpl(any_future, deadline, this);
return vtable->get_exception(*state);
}
Future<GilSafePythonHandle> PythonFutureObject::GetPythonValueFuture() {
internal_future::FutureStatePointer state;
{
absl::MutexLock lock(cpp_data.mutex);
if (StateIsCancelled(cpp_data.state)) return absl::CancelledError("");
state = cpp_data.state;
}
return vtable->get_python_value_future(*state);
}
void PythonFutureObject::AddDoneCallback(pybind11::handle callback) {
absl::ReleasableMutexLock lock(cpp_data.mutex);
if (StateIsDone(cpp_data.state)) {
lock.Release();
callback(py::handle(reinterpret_cast<PyObject*>(this)));
return;
}
cpp_data.callbacks.push_back(py::reinterpret_borrow<py::object>(callback));
if (cpp_data.callbacks.size() == 1) {
Py_INCREF(reinterpret_cast<PyObject*>(this));
internal_future::FutureStatePointer state = cpp_data.state;
lock.Release();
// Minimal implementation of `Force`
GilScopedRelease gil_release;
state->Force();
}
}
size_t PythonFutureObject::RemoveDoneCallback(pybind11::handle callback) {
bool do_decref = false;
size_t num_removed = 0;
{
absl::MutexLock lock(cpp_data.mutex);
auto& callbacks = cpp_data.callbacks;
// Since caller owns a reference to `callback`, we can be sure that removing
// `callback` from `callbacks` does not result in any reference counts
// reaching zero, and therefore we can be sure that `*this` is not modified.
auto it = std::remove_if(
callbacks.begin(), callbacks.end(),
[&](pybind11::handle h) { return h.ptr() == callback.ptr(); });
num_removed = callbacks.end() - it;
callbacks.erase(it, callbacks.end());
do_decref = num_removed && callbacks.empty();
}
if (do_decref) {
Py_DECREF(reinterpret_cast<PyObject*>(this));
}
return num_removed;
}
void PythonFutureObject::RunCallbacks(
std::vector<pybind11::object> done_callbacks) {
if (done_callbacks.empty()) return;
// If this object has already been finalized, then it is not safe to call
// callbacks, because they may now be in an invalid state due to garbage
// collection cycle breaking.
if (!PyObject_GC_IsFinalized(reinterpret_cast<PyObject*>(this))) {
for (py::handle callback : done_callbacks) {
if (PyObject* callback_result = PyObject_CallFunctionObjArgs(
callback.ptr(), reinterpret_cast<PyObject*>(this), nullptr)) {
Py_DECREF(callback_result);
continue;
}
PyErr_WriteUnraisable(nullptr);
PyErr_Clear();
}
}
Py_DECREF(reinterpret_cast<PyObject*>(this));
}
absl::Time GetWaitDeadline(std::optional<double> timeout,
std::optional<double> deadline) {
absl::Time deadline_time = absl::InfiniteFuture();
if (deadline) {
deadline_time = absl::UnixEpoch() + absl::Seconds(*deadline);
}
if (timeout) {
deadline_time =
std::min(deadline_time, absl::Now() + absl::Seconds(*timeout));
}
return deadline_time;
}
pybind11::object TryConvertToFuture(pybind11::handle src,
pybind11::handle loop) {
if (Py_TYPE(src.ptr()) == PythonFutureObject::python_type) {
return py::reinterpret_borrow<py::object>(src);
}
if (python_imports.asyncio_iscoroutine_function(src).ptr() != Py_True) {
return {};
}
if (loop.is_none()) {
throw py::value_error(
"no event loop specified and thread does not have a default event "
"loop");
}
auto asyncio_future =
python_imports.asyncio_run_coroutine_threadsafe_function(src, loop);
auto pair = PromiseFuturePair<GilSafePythonValueOrExceptionWeakRef>::Make();
// Create Python future wrapper before adding `done_callback`, to ensure that
// any references are retained by the `PythonObjectReferenceManager` of
// `future`.
auto future = PythonFutureObject::Make(std::move(pair.future));
// Register done callback.
py::object done_callback =
py::cpp_function([promise = pair.promise](py::object future_obj) {
py::object result;
if (py::object method = py::reinterpret_steal<py::object>(
PyObject_GetAttrString(future_obj.ptr(), "result"));
method.ptr()) {
result = py::reinterpret_steal<py::object>(
PyObject_CallFunctionObjArgs(method.ptr(), nullptr));
}
PythonValueOrException value =
result ? PythonValueOrException(std::move(result))
: PythonValueOrException::FromErrorIndicator();
PythonObjectReferenceManager manager;
PythonValueOrExceptionWeakRef value_weak_ref(manager, value);
// Release the GIL when invoking `promise.SetResult` in order to avoid
// blocking other Python threads while arbitrary C++ callbacks are run.
{
GilScopedRelease gil_release;
promise.SetResult(std::move(value_weak_ref));
}
});
asyncio_future.attr("add_done_callback")(done_callback);
// Register cancellation handler.
pair.promise.ExecuteWhenNotNeeded(
[asyncio_future = asyncio_future.release().ptr()] {
ExitSafeGilScopedAcquire gil;
if (!gil.acquired()) return;
// Invoke `cancel` method.
if (auto method = py::reinterpret_steal<py::object>(
PyObject_GetAttrString(asyncio_future, "cancel"));
!method.ptr()) {
// Ignore error obtaining `cancel` method.
PyErr_WriteUnraisable(nullptr);
PyErr_Clear();
} else if (!py::reinterpret_steal<py::object>(
PyObject_CallFunctionObjArgs(method.ptr(), nullptr))
.ptr()) {
// Ignore error calling `cancel` method.
PyErr_WriteUnraisable(nullptr);
PyErr_Clear();
}
Py_DECREF(asyncio_future);
});
return future;
}
namespace {
using FutureCls = py::class_<PythonFutureObject>;
using PromiseCls = py::class_<PythonPromiseObject>;
PyObject* FutureAlloc(PyTypeObject* type, Py_ssize_t nitems) {
PyObject* ptr = PyType_GenericAlloc(type, nitems);
if (!ptr) return nullptr;
// Immediately untrack by the garbage collector since the object is not yet
// fully constructed. Once it is fully constructed,
// `PythonFutureObject::Make` marks it as tracked again. There is no race
// condition here because there are no intervening Python API calls
// `PyType_GenericAlloc` marks it as tracked.
PyObject_GC_UnTrack(ptr);
auto& cpp_data = reinterpret_cast<PythonFutureObject*>(ptr)->cpp_data;
new (&cpp_data) PythonFutureObject::CppData;
internal::intrusive_linked_list::Initialize(CancelCallback::Accessor{},
&cpp_data.cancel_callbacks);
return ptr;
}
void FutureFinalize(PyObject* self) {
// No-op function that must be specified to ensure that
// `PyObject_GC_IsFinalized` becomes `true`.
}
void FutureDealloc(PyObject* self) {
auto& obj = *reinterpret_cast<PythonFutureObject*>(self);
auto& cpp_data = obj.cpp_data;
// Ensure object is not tracked by garbage collector before invalidating
// invariants during destruction.
PyObject_GC_UnTrack(self);
if (obj.weakrefs) PyObject_ClearWeakRefs(self);
// Clear `state`: this ensures that the callback corresponding to
// `registration` does not run with the reference count equal to 0.
FutureCallbackRegistration do_unregister;
PythonObjectReferenceManager refs;
{
absl::MutexLock lock(cpp_data.mutex);
cpp_data.state = {};
do_unregister = std::exchange(cpp_data.registration, {});
refs = std::move(cpp_data.reference_manager);
// There can be no live callbacks, otherwise the PyObject would be live.
assert(cpp_data.callbacks.empty());
}
if (cpp_data.weak_future_pointer) {
// Signal that the future is no longer live.
absl::MutexLock lock(cpp_data.weak_future_pointer->mutex);
cpp_data.weak_future_pointer->future = nullptr;
}
{
GilScopedRelease gil_release;
do_unregister.Unregister();
}
refs.Clear();
// Deallocate and free after clearing references.
cpp_data.~CppData();
PyTypeObject* type = Py_TYPE(self);
type->tp_free(self);
Py_DECREF(type);
}
// Invokes the visitor on each Python object directly owned by this object,
// as required by the `tp_traverse` protocol.
//
// This is invoked by the `tp_traverse` method for `tensorstore.Future`,
// which is called by the garbage collector to determine which objects are
// reachable from this object.
int FutureTraverse(PyObject* self, visitproc visit, void* arg) {
auto& cpp_data = reinterpret_cast<PythonFutureObject*>(self)->cpp_data;
absl::MutexLock lock(cpp_data.mutex);
Py_VISIT(Py_TYPE(self));
for (const auto& obj : cpp_data.callbacks) {
Py_VISIT(obj.ptr());
}
return cpp_data.reference_manager.Traverse(visit, arg);
}
// Clears Python references directly owned by this object, as required by the
// `tp_clear` protocol.
//
// This is invoked by the `tp_clear` method for `tensorstore.Future`, which
// is called by the garbage collector to break a reference cycle that
// contains this object.
//
// This leaves the object in a valid state, but all callbacks are
// unregistered and the accessor methods will behave as if the future was
// cancelled.
int FutureClear(PyObject* self) {
auto& cpp_data = reinterpret_cast<PythonFutureObject*>(self)->cpp_data;
FutureCallbackRegistration do_unregister;
PythonObjectReferenceManager refs;
std::vector<pybind11::object> done_callbacks;
{
absl::MutexLock lock(cpp_data.mutex);
cpp_data.state = {};
do_unregister = std::exchange(cpp_data.registration, {});
refs = std::move(cpp_data.reference_manager);
done_callbacks = std::move(cpp_data.callbacks);
}
// Signal that the future is no longer live.
if (cpp_data.weak_future_pointer) {
absl::MutexLock lock(cpp_data.weak_future_pointer->mutex);
cpp_data.weak_future_pointer->future = nullptr;
}
{
GilScopedRelease gil_release;
do_unregister.Unregister();
}
if (!done_callbacks.empty()) {
done_callbacks.clear();
Py_DECREF(self);
}
refs.Clear();
return 0;
}
FutureCls MakeFutureClass(py::module m) {
const char* doc = R"(
Handle for *consuming* the result of an asynchronous operation.
This type supports several different patterns for consuming results:
- Asynchronously with :py:mod:`asyncio`, using the :ref:`await<python:await>`
keyword:
>>> future = ts.open({
... 'driver': 'array',
... 'array': [1, 2, 3],
... 'dtype': 'uint32'
... })
>>> await future
TensorStore({
'array': [1, 2, 3],
'context': {'data_copy_concurrency': {}},
'driver': 'array',
'dtype': 'uint32',
'transform': {'input_exclusive_max': [3], 'input_inclusive_min': [0]},
})
- Synchronously blocking the current thread, by calling :py:meth:`.result()`.
>>> future = ts.open({
... 'driver': 'array',
... 'array': [1, 2, 3],
... 'dtype': 'uint32'
... })
>>> future.result()
TensorStore({
'array': [1, 2, 3],
'context': {'data_copy_concurrency': {}},
'driver': 'array',
'dtype': 'uint32',
'transform': {'input_exclusive_max': [3], 'input_inclusive_min': [0]},
})
- Asynchronously, by registering a callback using :py:meth:`.add_done_callback`:
>>> future = ts.open({
... 'driver': 'array',
... 'array': [1, 2, 3],
... 'dtype': 'uint32'
... })
>>> future.add_done_callback(
... lambda f: print(f'Callback: {f.result().domain}'))
... future.force() # ensure the operation is started
... # wait for completion (for testing only)
... result = future.result()
Callback: { [0, 3) }
If an error occurs, instead of returning a value, :py:obj:`.result()` or
:ref:`await<python:await>` will raise an exception.
This type supports a subset of the interfaces of
:py:class:`python:concurrent.futures.Future` and
:py:class:`python:asyncio.Future`. Unlike those types, however,
:py:class:`Future` provides only the *consumer* interface. The corresponding
*producer* interface is provided by :py:class:`Promise`.
.. warning::
While this class is designed to interoperate with :py:mod:`asyncio`, it
cannot be used with functions such as :py:obj:`asyncio.wait` that require an
:py:class:`python:asyncio.Future`, because :py:obj:`.add_done_callback` does
not guarantee that the callback is invoked from the current event loop. To
convert to a real :py:class:`python:asyncio.Future`, use
:py:obj:`python:asyncio.ensure_future`:
>>> dataset = await ts.open({
... 'driver': 'zarr',
... 'kvstore': 'memory://'
... },
... dtype=ts.uint32,
... shape=[70, 80],
... create=True)
>>> await asyncio.wait([
... asyncio.ensure_future(dataset[i * 5].write(i))
... for i in range(10)
... ])
See also:
- :py:class:`WriteFutures`
Type parameters:
T:
Result type of the asynchronous operation.
Group:
Asynchronous support
)";
static const PyMethodDef future_methods[] = {
{"__class_getitem__", Py_GenericAlias, METH_O | METH_CLASS, ""},
{nullptr},
};
PyType_Slot slots[] = {
{Py_tp_doc, const_cast<char*>(doc)},
{Py_tp_alloc, reinterpret_cast<void*>(&FutureAlloc)},
{Py_tp_dealloc, reinterpret_cast<void*>(&FutureDealloc)},
{Py_tp_traverse, reinterpret_cast<void*>(&FutureTraverse)},
{Py_tp_clear, reinterpret_cast<void*>(&FutureClear)},
{Py_tp_finalize, reinterpret_cast<void*>(&FutureFinalize)},
{Py_tp_methods,
const_cast<void*>(reinterpret_cast<const void*>(future_methods))},
{0, nullptr},
};
PyType_Spec spec = {};
spec.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC;
spec.slots = slots;
auto cls = DefineHeapType<PythonFutureObject>(spec);
PythonFutureObject::python_type->tp_weaklistoffset =
offsetof(PythonFutureObject, weakrefs);
m.attr("Future") = cls;
return cls;
}
void DefineFutureAttributes(FutureCls& cls) {
cls.def(
"__new__",
[](py::handle cls_unused, UntypedFutureLike python_future,
std::optional<AbstractEventLoopParameter> loop)
-> UntypedFutureWrapper {
if (!loop) loop.emplace().value = GetCurrentThreadAsyncioEventLoop();
if (py::object future =
TryConvertToFuture(python_future.value, loop->value)) {
return {future};
}
PythonObjectReferenceManager manager;
return {PythonFutureObject::Make(
Future<GilSafePythonValueOrExceptionWeakRef>(
GilSafePythonValueOrExceptionWeakRef{
PythonValueOrExceptionWeakRef(
manager, PythonValueOrException{
std::move(python_future.value)})}))};
},
R"(
Converts a :py:obj:`.FutureLike` object to a :py:obj:`.Future`.
Example:
>>> await ts.Future(3)
3
>>> x = ts.Future(3)
>>> assert x is ts.Future(x)
>>> async def get_value():
... return 42
>>> x = ts.Future(get_value())
>>> x.done()
False
>>> await x
>>> x.result()
42
Args:
future: Specifies the immediate or asynchronous result.
loop: Event loop on which to run :py:param:`.future` if it is a
:ref:`coroutine<async>`. If not specified (or :py:obj:`None` is specified),
defaults to the loop returned by :py:obj:`asyncio.get_running_loop`. If
:py:param:`.loop` is not specified and there is no running event loop, it is
an error for :py:param:`.future` to be a coroutine.
Returns:
- If :py:param:`.future` is a :py:obj:`.Future`, it is simply returned as is.
- If :py:param:`.future` is a :ref:`coroutine<async>`, it is run using
:py:param:`.loop` and the returned :py:obj:`.Future` corresponds to the
asynchronous result.
- Otherwise, :py:param:`.future` is treated as an immediate result, and the
returned :py:obj:`.Future` resolves immediately to :py:param:`.future`.
Warning:
If :py:param:`.future` is a :ref:`coroutine<async>`, a blocking call to
:py:obj:`Future.result` or :py:obj:`Future.exception` in the thread running
the associated event loop may lead to deadlock. Blocking calls should be
avoided when using an event loop.
)",
py::arg("future"), py::kw_only(), py::arg("loop") = std::nullopt);
cls.def("__await__", [](PythonFutureObject& self) -> AwaitResult<TypeVarT> {
return {self.GetAwaitable()};
});
cls.def(
"add_done_callback",
[](PythonFutureObject& self, Callable<void, Future<TypeVarT>> callback) {
self.AddDoneCallback(callback.value);
},
py::arg("callback"),
R"(
Registers a callback to be invoked upon completion of the asynchronous operation.
Args:
callback: Callback to invoke with :python:`self` when this future becomes
ready.
.. warning::
Unlike :py:obj:`python:asyncio.Future.add_done_callback`, but like
:py:obj:`python:concurrent.futures.Future.add_done_callback`, the
:py:param:`.callback` may be invoked from any thread. If using
:py:mod:`asyncio` and :py:param:`.callback` needs to be invoked from a
particular event loop, wrap :py:param:`.callback` with
:py:obj:`python:asyncio.loop.call_soon_threadsafe`.
Group:
Callback interface
)");
cls.def(
"remove_done_callback",
[](PythonFutureObject& self, Callable<void, Future<TypeVarT>> callback) {
return self.RemoveDoneCallback(callback.value);
},
py::arg("callback"),
R"(
Unregisters a previously-registered callback.
Group:
Callback interface
)");
cls.def(
"result",
[](PythonFutureObject& self, std::optional<double> timeout,
std::optional<double> deadline) -> TypeVarT {
return TypeVarT{self.GetResult(GetWaitDeadline(timeout, deadline))};
},
py::arg("timeout") = std::nullopt, py::arg("deadline") = std::nullopt,
R"(
Blocks until the asynchronous operation completes, and returns the result.
If the asynchronous operation completes unsuccessfully, raises the error that
was produced.
Args:
timeout: Maximum number of seconds to block.
deadline: Deadline in seconds since the Unix epoch.
Returns:
The result of the asynchronous operation, if successful.
Raises:
TimeoutError: If the result did not become ready within the specified
:py:param:`.timeout` or :py:param:`.deadline`.
KeyboardInterrupt: If running on the main thread and a keyboard interrupt is
received.
Group:
Blocking interface
)");
cls.def(
"exception",
[](PythonFutureObject& self, std::optional<double> timeout,
std::optional<double> deadline) -> py::object {
You can’t perform that action at this time.
