ZTWHHH commited on
Commit
966937d
·
verified ·
1 Parent(s): af69712

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_cholesky_solve_helper_native.h +23 -0
  2. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_copy.h +44 -0
  3. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_maximum_compositeexplicitautograd_dispatch.h +28 -0
  4. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sign.h +44 -0
  5. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_histogramdd_from_bin_cts_native.h +22 -0
  6. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_local_scalar_dense_cuda_dispatch.h +23 -0
  7. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_remove_batch_dim_ops.h +28 -0
  8. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_softmax_backward_data_meta.h +27 -0
  9. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_trilinear_native.h +22 -0
  10. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_nearest_exact2d_backward_meta_dispatch.h +28 -0
  11. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/all_compositeexplicitautograd_dispatch.h +25 -0
  12. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/arcsinh_compositeimplicitautograd_dispatch.h +26 -0
  13. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/binomial_cuda_dispatch.h +23 -0
  14. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/cumprod.h +53 -0
  15. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/diagonal_scatter.h +39 -0
  16. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/empty_like_native.h +26 -0
  17. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/igamma_cuda_dispatch.h +26 -0
  18. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/is_neg_ops.h +28 -0
  19. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/isclose_compositeimplicitautograd_dispatch.h +23 -0
  20. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/lcm_cuda_dispatch.h +26 -0
  21. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/linear_backward.h +39 -0
  22. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/log_sigmoid_backward_cpu_dispatch.h +25 -0
  23. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/logit_meta_dispatch.h +23 -0
  24. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/masked_scatter_backward_native.h +21 -0
  25. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/permute_copy.h +39 -0
  26. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/quantize_per_tensor_dynamic_cpu_dispatch.h +23 -0
  27. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/rshift_meta_dispatch.h +24 -0
  28. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/scatter_compositeimplicitautograd_dispatch.h +24 -0
  29. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/selu_native.h +22 -0
  30. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sigmoid_backward_cpu_dispatch.h +25 -0
  31. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_csc_tensor_compositeimplicitautograd_dispatch.h +26 -0
  32. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_bessel_y0_meta_dispatch.h +25 -0
  33. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_u_compositeexplicitautograd_dispatch.h +28 -0
  34. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_erfc_ops.h +39 -0
  35. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_linear1d_backward_meta_dispatch.h +28 -0
  36. vllm/lib/python3.10/site-packages/anyio/__init__.py +76 -0
  37. vllm/lib/python3.10/site-packages/anyio/__pycache__/__init__.cpython-310.pyc +0 -0
  38. vllm/lib/python3.10/site-packages/anyio/__pycache__/from_thread.cpython-310.pyc +0 -0
  39. vllm/lib/python3.10/site-packages/anyio/__pycache__/lowlevel.cpython-310.pyc +0 -0
  40. vllm/lib/python3.10/site-packages/anyio/__pycache__/pytest_plugin.cpython-310.pyc +0 -0
  41. vllm/lib/python3.10/site-packages/anyio/__pycache__/to_process.cpython-310.pyc +0 -0
  42. vllm/lib/python3.10/site-packages/anyio/__pycache__/to_thread.cpython-310.pyc +0 -0
  43. vllm/lib/python3.10/site-packages/anyio/_backends/__init__.py +0 -0
  44. vllm/lib/python3.10/site-packages/anyio/_backends/__pycache__/__init__.cpython-310.pyc +0 -0
  45. vllm/lib/python3.10/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-310.pyc +0 -0
  46. vllm/lib/python3.10/site-packages/anyio/_backends/__pycache__/_trio.cpython-310.pyc +0 -0
  47. vllm/lib/python3.10/site-packages/anyio/_backends/_asyncio.py +2851 -0
  48. vllm/lib/python3.10/site-packages/anyio/_backends/_trio.py +1334 -0
  49. vllm/lib/python3.10/site-packages/anyio/_core/__init__.py +0 -0
  50. vllm/lib/python3.10/site-packages/anyio/_core/__pycache__/_asyncio_selector_thread.cpython-310.pyc +0 -0
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_cholesky_solve_helper_native.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor & _cholesky_solve_helper_out(const at::Tensor & self, const at::Tensor & A, bool upper, at::Tensor & out);
20
+ TORCH_API at::Tensor _cholesky_solve_helper_cpu(const at::Tensor & self, const at::Tensor & A, bool upper);
21
+ TORCH_API at::Tensor _cholesky_solve_helper_cuda(const at::Tensor & self, const at::Tensor & A, bool upper);
22
+ } // namespace native
23
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_copy.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/_foreach_copy_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_foreach_copy_(Tensor(a!)[] self, Tensor[] src, bool non_blocking=False) -> ()
26
+ inline void _foreach_copy_(at::TensorList self, at::TensorList src, bool non_blocking=false) {
27
+ return at::_ops::_foreach_copy_::call(self, src, non_blocking);
28
+ }
29
+
30
+ // aten::_foreach_copy.out(Tensor[] self, Tensor[] src, bool non_blocking=False, *, Tensor(a!)[] out) -> ()
31
+ inline void _foreach_copy_out(at::TensorList out, at::TensorList self, at::TensorList src, bool non_blocking=false) {
32
+ return at::_ops::_foreach_copy_out::call(self, src, non_blocking, out);
33
+ }
34
+ // aten::_foreach_copy.out(Tensor[] self, Tensor[] src, bool non_blocking=False, *, Tensor(a!)[] out) -> ()
35
+ inline void _foreach_copy_outf(at::TensorList self, at::TensorList src, bool non_blocking, at::TensorList out) {
36
+ return at::_ops::_foreach_copy_out::call(self, src, non_blocking, out);
37
+ }
38
+
39
+ // aten::_foreach_copy(Tensor[] self, Tensor[] src, bool non_blocking=False) -> Tensor[] self_out
40
+ inline ::std::vector<at::Tensor> _foreach_copy(at::TensorList self, at::TensorList src, bool non_blocking=false) {
41
+ return at::_ops::_foreach_copy::call(self, src, non_blocking);
42
+ }
43
+
44
+ }
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_maximum_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API void _foreach_maximum_out(at::TensorList out, at::TensorList self, const at::Scalar & scalar);
21
+ TORCH_API void _foreach_maximum_outf(at::TensorList self, const at::Scalar & scalar, at::TensorList out);
22
+ TORCH_API void _foreach_maximum_out(at::TensorList out, at::TensorList self, at::TensorList other);
23
+ TORCH_API void _foreach_maximum_outf(at::TensorList self, at::TensorList other, at::TensorList out);
24
+ TORCH_API void _foreach_maximum_out(at::TensorList out, at::TensorList self, at::ArrayRef<at::Scalar> scalars);
25
+ TORCH_API void _foreach_maximum_outf(at::TensorList self, at::ArrayRef<at::Scalar> scalars, at::TensorList out);
26
+
27
+ } // namespace compositeexplicitautograd
28
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sign.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/_foreach_sign_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_foreach_sign(Tensor[] self) -> Tensor[]
26
+ inline ::std::vector<at::Tensor> _foreach_sign(at::TensorList self) {
27
+ return at::_ops::_foreach_sign::call(self);
28
+ }
29
+
30
+ // aten::_foreach_sign_(Tensor(a!)[] self) -> ()
31
+ inline void _foreach_sign_(at::TensorList self) {
32
+ return at::_ops::_foreach_sign_::call(self);
33
+ }
34
+
35
+ // aten::_foreach_sign.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
36
+ inline void _foreach_sign_out(at::TensorList out, at::TensorList self) {
37
+ return at::_ops::_foreach_sign_out::call(self, out);
38
+ }
39
+ // aten::_foreach_sign.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
40
+ inline void _foreach_sign_outf(at::TensorList self, at::TensorList out) {
41
+ return at::_ops::_foreach_sign_out::call(self, out);
42
+ }
43
+
44
+ }
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_histogramdd_from_bin_cts_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor & _histogramdd_from_bin_cts_out(const at::Tensor & self, at::IntArrayRef bins, c10::optional<at::ArrayRef<double>> range, const c10::optional<at::Tensor> & weight, bool density, at::Tensor & out);
20
+ TORCH_API at::Tensor _histogramdd(const at::Tensor & self, at::IntArrayRef bins, c10::optional<at::ArrayRef<double>> range=c10::nullopt, const c10::optional<at::Tensor> & weight={}, bool density=false);
21
+ } // namespace native
22
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_local_scalar_dense_cuda_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Scalar _local_scalar_dense(const at::Tensor & self);
21
+
22
+ } // namespace cuda
23
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_remove_batch_dim_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _remove_batch_dim {
18
+ using schema = at::Tensor (const at::Tensor &, int64_t, int64_t, int64_t);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_remove_batch_dim")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_remove_batch_dim(Tensor self, int level, int batch_size, int out_dim) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, int64_t level, int64_t batch_size, int64_t out_dim);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t level, int64_t batch_size, int64_t out_dim);
26
+ };
27
+
28
+ }} // namespace at::_ops
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_softmax_backward_data_meta.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeMetaFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/TensorIterator.h>
13
+ #include <ATen/TensorMeta.h>
14
+ #include <tuple>
15
+ #include <vector>
16
+
17
+ namespace at {
18
+ namespace meta {
19
+
20
+ struct TORCH_API structured__softmax_backward_data : public at::impl::MetaBase {
21
+
22
+
23
+ void meta(const at::Tensor & grad_output, const at::Tensor & output, int64_t dim, at::ScalarType input_dtype);
24
+ };
25
+
26
+ } // namespace native
27
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_trilinear_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor & _trilinear_out(const at::Tensor & i1, const at::Tensor & i2, const at::Tensor & i3, at::IntArrayRef expand1, at::IntArrayRef expand2, at::IntArrayRef expand3, at::IntArrayRef sumdim, int64_t unroll_dim, at::Tensor & out);
20
+ TORCH_API at::Tensor _trilinear(const at::Tensor & i1, const at::Tensor & i2, const at::Tensor & i3, at::IntArrayRef expand1, at::IntArrayRef expand2, at::IntArrayRef expand3, at::IntArrayRef sumdim, int64_t unroll_dim=1);
21
+ } // namespace native
22
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_nearest_exact2d_backward_meta_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor _upsample_nearest_exact2d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt);
21
+ TORCH_API at::Tensor _upsample_nearest_exact2d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt);
22
+ TORCH_API at::Tensor & _upsample_nearest_exact2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt);
23
+ TORCH_API at::Tensor & _upsample_nearest_exact2d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, c10::optional<double> scales_h, c10::optional<double> scales_w, at::Tensor & grad_input);
24
+ TORCH_API at::Tensor & _upsample_nearest_exact2d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt);
25
+ TORCH_API at::Tensor & _upsample_nearest_exact2d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, c10::optional<double> scales_h, c10::optional<double> scales_w, at::Tensor & grad_input);
26
+
27
+ } // namespace meta
28
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/all_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor all(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false);
21
+ TORCH_API at::Tensor & all_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false);
22
+ TORCH_API at::Tensor & all_outf(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, at::Tensor & out);
23
+
24
+ } // namespace compositeexplicitautograd
25
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/arcsinh_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor arcsinh(const at::Tensor & self);
21
+ TORCH_API at::Tensor & arcsinh_out(at::Tensor & out, const at::Tensor & self);
22
+ TORCH_API at::Tensor & arcsinh_outf(const at::Tensor & self, at::Tensor & out);
23
+ TORCH_API at::Tensor & arcsinh_(at::Tensor & self);
24
+
25
+ } // namespace compositeimplicitautograd
26
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/binomial_cuda_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor binomial(const at::Tensor & count, const at::Tensor & prob, c10::optional<at::Generator> generator=c10::nullopt);
21
+
22
+ } // namespace cuda
23
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/cumprod.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/cumprod_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::cumprod(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor
26
+ inline at::Tensor cumprod(const at::Tensor & self, int64_t dim, c10::optional<at::ScalarType> dtype=c10::nullopt) {
27
+ return at::_ops::cumprod::call(self, dim, dtype);
28
+ }
29
+
30
+ // aten::cumprod.out(Tensor self, int dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & cumprod_out(at::Tensor & out, const at::Tensor & self, int64_t dim, c10::optional<at::ScalarType> dtype=c10::nullopt) {
32
+ return at::_ops::cumprod_out::call(self, dim, dtype, out);
33
+ }
34
+ // aten::cumprod.out(Tensor self, int dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & cumprod_outf(const at::Tensor & self, int64_t dim, c10::optional<at::ScalarType> dtype, at::Tensor & out) {
36
+ return at::_ops::cumprod_out::call(self, dim, dtype, out);
37
+ }
38
+
39
+ // aten::cumprod.dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
40
+ inline at::Tensor cumprod(const at::Tensor & self, at::Dimname dim, c10::optional<at::ScalarType> dtype=c10::nullopt) {
41
+ return at::_ops::cumprod_dimname::call(self, dim, dtype);
42
+ }
43
+
44
+ // aten::cumprod.dimname_out(Tensor self, Dimname dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
45
+ inline at::Tensor & cumprod_out(at::Tensor & out, const at::Tensor & self, at::Dimname dim, c10::optional<at::ScalarType> dtype=c10::nullopt) {
46
+ return at::_ops::cumprod_dimname_out::call(self, dim, dtype, out);
47
+ }
48
+ // aten::cumprod.dimname_out(Tensor self, Dimname dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
49
+ inline at::Tensor & cumprod_outf(const at::Tensor & self, at::Dimname dim, c10::optional<at::ScalarType> dtype, at::Tensor & out) {
50
+ return at::_ops::cumprod_dimname_out::call(self, dim, dtype, out);
51
+ }
52
+
53
+ }
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/diagonal_scatter.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/diagonal_scatter_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::diagonal_scatter(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1) -> Tensor
26
+ inline at::Tensor diagonal_scatter(const at::Tensor & self, const at::Tensor & src, int64_t offset=0, int64_t dim1=0, int64_t dim2=1) {
27
+ return at::_ops::diagonal_scatter::call(self, src, offset, dim1, dim2);
28
+ }
29
+
30
+ // aten::diagonal_scatter.out(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1, *, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & diagonal_scatter_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, int64_t offset=0, int64_t dim1=0, int64_t dim2=1) {
32
+ return at::_ops::diagonal_scatter_out::call(self, src, offset, dim1, dim2, out);
33
+ }
34
+ // aten::diagonal_scatter.out(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1, *, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & diagonal_scatter_outf(const at::Tensor & self, const at::Tensor & src, int64_t offset, int64_t dim1, int64_t dim2, at::Tensor & out) {
36
+ return at::_ops::diagonal_scatter_out::call(self, src, offset, dim1, dim2, out);
37
+ }
38
+
39
+ }
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/empty_like_native.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor empty_like(const at::Tensor & self, c10::optional<at::ScalarType> dtype={}, c10::optional<at::Layout> layout={}, c10::optional<at::Device> device={}, c10::optional<bool> pin_memory={}, c10::optional<at::MemoryFormat> memory_format=c10::nullopt);
20
+ TORCH_API at::Tensor & empty_like_out(const at::Tensor & self, c10::optional<at::MemoryFormat> memory_format, at::Tensor & out);
21
+ TORCH_API at::Tensor empty_like_nested(const at::Tensor & self, c10::optional<at::ScalarType> dtype={}, c10::optional<at::Layout> layout={}, c10::optional<at::Device> device={}, c10::optional<bool> pin_memory={}, c10::optional<at::MemoryFormat> memory_format=c10::nullopt);
22
+ TORCH_API at::Tensor empty_like_sparse_coo(const at::Tensor & self, c10::optional<at::ScalarType> dtype={}, c10::optional<at::Layout> layout={}, c10::optional<at::Device> device={}, c10::optional<bool> pin_memory={}, c10::optional<at::MemoryFormat> memory_format=c10::nullopt);
23
+ TORCH_API at::Tensor empty_like_sparse_csr(const at::Tensor & self, c10::optional<at::ScalarType> dtype={}, c10::optional<at::Layout> layout={}, c10::optional<at::Device> device={}, c10::optional<bool> pin_memory={}, c10::optional<at::MemoryFormat> memory_format=c10::nullopt);
24
+ TORCH_API at::Tensor empty_like_quantized(const at::Tensor & self, c10::optional<at::ScalarType> dtype={}, c10::optional<at::Layout> layout={}, c10::optional<at::Device> device={}, c10::optional<bool> pin_memory={}, c10::optional<at::MemoryFormat> memory_format=c10::nullopt);
25
+ } // namespace native
26
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/igamma_cuda_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor igamma(const at::Tensor & self, const at::Tensor & other);
21
+ TORCH_API at::Tensor & igamma_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other);
22
+ TORCH_API at::Tensor & igamma_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
23
+ TORCH_API at::Tensor & igamma_(at::Tensor & self, const at::Tensor & other);
24
+
25
+ } // namespace cuda
26
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/is_neg_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API is_neg {
18
+ using schema = bool (const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::is_neg")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "is_neg(Tensor self) -> bool")
24
+ static bool call(const at::Tensor & self);
25
+ static bool redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
26
+ };
27
+
28
+ }} // namespace at::_ops
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/isclose_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor isclose(const at::Tensor & self, const at::Tensor & other, double rtol=1e-05, double atol=1e-08, bool equal_nan=false);
21
+
22
+ } // namespace compositeimplicitautograd
23
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/lcm_cuda_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor lcm(const at::Tensor & self, const at::Tensor & other);
21
+ TORCH_API at::Tensor & lcm_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other);
22
+ TORCH_API at::Tensor & lcm_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
23
+ TORCH_API at::Tensor & lcm_(at::Tensor & self, const at::Tensor & other);
24
+
25
+ } // namespace cuda
26
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/linear_backward.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/linear_backward_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::linear_backward(Tensor self, Tensor grad_output, Tensor weight, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
26
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor> linear_backward(const at::Tensor & self, const at::Tensor & grad_output, const at::Tensor & weight, ::std::array<bool,3> output_mask) {
27
+ return at::_ops::linear_backward::call(self, grad_output, weight, output_mask);
28
+ }
29
+
30
+ // aten::linear_backward.out(Tensor self, Tensor grad_output, Tensor weight, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
31
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> linear_backward_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & self, const at::Tensor & grad_output, const at::Tensor & weight, ::std::array<bool,3> output_mask) {
32
+ return at::_ops::linear_backward_out::call(self, grad_output, weight, output_mask, out0, out1, out2);
33
+ }
34
+ // aten::linear_backward.out(Tensor self, Tensor grad_output, Tensor weight, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))
35
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> linear_backward_outf(const at::Tensor & self, const at::Tensor & grad_output, const at::Tensor & weight, ::std::array<bool,3> output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2) {
36
+ return at::_ops::linear_backward_out::call(self, grad_output, weight, output_mask, out0, out1, out2);
37
+ }
38
+
39
+ }
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/log_sigmoid_backward_cpu_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor log_sigmoid_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & buffer);
21
+ TORCH_API at::Tensor & log_sigmoid_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & buffer);
22
+ TORCH_API at::Tensor & log_sigmoid_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & buffer, at::Tensor & grad_input);
23
+
24
+ } // namespace cpu
25
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/logit_meta_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor & logit_(at::Tensor & self, c10::optional<double> eps=c10::nullopt);
21
+
22
+ } // namespace meta
23
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/masked_scatter_backward_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor masked_scatter_backward_symint(const at::Tensor & grad_output, const at::Tensor & mask, c10::SymIntArrayRef sizes);
20
+ } // namespace native
21
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/permute_copy.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/permute_copy_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::permute_copy(Tensor self, int[] dims) -> Tensor
26
+ inline at::Tensor permute_copy(const at::Tensor & self, at::IntArrayRef dims) {
27
+ return at::_ops::permute_copy::call(self, dims);
28
+ }
29
+
30
+ // aten::permute_copy.out(Tensor self, int[] dims, *, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & permute_copy_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef dims) {
32
+ return at::_ops::permute_copy_out::call(self, dims, out);
33
+ }
34
+ // aten::permute_copy.out(Tensor self, int[] dims, *, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & permute_copy_outf(const at::Tensor & self, at::IntArrayRef dims, at::Tensor & out) {
36
+ return at::_ops::permute_copy_out::call(self, dims, out);
37
+ }
38
+
39
+ }
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/quantize_per_tensor_dynamic_cpu_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor quantize_per_tensor_dynamic(const at::Tensor & self, at::ScalarType dtype, bool reduce_range);
21
+
22
+ } // namespace cpu
23
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/rshift_meta_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor & __irshift__(at::Tensor & self, const at::Scalar & other);
21
+ TORCH_API at::Tensor & __irshift__(at::Tensor & self, const at::Tensor & other);
22
+
23
+ } // namespace meta
24
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/scatter_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor scatter(const at::Tensor & self, at::Dimname dim, const at::Tensor & index, const at::Tensor & src);
21
+ TORCH_API at::Tensor scatter(const at::Tensor & self, at::Dimname dim, const at::Tensor & index, const at::Scalar & value);
22
+
23
+ } // namespace compositeimplicitautograd
24
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/selu_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor selu(const at::Tensor & self);
20
+ TORCH_API at::Tensor & selu_(at::Tensor & self);
21
+ } // namespace native
22
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sigmoid_backward_cpu_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor sigmoid_backward(const at::Tensor & grad_output, const at::Tensor & output);
21
+ TORCH_API at::Tensor & sigmoid_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & output);
22
+ TORCH_API at::Tensor & sigmoid_backward_outf(const at::Tensor & grad_output, const at::Tensor & output, at::Tensor & grad_input);
23
+
24
+ } // namespace cpu
25
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_csc_tensor_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor sparse_csc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options);
21
+ TORCH_API at::Tensor sparse_csc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
22
+ TORCH_API at::Tensor sparse_csc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::TensorOptions options);
23
+ TORCH_API at::Tensor sparse_csc_tensor(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
24
+
25
+ } // namespace compositeimplicitautograd
26
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_bessel_y0_meta_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor special_bessel_y0(const at::Tensor & self);
21
+ TORCH_API at::Tensor & special_bessel_y0_out(at::Tensor & out, const at::Tensor & self);
22
+ TORCH_API at::Tensor & special_bessel_y0_outf(const at::Tensor & self, at::Tensor & out);
23
+
24
+ } // namespace meta
25
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_u_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor special_chebyshev_polynomial_u(const at::Scalar & x, const at::Tensor & n);
21
+ TORCH_API at::Tensor & special_chebyshev_polynomial_u_out(at::Tensor & out, const at::Scalar & x, const at::Tensor & n);
22
+ TORCH_API at::Tensor & special_chebyshev_polynomial_u_outf(const at::Scalar & x, const at::Tensor & n, at::Tensor & out);
23
+ TORCH_API at::Tensor special_chebyshev_polynomial_u(const at::Tensor & x, const at::Scalar & n);
24
+ TORCH_API at::Tensor & special_chebyshev_polynomial_u_out(at::Tensor & out, const at::Tensor & x, const at::Scalar & n);
25
+ TORCH_API at::Tensor & special_chebyshev_polynomial_u_outf(const at::Tensor & x, const at::Scalar & n, at::Tensor & out);
26
+
27
+ } // namespace compositeexplicitautograd
28
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_erfc_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API special_erfc {
18
+ using schema = at::Tensor (const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_erfc")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_erfc(Tensor self) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
26
+ };
27
+
28
+ struct TORCH_API special_erfc_out {
29
+ using schema = at::Tensor & (const at::Tensor &, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_erfc")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_erfc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & self, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_linear1d_backward_meta_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor upsample_linear1d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional<double> scales=c10::nullopt);
21
+ TORCH_API at::Tensor upsample_linear1d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional<double> scales=c10::nullopt);
22
+ TORCH_API at::Tensor & upsample_linear1d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional<double> scales=c10::nullopt);
23
+ TORCH_API at::Tensor & upsample_linear1d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, c10::optional<double> scales, at::Tensor & grad_input);
24
+ TORCH_API at::Tensor & upsample_linear1d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional<double> scales=c10::nullopt);
25
+ TORCH_API at::Tensor & upsample_linear1d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, c10::optional<double> scales, at::Tensor & grad_input);
26
+
27
+ } // namespace meta
28
+ } // namespace at
vllm/lib/python3.10/site-packages/anyio/__init__.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from ._core._eventloop import current_time as current_time
4
+ from ._core._eventloop import get_all_backends as get_all_backends
5
+ from ._core._eventloop import get_cancelled_exc_class as get_cancelled_exc_class
6
+ from ._core._eventloop import run as run
7
+ from ._core._eventloop import sleep as sleep
8
+ from ._core._eventloop import sleep_forever as sleep_forever
9
+ from ._core._eventloop import sleep_until as sleep_until
10
+ from ._core._exceptions import BrokenResourceError as BrokenResourceError
11
+ from ._core._exceptions import BrokenWorkerProcess as BrokenWorkerProcess
12
+ from ._core._exceptions import BusyResourceError as BusyResourceError
13
+ from ._core._exceptions import ClosedResourceError as ClosedResourceError
14
+ from ._core._exceptions import DelimiterNotFound as DelimiterNotFound
15
+ from ._core._exceptions import EndOfStream as EndOfStream
16
+ from ._core._exceptions import IncompleteRead as IncompleteRead
17
+ from ._core._exceptions import TypedAttributeLookupError as TypedAttributeLookupError
18
+ from ._core._exceptions import WouldBlock as WouldBlock
19
+ from ._core._fileio import AsyncFile as AsyncFile
20
+ from ._core._fileio import Path as Path
21
+ from ._core._fileio import open_file as open_file
22
+ from ._core._fileio import wrap_file as wrap_file
23
+ from ._core._resources import aclose_forcefully as aclose_forcefully
24
+ from ._core._signals import open_signal_receiver as open_signal_receiver
25
+ from ._core._sockets import connect_tcp as connect_tcp
26
+ from ._core._sockets import connect_unix as connect_unix
27
+ from ._core._sockets import create_connected_udp_socket as create_connected_udp_socket
28
+ from ._core._sockets import (
29
+ create_connected_unix_datagram_socket as create_connected_unix_datagram_socket,
30
+ )
31
+ from ._core._sockets import create_tcp_listener as create_tcp_listener
32
+ from ._core._sockets import create_udp_socket as create_udp_socket
33
+ from ._core._sockets import create_unix_datagram_socket as create_unix_datagram_socket
34
+ from ._core._sockets import create_unix_listener as create_unix_listener
35
+ from ._core._sockets import getaddrinfo as getaddrinfo
36
+ from ._core._sockets import getnameinfo as getnameinfo
37
+ from ._core._sockets import wait_readable as wait_readable
38
+ from ._core._sockets import wait_socket_readable as wait_socket_readable
39
+ from ._core._sockets import wait_socket_writable as wait_socket_writable
40
+ from ._core._sockets import wait_writable as wait_writable
41
+ from ._core._streams import create_memory_object_stream as create_memory_object_stream
42
+ from ._core._subprocesses import open_process as open_process
43
+ from ._core._subprocesses import run_process as run_process
44
+ from ._core._synchronization import CapacityLimiter as CapacityLimiter
45
+ from ._core._synchronization import (
46
+ CapacityLimiterStatistics as CapacityLimiterStatistics,
47
+ )
48
+ from ._core._synchronization import Condition as Condition
49
+ from ._core._synchronization import ConditionStatistics as ConditionStatistics
50
+ from ._core._synchronization import Event as Event
51
+ from ._core._synchronization import EventStatistics as EventStatistics
52
+ from ._core._synchronization import Lock as Lock
53
+ from ._core._synchronization import LockStatistics as LockStatistics
54
+ from ._core._synchronization import ResourceGuard as ResourceGuard
55
+ from ._core._synchronization import Semaphore as Semaphore
56
+ from ._core._synchronization import SemaphoreStatistics as SemaphoreStatistics
57
+ from ._core._tasks import TASK_STATUS_IGNORED as TASK_STATUS_IGNORED
58
+ from ._core._tasks import CancelScope as CancelScope
59
+ from ._core._tasks import create_task_group as create_task_group
60
+ from ._core._tasks import current_effective_deadline as current_effective_deadline
61
+ from ._core._tasks import fail_after as fail_after
62
+ from ._core._tasks import move_on_after as move_on_after
63
+ from ._core._testing import TaskInfo as TaskInfo
64
+ from ._core._testing import get_current_task as get_current_task
65
+ from ._core._testing import get_running_tasks as get_running_tasks
66
+ from ._core._testing import wait_all_tasks_blocked as wait_all_tasks_blocked
67
+ from ._core._typedattr import TypedAttributeProvider as TypedAttributeProvider
68
+ from ._core._typedattr import TypedAttributeSet as TypedAttributeSet
69
+ from ._core._typedattr import typed_attribute as typed_attribute
70
+
71
+ # Re-export imports so they look like they live directly in this package
72
+ for __value in list(locals().values()):
73
+ if getattr(__value, "__module__", "").startswith("anyio."):
74
+ __value.__module__ = __name__
75
+
76
+ del __value
vllm/lib/python3.10/site-packages/anyio/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.99 kB). View file
 
vllm/lib/python3.10/site-packages/anyio/__pycache__/from_thread.cpython-310.pyc ADDED
Binary file (17.2 kB). View file
 
vllm/lib/python3.10/site-packages/anyio/__pycache__/lowlevel.cpython-310.pyc ADDED
Binary file (5.15 kB). View file
 
vllm/lib/python3.10/site-packages/anyio/__pycache__/pytest_plugin.cpython-310.pyc ADDED
Binary file (5.92 kB). View file
 
vllm/lib/python3.10/site-packages/anyio/__pycache__/to_process.cpython-310.pyc ADDED
Binary file (6.58 kB). View file
 
vllm/lib/python3.10/site-packages/anyio/__pycache__/to_thread.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
vllm/lib/python3.10/site-packages/anyio/_backends/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/anyio/_backends/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (165 Bytes). View file
 
vllm/lib/python3.10/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-310.pyc ADDED
Binary file (78.2 kB). View file
 
vllm/lib/python3.10/site-packages/anyio/_backends/__pycache__/_trio.cpython-310.pyc ADDED
Binary file (44.2 kB). View file
 
vllm/lib/python3.10/site-packages/anyio/_backends/_asyncio.py ADDED
@@ -0,0 +1,2851 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import array
4
+ import asyncio
5
+ import concurrent.futures
6
+ import math
7
+ import os
8
+ import socket
9
+ import sys
10
+ import threading
11
+ import weakref
12
+ from asyncio import (
13
+ AbstractEventLoop,
14
+ CancelledError,
15
+ all_tasks,
16
+ create_task,
17
+ current_task,
18
+ get_running_loop,
19
+ sleep,
20
+ )
21
+ from asyncio.base_events import _run_until_complete_cb # type: ignore[attr-defined]
22
+ from collections import OrderedDict, deque
23
+ from collections.abc import (
24
+ AsyncGenerator,
25
+ AsyncIterator,
26
+ Awaitable,
27
+ Callable,
28
+ Collection,
29
+ Coroutine,
30
+ Iterable,
31
+ Iterator,
32
+ MutableMapping,
33
+ Sequence,
34
+ )
35
+ from concurrent.futures import Future
36
+ from contextlib import AbstractContextManager, suppress
37
+ from contextvars import Context, copy_context
38
+ from dataclasses import dataclass
39
+ from functools import partial, wraps
40
+ from inspect import (
41
+ CORO_RUNNING,
42
+ CORO_SUSPENDED,
43
+ getcoroutinestate,
44
+ iscoroutine,
45
+ )
46
+ from io import IOBase
47
+ from os import PathLike
48
+ from queue import Queue
49
+ from signal import Signals
50
+ from socket import AddressFamily, SocketKind
51
+ from threading import Thread
52
+ from types import TracebackType
53
+ from typing import (
54
+ IO,
55
+ TYPE_CHECKING,
56
+ Any,
57
+ Optional,
58
+ TypeVar,
59
+ cast,
60
+ )
61
+ from weakref import WeakKeyDictionary
62
+
63
+ import sniffio
64
+
65
+ from .. import (
66
+ CapacityLimiterStatistics,
67
+ EventStatistics,
68
+ LockStatistics,
69
+ TaskInfo,
70
+ abc,
71
+ )
72
+ from .._core._eventloop import claim_worker_thread, threadlocals
73
+ from .._core._exceptions import (
74
+ BrokenResourceError,
75
+ BusyResourceError,
76
+ ClosedResourceError,
77
+ EndOfStream,
78
+ WouldBlock,
79
+ iterate_exceptions,
80
+ )
81
+ from .._core._sockets import convert_ipv6_sockaddr
82
+ from .._core._streams import create_memory_object_stream
83
+ from .._core._synchronization import (
84
+ CapacityLimiter as BaseCapacityLimiter,
85
+ )
86
+ from .._core._synchronization import Event as BaseEvent
87
+ from .._core._synchronization import Lock as BaseLock
88
+ from .._core._synchronization import (
89
+ ResourceGuard,
90
+ SemaphoreStatistics,
91
+ )
92
+ from .._core._synchronization import Semaphore as BaseSemaphore
93
+ from .._core._tasks import CancelScope as BaseCancelScope
94
+ from ..abc import (
95
+ AsyncBackend,
96
+ IPSockAddrType,
97
+ SocketListener,
98
+ UDPPacketType,
99
+ UNIXDatagramPacketType,
100
+ )
101
+ from ..abc._eventloop import StrOrBytesPath
102
+ from ..lowlevel import RunVar
103
+ from ..streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
104
+
105
+ if TYPE_CHECKING:
106
+ from _typeshed import FileDescriptorLike
107
+ else:
108
+ FileDescriptorLike = object
109
+
110
+ if sys.version_info >= (3, 10):
111
+ from typing import ParamSpec
112
+ else:
113
+ from typing_extensions import ParamSpec
114
+
115
+ if sys.version_info >= (3, 11):
116
+ from asyncio import Runner
117
+ from typing import TypeVarTuple, Unpack
118
+ else:
119
+ import contextvars
120
+ import enum
121
+ import signal
122
+ from asyncio import coroutines, events, exceptions, tasks
123
+
124
+ from exceptiongroup import BaseExceptionGroup
125
+ from typing_extensions import TypeVarTuple, Unpack
126
+
127
+ class _State(enum.Enum):
128
+ CREATED = "created"
129
+ INITIALIZED = "initialized"
130
+ CLOSED = "closed"
131
+
132
+ class Runner:
133
+ # Copied from CPython 3.11
134
+ def __init__(
135
+ self,
136
+ *,
137
+ debug: bool | None = None,
138
+ loop_factory: Callable[[], AbstractEventLoop] | None = None,
139
+ ):
140
+ self._state = _State.CREATED
141
+ self._debug = debug
142
+ self._loop_factory = loop_factory
143
+ self._loop: AbstractEventLoop | None = None
144
+ self._context = None
145
+ self._interrupt_count = 0
146
+ self._set_event_loop = False
147
+
148
+ def __enter__(self) -> Runner:
149
+ self._lazy_init()
150
+ return self
151
+
152
+ def __exit__(
153
+ self,
154
+ exc_type: type[BaseException],
155
+ exc_val: BaseException,
156
+ exc_tb: TracebackType,
157
+ ) -> None:
158
+ self.close()
159
+
160
+ def close(self) -> None:
161
+ """Shutdown and close event loop."""
162
+ if self._state is not _State.INITIALIZED:
163
+ return
164
+ try:
165
+ loop = self._loop
166
+ _cancel_all_tasks(loop)
167
+ loop.run_until_complete(loop.shutdown_asyncgens())
168
+ if hasattr(loop, "shutdown_default_executor"):
169
+ loop.run_until_complete(loop.shutdown_default_executor())
170
+ else:
171
+ loop.run_until_complete(_shutdown_default_executor(loop))
172
+ finally:
173
+ if self._set_event_loop:
174
+ events.set_event_loop(None)
175
+ loop.close()
176
+ self._loop = None
177
+ self._state = _State.CLOSED
178
+
179
+ def get_loop(self) -> AbstractEventLoop:
180
+ """Return embedded event loop."""
181
+ self._lazy_init()
182
+ return self._loop
183
+
184
+ def run(self, coro: Coroutine[T_Retval], *, context=None) -> T_Retval:
185
+ """Run a coroutine inside the embedded event loop."""
186
+ if not coroutines.iscoroutine(coro):
187
+ raise ValueError(f"a coroutine was expected, got {coro!r}")
188
+
189
+ if events._get_running_loop() is not None:
190
+ # fail fast with short traceback
191
+ raise RuntimeError(
192
+ "Runner.run() cannot be called from a running event loop"
193
+ )
194
+
195
+ self._lazy_init()
196
+
197
+ if context is None:
198
+ context = self._context
199
+ task = context.run(self._loop.create_task, coro)
200
+
201
+ if (
202
+ threading.current_thread() is threading.main_thread()
203
+ and signal.getsignal(signal.SIGINT) is signal.default_int_handler
204
+ ):
205
+ sigint_handler = partial(self._on_sigint, main_task=task)
206
+ try:
207
+ signal.signal(signal.SIGINT, sigint_handler)
208
+ except ValueError:
209
+ # `signal.signal` may throw if `threading.main_thread` does
210
+ # not support signals (e.g. embedded interpreter with signals
211
+ # not registered - see gh-91880)
212
+ sigint_handler = None
213
+ else:
214
+ sigint_handler = None
215
+
216
+ self._interrupt_count = 0
217
+ try:
218
+ return self._loop.run_until_complete(task)
219
+ except exceptions.CancelledError:
220
+ if self._interrupt_count > 0:
221
+ uncancel = getattr(task, "uncancel", None)
222
+ if uncancel is not None and uncancel() == 0:
223
+ raise KeyboardInterrupt()
224
+ raise # CancelledError
225
+ finally:
226
+ if (
227
+ sigint_handler is not None
228
+ and signal.getsignal(signal.SIGINT) is sigint_handler
229
+ ):
230
+ signal.signal(signal.SIGINT, signal.default_int_handler)
231
+
232
+ def _lazy_init(self) -> None:
233
+ if self._state is _State.CLOSED:
234
+ raise RuntimeError("Runner is closed")
235
+ if self._state is _State.INITIALIZED:
236
+ return
237
+ if self._loop_factory is None:
238
+ self._loop = events.new_event_loop()
239
+ if not self._set_event_loop:
240
+ # Call set_event_loop only once to avoid calling
241
+ # attach_loop multiple times on child watchers
242
+ events.set_event_loop(self._loop)
243
+ self._set_event_loop = True
244
+ else:
245
+ self._loop = self._loop_factory()
246
+ if self._debug is not None:
247
+ self._loop.set_debug(self._debug)
248
+ self._context = contextvars.copy_context()
249
+ self._state = _State.INITIALIZED
250
+
251
+ def _on_sigint(self, signum, frame, main_task: asyncio.Task) -> None:
252
+ self._interrupt_count += 1
253
+ if self._interrupt_count == 1 and not main_task.done():
254
+ main_task.cancel()
255
+ # wakeup loop if it is blocked by select() with long timeout
256
+ self._loop.call_soon_threadsafe(lambda: None)
257
+ return
258
+ raise KeyboardInterrupt()
259
+
260
+ def _cancel_all_tasks(loop: AbstractEventLoop) -> None:
261
+ to_cancel = tasks.all_tasks(loop)
262
+ if not to_cancel:
263
+ return
264
+
265
+ for task in to_cancel:
266
+ task.cancel()
267
+
268
+ loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True))
269
+
270
+ for task in to_cancel:
271
+ if task.cancelled():
272
+ continue
273
+ if task.exception() is not None:
274
+ loop.call_exception_handler(
275
+ {
276
+ "message": "unhandled exception during asyncio.run() shutdown",
277
+ "exception": task.exception(),
278
+ "task": task,
279
+ }
280
+ )
281
+
282
+ async def _shutdown_default_executor(loop: AbstractEventLoop) -> None:
283
+ """Schedule the shutdown of the default executor."""
284
+
285
+ def _do_shutdown(future: asyncio.futures.Future) -> None:
286
+ try:
287
+ loop._default_executor.shutdown(wait=True) # type: ignore[attr-defined]
288
+ loop.call_soon_threadsafe(future.set_result, None)
289
+ except Exception as ex:
290
+ loop.call_soon_threadsafe(future.set_exception, ex)
291
+
292
+ loop._executor_shutdown_called = True
293
+ if loop._default_executor is None:
294
+ return
295
+ future = loop.create_future()
296
+ thread = threading.Thread(target=_do_shutdown, args=(future,))
297
+ thread.start()
298
+ try:
299
+ await future
300
+ finally:
301
+ thread.join()
302
+
303
+
304
+ T_Retval = TypeVar("T_Retval")
305
+ T_contra = TypeVar("T_contra", contravariant=True)
306
+ PosArgsT = TypeVarTuple("PosArgsT")
307
+ P = ParamSpec("P")
308
+
309
+ _root_task: RunVar[asyncio.Task | None] = RunVar("_root_task")
310
+
311
+
312
+ def find_root_task() -> asyncio.Task:
313
+ root_task = _root_task.get(None)
314
+ if root_task is not None and not root_task.done():
315
+ return root_task
316
+
317
+ # Look for a task that has been started via run_until_complete()
318
+ for task in all_tasks():
319
+ if task._callbacks and not task.done():
320
+ callbacks = [cb for cb, context in task._callbacks]
321
+ for cb in callbacks:
322
+ if (
323
+ cb is _run_until_complete_cb
324
+ or getattr(cb, "__module__", None) == "uvloop.loop"
325
+ ):
326
+ _root_task.set(task)
327
+ return task
328
+
329
+ # Look up the topmost task in the AnyIO task tree, if possible
330
+ task = cast(asyncio.Task, current_task())
331
+ state = _task_states.get(task)
332
+ if state:
333
+ cancel_scope = state.cancel_scope
334
+ while cancel_scope and cancel_scope._parent_scope is not None:
335
+ cancel_scope = cancel_scope._parent_scope
336
+
337
+ if cancel_scope is not None:
338
+ return cast(asyncio.Task, cancel_scope._host_task)
339
+
340
+ return task
341
+
342
+
343
+ def get_callable_name(func: Callable) -> str:
344
+ module = getattr(func, "__module__", None)
345
+ qualname = getattr(func, "__qualname__", None)
346
+ return ".".join([x for x in (module, qualname) if x])
347
+
348
+
349
+ #
350
+ # Event loop
351
+ #
352
+
353
+ _run_vars: WeakKeyDictionary[asyncio.AbstractEventLoop, Any] = WeakKeyDictionary()
354
+
355
+
356
+ def _task_started(task: asyncio.Task) -> bool:
357
+ """Return ``True`` if the task has been started and has not finished."""
358
+ # The task coro should never be None here, as we never add finished tasks to the
359
+ # task list
360
+ coro = task.get_coro()
361
+ assert coro is not None
362
+ try:
363
+ return getcoroutinestate(coro) in (CORO_RUNNING, CORO_SUSPENDED)
364
+ except AttributeError:
365
+ # task coro is async_genenerator_asend https://bugs.python.org/issue37771
366
+ raise Exception(f"Cannot determine if task {task} has started or not") from None
367
+
368
+
369
+ #
370
+ # Timeouts and cancellation
371
+ #
372
+
373
+
374
+ def is_anyio_cancellation(exc: CancelledError) -> bool:
375
+ # Sometimes third party frameworks catch a CancelledError and raise a new one, so as
376
+ # a workaround we have to look at the previous ones in __context__ too for a
377
+ # matching cancel message
378
+ while True:
379
+ if (
380
+ exc.args
381
+ and isinstance(exc.args[0], str)
382
+ and exc.args[0].startswith("Cancelled by cancel scope ")
383
+ ):
384
+ return True
385
+
386
+ if isinstance(exc.__context__, CancelledError):
387
+ exc = exc.__context__
388
+ continue
389
+
390
+ return False
391
+
392
+
393
+ class CancelScope(BaseCancelScope):
394
+ def __new__(
395
+ cls, *, deadline: float = math.inf, shield: bool = False
396
+ ) -> CancelScope:
397
+ return object.__new__(cls)
398
+
399
+ def __init__(self, deadline: float = math.inf, shield: bool = False):
400
+ self._deadline = deadline
401
+ self._shield = shield
402
+ self._parent_scope: CancelScope | None = None
403
+ self._child_scopes: set[CancelScope] = set()
404
+ self._cancel_called = False
405
+ self._cancelled_caught = False
406
+ self._active = False
407
+ self._timeout_handle: asyncio.TimerHandle | None = None
408
+ self._cancel_handle: asyncio.Handle | None = None
409
+ self._tasks: set[asyncio.Task] = set()
410
+ self._host_task: asyncio.Task | None = None
411
+ if sys.version_info >= (3, 11):
412
+ self._pending_uncancellations: int | None = 0
413
+ else:
414
+ self._pending_uncancellations = None
415
+
416
+ def __enter__(self) -> CancelScope:
417
+ if self._active:
418
+ raise RuntimeError(
419
+ "Each CancelScope may only be used for a single 'with' block"
420
+ )
421
+
422
+ self._host_task = host_task = cast(asyncio.Task, current_task())
423
+ self._tasks.add(host_task)
424
+ try:
425
+ task_state = _task_states[host_task]
426
+ except KeyError:
427
+ task_state = TaskState(None, self)
428
+ _task_states[host_task] = task_state
429
+ else:
430
+ self._parent_scope = task_state.cancel_scope
431
+ task_state.cancel_scope = self
432
+ if self._parent_scope is not None:
433
+ # If using an eager task factory, the parent scope may not even contain
434
+ # the host task
435
+ self._parent_scope._child_scopes.add(self)
436
+ self._parent_scope._tasks.discard(host_task)
437
+
438
+ self._timeout()
439
+ self._active = True
440
+
441
+ # Start cancelling the host task if the scope was cancelled before entering
442
+ if self._cancel_called:
443
+ self._deliver_cancellation(self)
444
+
445
+ return self
446
+
447
+ def __exit__(
448
+ self,
449
+ exc_type: type[BaseException] | None,
450
+ exc_val: BaseException | None,
451
+ exc_tb: TracebackType | None,
452
+ ) -> bool | None:
453
+ del exc_tb
454
+
455
+ if not self._active:
456
+ raise RuntimeError("This cancel scope is not active")
457
+ if current_task() is not self._host_task:
458
+ raise RuntimeError(
459
+ "Attempted to exit cancel scope in a different task than it was "
460
+ "entered in"
461
+ )
462
+
463
+ assert self._host_task is not None
464
+ host_task_state = _task_states.get(self._host_task)
465
+ if host_task_state is None or host_task_state.cancel_scope is not self:
466
+ raise RuntimeError(
467
+ "Attempted to exit a cancel scope that isn't the current tasks's "
468
+ "current cancel scope"
469
+ )
470
+
471
+ try:
472
+ self._active = False
473
+ if self._timeout_handle:
474
+ self._timeout_handle.cancel()
475
+ self._timeout_handle = None
476
+
477
+ self._tasks.remove(self._host_task)
478
+ if self._parent_scope is not None:
479
+ self._parent_scope._child_scopes.remove(self)
480
+ self._parent_scope._tasks.add(self._host_task)
481
+
482
+ host_task_state.cancel_scope = self._parent_scope
483
+
484
+ # Restart the cancellation effort in the closest visible, cancelled parent
485
+ # scope if necessary
486
+ self._restart_cancellation_in_parent()
487
+
488
+ # We only swallow the exception iff it was an AnyIO CancelledError, either
489
+ # directly as exc_val or inside an exception group and there are no cancelled
490
+ # parent cancel scopes visible to us here
491
+ if self._cancel_called and not self._parent_cancellation_is_visible_to_us:
492
+ # For each level-cancel() call made on the host task, call uncancel()
493
+ while self._pending_uncancellations:
494
+ self._host_task.uncancel()
495
+ self._pending_uncancellations -= 1
496
+
497
+ # Update cancelled_caught and check for exceptions we must not swallow
498
+ cannot_swallow_exc_val = False
499
+ if exc_val is not None:
500
+ for exc in iterate_exceptions(exc_val):
501
+ if isinstance(exc, CancelledError) and is_anyio_cancellation(
502
+ exc
503
+ ):
504
+ self._cancelled_caught = True
505
+ else:
506
+ cannot_swallow_exc_val = True
507
+
508
+ return self._cancelled_caught and not cannot_swallow_exc_val
509
+ else:
510
+ if self._pending_uncancellations:
511
+ assert self._parent_scope is not None
512
+ assert self._parent_scope._pending_uncancellations is not None
513
+ self._parent_scope._pending_uncancellations += (
514
+ self._pending_uncancellations
515
+ )
516
+ self._pending_uncancellations = 0
517
+
518
+ return False
519
+ finally:
520
+ self._host_task = None
521
+ del exc_val
522
+
523
+ @property
524
+ def _effectively_cancelled(self) -> bool:
525
+ cancel_scope: CancelScope | None = self
526
+ while cancel_scope is not None:
527
+ if cancel_scope._cancel_called:
528
+ return True
529
+
530
+ if cancel_scope.shield:
531
+ return False
532
+
533
+ cancel_scope = cancel_scope._parent_scope
534
+
535
+ return False
536
+
537
+ @property
538
+ def _parent_cancellation_is_visible_to_us(self) -> bool:
539
+ return (
540
+ self._parent_scope is not None
541
+ and not self.shield
542
+ and self._parent_scope._effectively_cancelled
543
+ )
544
+
545
+ def _timeout(self) -> None:
546
+ if self._deadline != math.inf:
547
+ loop = get_running_loop()
548
+ if loop.time() >= self._deadline:
549
+ self.cancel()
550
+ else:
551
+ self._timeout_handle = loop.call_at(self._deadline, self._timeout)
552
+
553
+ def _deliver_cancellation(self, origin: CancelScope) -> bool:
554
+ """
555
+ Deliver cancellation to directly contained tasks and nested cancel scopes.
556
+
557
+ Schedule another run at the end if we still have tasks eligible for
558
+ cancellation.
559
+
560
+ :param origin: the cancel scope that originated the cancellation
561
+ :return: ``True`` if the delivery needs to be retried on the next cycle
562
+
563
+ """
564
+ should_retry = False
565
+ current = current_task()
566
+ for task in self._tasks:
567
+ should_retry = True
568
+ if task._must_cancel: # type: ignore[attr-defined]
569
+ continue
570
+
571
+ # The task is eligible for cancellation if it has started
572
+ if task is not current and (task is self._host_task or _task_started(task)):
573
+ waiter = task._fut_waiter # type: ignore[attr-defined]
574
+ if not isinstance(waiter, asyncio.Future) or not waiter.done():
575
+ task.cancel(f"Cancelled by cancel scope {id(origin):x}")
576
+ if (
577
+ task is origin._host_task
578
+ and origin._pending_uncancellations is not None
579
+ ):
580
+ origin._pending_uncancellations += 1
581
+
582
+ # Deliver cancellation to child scopes that aren't shielded or running their own
583
+ # cancellation callbacks
584
+ for scope in self._child_scopes:
585
+ if not scope._shield and not scope.cancel_called:
586
+ should_retry = scope._deliver_cancellation(origin) or should_retry
587
+
588
+ # Schedule another callback if there are still tasks left
589
+ if origin is self:
590
+ if should_retry:
591
+ self._cancel_handle = get_running_loop().call_soon(
592
+ self._deliver_cancellation, origin
593
+ )
594
+ else:
595
+ self._cancel_handle = None
596
+
597
+ return should_retry
598
+
599
+ def _restart_cancellation_in_parent(self) -> None:
600
+ """
601
+ Restart the cancellation effort in the closest directly cancelled parent scope.
602
+
603
+ """
604
+ scope = self._parent_scope
605
+ while scope is not None:
606
+ if scope._cancel_called:
607
+ if scope._cancel_handle is None:
608
+ scope._deliver_cancellation(scope)
609
+
610
+ break
611
+
612
+ # No point in looking beyond any shielded scope
613
+ if scope._shield:
614
+ break
615
+
616
+ scope = scope._parent_scope
617
+
618
+ def cancel(self) -> None:
619
+ if not self._cancel_called:
620
+ if self._timeout_handle:
621
+ self._timeout_handle.cancel()
622
+ self._timeout_handle = None
623
+
624
+ self._cancel_called = True
625
+ if self._host_task is not None:
626
+ self._deliver_cancellation(self)
627
+
628
+ @property
629
+ def deadline(self) -> float:
630
+ return self._deadline
631
+
632
+ @deadline.setter
633
+ def deadline(self, value: float) -> None:
634
+ self._deadline = float(value)
635
+ if self._timeout_handle is not None:
636
+ self._timeout_handle.cancel()
637
+ self._timeout_handle = None
638
+
639
+ if self._active and not self._cancel_called:
640
+ self._timeout()
641
+
642
+ @property
643
+ def cancel_called(self) -> bool:
644
+ return self._cancel_called
645
+
646
+ @property
647
+ def cancelled_caught(self) -> bool:
648
+ return self._cancelled_caught
649
+
650
+ @property
651
+ def shield(self) -> bool:
652
+ return self._shield
653
+
654
+ @shield.setter
655
+ def shield(self, value: bool) -> None:
656
+ if self._shield != value:
657
+ self._shield = value
658
+ if not value:
659
+ self._restart_cancellation_in_parent()
660
+
661
+
662
+ #
663
+ # Task states
664
+ #
665
+
666
+
667
+ class TaskState:
668
+ """
669
+ Encapsulates auxiliary task information that cannot be added to the Task instance
670
+ itself because there are no guarantees about its implementation.
671
+ """
672
+
673
+ __slots__ = "parent_id", "cancel_scope", "__weakref__"
674
+
675
+ def __init__(self, parent_id: int | None, cancel_scope: CancelScope | None):
676
+ self.parent_id = parent_id
677
+ self.cancel_scope = cancel_scope
678
+
679
+
680
+ class TaskStateStore(MutableMapping["Awaitable[Any] | asyncio.Task", TaskState]):
681
+ def __init__(self) -> None:
682
+ self._task_states = WeakKeyDictionary[asyncio.Task, TaskState]()
683
+ self._preliminary_task_states: dict[Awaitable[Any], TaskState] = {}
684
+
685
+ def __getitem__(self, key: Awaitable[Any] | asyncio.Task, /) -> TaskState:
686
+ assert isinstance(key, asyncio.Task)
687
+ try:
688
+ return self._task_states[key]
689
+ except KeyError:
690
+ if coro := key.get_coro():
691
+ if state := self._preliminary_task_states.get(coro):
692
+ return state
693
+
694
+ raise KeyError(key)
695
+
696
+ def __setitem__(
697
+ self, key: asyncio.Task | Awaitable[Any], value: TaskState, /
698
+ ) -> None:
699
+ if isinstance(key, asyncio.Task):
700
+ self._task_states[key] = value
701
+ else:
702
+ self._preliminary_task_states[key] = value
703
+
704
+ def __delitem__(self, key: asyncio.Task | Awaitable[Any], /) -> None:
705
+ if isinstance(key, asyncio.Task):
706
+ del self._task_states[key]
707
+ else:
708
+ del self._preliminary_task_states[key]
709
+
710
+ def __len__(self) -> int:
711
+ return len(self._task_states) + len(self._preliminary_task_states)
712
+
713
+ def __iter__(self) -> Iterator[Awaitable[Any] | asyncio.Task]:
714
+ yield from self._task_states
715
+ yield from self._preliminary_task_states
716
+
717
+
718
+ _task_states = TaskStateStore()
719
+
720
+
721
+ #
722
+ # Task groups
723
+ #
724
+
725
+
726
+ class _AsyncioTaskStatus(abc.TaskStatus):
727
+ def __init__(self, future: asyncio.Future, parent_id: int):
728
+ self._future = future
729
+ self._parent_id = parent_id
730
+
731
+ def started(self, value: T_contra | None = None) -> None:
732
+ try:
733
+ self._future.set_result(value)
734
+ except asyncio.InvalidStateError:
735
+ if not self._future.cancelled():
736
+ raise RuntimeError(
737
+ "called 'started' twice on the same task status"
738
+ ) from None
739
+
740
+ task = cast(asyncio.Task, current_task())
741
+ _task_states[task].parent_id = self._parent_id
742
+
743
+
744
+ async def _wait(tasks: Iterable[asyncio.Task[object]]) -> None:
745
+ tasks = set(tasks)
746
+ waiter = get_running_loop().create_future()
747
+
748
+ def on_completion(task: asyncio.Task[object]) -> None:
749
+ tasks.discard(task)
750
+ if not tasks and not waiter.done():
751
+ waiter.set_result(None)
752
+
753
+ for task in tasks:
754
+ task.add_done_callback(on_completion)
755
+ del task
756
+
757
+ try:
758
+ await waiter
759
+ finally:
760
+ while tasks:
761
+ tasks.pop().remove_done_callback(on_completion)
762
+
763
+
764
+ class TaskGroup(abc.TaskGroup):
765
+ def __init__(self) -> None:
766
+ self.cancel_scope: CancelScope = CancelScope()
767
+ self._active = False
768
+ self._exceptions: list[BaseException] = []
769
+ self._tasks: set[asyncio.Task] = set()
770
+
771
+ async def __aenter__(self) -> TaskGroup:
772
+ self.cancel_scope.__enter__()
773
+ self._active = True
774
+ return self
775
+
776
+ async def __aexit__(
777
+ self,
778
+ exc_type: type[BaseException] | None,
779
+ exc_val: BaseException | None,
780
+ exc_tb: TracebackType | None,
781
+ ) -> bool | None:
782
+ try:
783
+ if exc_val is not None:
784
+ self.cancel_scope.cancel()
785
+ if not isinstance(exc_val, CancelledError):
786
+ self._exceptions.append(exc_val)
787
+
788
+ try:
789
+ if self._tasks:
790
+ with CancelScope() as wait_scope:
791
+ while self._tasks:
792
+ try:
793
+ await _wait(self._tasks)
794
+ except CancelledError as exc:
795
+ # Shield the scope against further cancellation attempts,
796
+ # as they're not productive (#695)
797
+ wait_scope.shield = True
798
+ self.cancel_scope.cancel()
799
+
800
+ # Set exc_val from the cancellation exception if it was
801
+ # previously unset. However, we should not replace a native
802
+ # cancellation exception with one raise by a cancel scope.
803
+ if exc_val is None or (
804
+ isinstance(exc_val, CancelledError)
805
+ and not is_anyio_cancellation(exc)
806
+ ):
807
+ exc_val = exc
808
+ else:
809
+ # If there are no child tasks to wait on, run at least one checkpoint
810
+ # anyway
811
+ await AsyncIOBackend.cancel_shielded_checkpoint()
812
+
813
+ self._active = False
814
+ if self._exceptions:
815
+ raise BaseExceptionGroup(
816
+ "unhandled errors in a TaskGroup", self._exceptions
817
+ )
818
+ elif exc_val:
819
+ raise exc_val
820
+ except BaseException as exc:
821
+ if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__):
822
+ return True
823
+
824
+ raise
825
+
826
+ return self.cancel_scope.__exit__(exc_type, exc_val, exc_tb)
827
+ finally:
828
+ del exc_val, exc_tb, self._exceptions
829
+
830
+ def _spawn(
831
+ self,
832
+ func: Callable[[Unpack[PosArgsT]], Awaitable[Any]],
833
+ args: tuple[Unpack[PosArgsT]],
834
+ name: object,
835
+ task_status_future: asyncio.Future | None = None,
836
+ ) -> asyncio.Task:
837
+ def task_done(_task: asyncio.Task) -> None:
838
+ # task_state = _task_states[_task]
839
+ assert task_state.cancel_scope is not None
840
+ assert _task in task_state.cancel_scope._tasks
841
+ task_state.cancel_scope._tasks.remove(_task)
842
+ self._tasks.remove(task)
843
+ del _task_states[_task]
844
+
845
+ try:
846
+ exc = _task.exception()
847
+ except CancelledError as e:
848
+ while isinstance(e.__context__, CancelledError):
849
+ e = e.__context__
850
+
851
+ exc = e
852
+
853
+ if exc is not None:
854
+ # The future can only be in the cancelled state if the host task was
855
+ # cancelled, so return immediately instead of adding one more
856
+ # CancelledError to the exceptions list
857
+ if task_status_future is not None and task_status_future.cancelled():
858
+ return
859
+
860
+ if task_status_future is None or task_status_future.done():
861
+ if not isinstance(exc, CancelledError):
862
+ self._exceptions.append(exc)
863
+
864
+ if not self.cancel_scope._effectively_cancelled:
865
+ self.cancel_scope.cancel()
866
+ else:
867
+ task_status_future.set_exception(exc)
868
+ elif task_status_future is not None and not task_status_future.done():
869
+ task_status_future.set_exception(
870
+ RuntimeError("Child exited without calling task_status.started()")
871
+ )
872
+
873
+ if not self._active:
874
+ raise RuntimeError(
875
+ "This task group is not active; no new tasks can be started."
876
+ )
877
+
878
+ kwargs = {}
879
+ if task_status_future:
880
+ parent_id = id(current_task())
881
+ kwargs["task_status"] = _AsyncioTaskStatus(
882
+ task_status_future, id(self.cancel_scope._host_task)
883
+ )
884
+ else:
885
+ parent_id = id(self.cancel_scope._host_task)
886
+
887
+ coro = func(*args, **kwargs)
888
+ if not iscoroutine(coro):
889
+ prefix = f"{func.__module__}." if hasattr(func, "__module__") else ""
890
+ raise TypeError(
891
+ f"Expected {prefix}{func.__qualname__}() to return a coroutine, but "
892
+ f"the return value ({coro!r}) is not a coroutine object"
893
+ )
894
+
895
+ # Make the spawned task inherit the task group's cancel scope
896
+ _task_states[coro] = task_state = TaskState(
897
+ parent_id=parent_id, cancel_scope=self.cancel_scope
898
+ )
899
+ name = get_callable_name(func) if name is None else str(name)
900
+ try:
901
+ task = create_task(coro, name=name)
902
+ finally:
903
+ del _task_states[coro]
904
+
905
+ _task_states[task] = task_state
906
+ self.cancel_scope._tasks.add(task)
907
+ self._tasks.add(task)
908
+
909
+ if task.done():
910
+ # This can happen with eager task factories
911
+ task_done(task)
912
+ else:
913
+ task.add_done_callback(task_done)
914
+
915
+ return task
916
+
917
+ def start_soon(
918
+ self,
919
+ func: Callable[[Unpack[PosArgsT]], Awaitable[Any]],
920
+ *args: Unpack[PosArgsT],
921
+ name: object = None,
922
+ ) -> None:
923
+ self._spawn(func, args, name)
924
+
925
+ async def start(
926
+ self, func: Callable[..., Awaitable[Any]], *args: object, name: object = None
927
+ ) -> Any:
928
+ future: asyncio.Future = asyncio.Future()
929
+ task = self._spawn(func, args, name, future)
930
+
931
+ # If the task raises an exception after sending a start value without a switch
932
+ # point between, the task group is cancelled and this method never proceeds to
933
+ # process the completed future. That's why we have to have a shielded cancel
934
+ # scope here.
935
+ try:
936
+ return await future
937
+ except CancelledError:
938
+ # Cancel the task and wait for it to exit before returning
939
+ task.cancel()
940
+ with CancelScope(shield=True), suppress(CancelledError):
941
+ await task
942
+
943
+ raise
944
+
945
+
946
+ #
947
+ # Threads
948
+ #
949
+
950
+ _Retval_Queue_Type = tuple[Optional[T_Retval], Optional[BaseException]]
951
+
952
+
953
+ class WorkerThread(Thread):
954
+ MAX_IDLE_TIME = 10 # seconds
955
+
956
+ def __init__(
957
+ self,
958
+ root_task: asyncio.Task,
959
+ workers: set[WorkerThread],
960
+ idle_workers: deque[WorkerThread],
961
+ ):
962
+ super().__init__(name="AnyIO worker thread")
963
+ self.root_task = root_task
964
+ self.workers = workers
965
+ self.idle_workers = idle_workers
966
+ self.loop = root_task._loop
967
+ self.queue: Queue[
968
+ tuple[Context, Callable, tuple, asyncio.Future, CancelScope] | None
969
+ ] = Queue(2)
970
+ self.idle_since = AsyncIOBackend.current_time()
971
+ self.stopping = False
972
+
973
+ def _report_result(
974
+ self, future: asyncio.Future, result: Any, exc: BaseException | None
975
+ ) -> None:
976
+ self.idle_since = AsyncIOBackend.current_time()
977
+ if not self.stopping:
978
+ self.idle_workers.append(self)
979
+
980
+ if not future.cancelled():
981
+ if exc is not None:
982
+ if isinstance(exc, StopIteration):
983
+ new_exc = RuntimeError("coroutine raised StopIteration")
984
+ new_exc.__cause__ = exc
985
+ exc = new_exc
986
+
987
+ future.set_exception(exc)
988
+ else:
989
+ future.set_result(result)
990
+
991
+ def run(self) -> None:
992
+ with claim_worker_thread(AsyncIOBackend, self.loop):
993
+ while True:
994
+ item = self.queue.get()
995
+ if item is None:
996
+ # Shutdown command received
997
+ return
998
+
999
+ context, func, args, future, cancel_scope = item
1000
+ if not future.cancelled():
1001
+ result = None
1002
+ exception: BaseException | None = None
1003
+ threadlocals.current_cancel_scope = cancel_scope
1004
+ try:
1005
+ result = context.run(func, *args)
1006
+ except BaseException as exc:
1007
+ exception = exc
1008
+ finally:
1009
+ del threadlocals.current_cancel_scope
1010
+
1011
+ if not self.loop.is_closed():
1012
+ self.loop.call_soon_threadsafe(
1013
+ self._report_result, future, result, exception
1014
+ )
1015
+
1016
+ self.queue.task_done()
1017
+
1018
+ def stop(self, f: asyncio.Task | None = None) -> None:
1019
+ self.stopping = True
1020
+ self.queue.put_nowait(None)
1021
+ self.workers.discard(self)
1022
+ try:
1023
+ self.idle_workers.remove(self)
1024
+ except ValueError:
1025
+ pass
1026
+
1027
+
1028
+ _threadpool_idle_workers: RunVar[deque[WorkerThread]] = RunVar(
1029
+ "_threadpool_idle_workers"
1030
+ )
1031
+ _threadpool_workers: RunVar[set[WorkerThread]] = RunVar("_threadpool_workers")
1032
+
1033
+
1034
+ class BlockingPortal(abc.BlockingPortal):
1035
+ def __new__(cls) -> BlockingPortal:
1036
+ return object.__new__(cls)
1037
+
1038
+ def __init__(self) -> None:
1039
+ super().__init__()
1040
+ self._loop = get_running_loop()
1041
+
1042
+ def _spawn_task_from_thread(
1043
+ self,
1044
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval],
1045
+ args: tuple[Unpack[PosArgsT]],
1046
+ kwargs: dict[str, Any],
1047
+ name: object,
1048
+ future: Future[T_Retval],
1049
+ ) -> None:
1050
+ AsyncIOBackend.run_sync_from_thread(
1051
+ partial(self._task_group.start_soon, name=name),
1052
+ (self._call_func, func, args, kwargs, future),
1053
+ self._loop,
1054
+ )
1055
+
1056
+
1057
+ #
1058
+ # Subprocesses
1059
+ #
1060
+
1061
+
1062
+ @dataclass(eq=False)
1063
+ class StreamReaderWrapper(abc.ByteReceiveStream):
1064
+ _stream: asyncio.StreamReader
1065
+
1066
+ async def receive(self, max_bytes: int = 65536) -> bytes:
1067
+ data = await self._stream.read(max_bytes)
1068
+ if data:
1069
+ return data
1070
+ else:
1071
+ raise EndOfStream
1072
+
1073
+ async def aclose(self) -> None:
1074
+ self._stream.set_exception(ClosedResourceError())
1075
+ await AsyncIOBackend.checkpoint()
1076
+
1077
+
1078
+ @dataclass(eq=False)
1079
+ class StreamWriterWrapper(abc.ByteSendStream):
1080
+ _stream: asyncio.StreamWriter
1081
+
1082
+ async def send(self, item: bytes) -> None:
1083
+ self._stream.write(item)
1084
+ await self._stream.drain()
1085
+
1086
+ async def aclose(self) -> None:
1087
+ self._stream.close()
1088
+ await AsyncIOBackend.checkpoint()
1089
+
1090
+
1091
+ @dataclass(eq=False)
1092
+ class Process(abc.Process):
1093
+ _process: asyncio.subprocess.Process
1094
+ _stdin: StreamWriterWrapper | None
1095
+ _stdout: StreamReaderWrapper | None
1096
+ _stderr: StreamReaderWrapper | None
1097
+
1098
+ async def aclose(self) -> None:
1099
+ with CancelScope(shield=True) as scope:
1100
+ if self._stdin:
1101
+ await self._stdin.aclose()
1102
+ if self._stdout:
1103
+ await self._stdout.aclose()
1104
+ if self._stderr:
1105
+ await self._stderr.aclose()
1106
+
1107
+ scope.shield = False
1108
+ try:
1109
+ await self.wait()
1110
+ except BaseException:
1111
+ scope.shield = True
1112
+ self.kill()
1113
+ await self.wait()
1114
+ raise
1115
+
1116
+ async def wait(self) -> int:
1117
+ return await self._process.wait()
1118
+
1119
+ def terminate(self) -> None:
1120
+ self._process.terminate()
1121
+
1122
+ def kill(self) -> None:
1123
+ self._process.kill()
1124
+
1125
+ def send_signal(self, signal: int) -> None:
1126
+ self._process.send_signal(signal)
1127
+
1128
+ @property
1129
+ def pid(self) -> int:
1130
+ return self._process.pid
1131
+
1132
+ @property
1133
+ def returncode(self) -> int | None:
1134
+ return self._process.returncode
1135
+
1136
+ @property
1137
+ def stdin(self) -> abc.ByteSendStream | None:
1138
+ return self._stdin
1139
+
1140
+ @property
1141
+ def stdout(self) -> abc.ByteReceiveStream | None:
1142
+ return self._stdout
1143
+
1144
+ @property
1145
+ def stderr(self) -> abc.ByteReceiveStream | None:
1146
+ return self._stderr
1147
+
1148
+
1149
+ def _forcibly_shutdown_process_pool_on_exit(
1150
+ workers: set[Process], _task: object
1151
+ ) -> None:
1152
+ """
1153
+ Forcibly shuts down worker processes belonging to this event loop."""
1154
+ child_watcher: asyncio.AbstractChildWatcher | None = None
1155
+ if sys.version_info < (3, 12):
1156
+ try:
1157
+ child_watcher = asyncio.get_event_loop_policy().get_child_watcher()
1158
+ except NotImplementedError:
1159
+ pass
1160
+
1161
+ # Close as much as possible (w/o async/await) to avoid warnings
1162
+ for process in workers:
1163
+ if process.returncode is None:
1164
+ continue
1165
+
1166
+ process._stdin._stream._transport.close() # type: ignore[union-attr]
1167
+ process._stdout._stream._transport.close() # type: ignore[union-attr]
1168
+ process._stderr._stream._transport.close() # type: ignore[union-attr]
1169
+ process.kill()
1170
+ if child_watcher:
1171
+ child_watcher.remove_child_handler(process.pid)
1172
+
1173
+
1174
+ async def _shutdown_process_pool_on_exit(workers: set[abc.Process]) -> None:
1175
+ """
1176
+ Shuts down worker processes belonging to this event loop.
1177
+
1178
+ NOTE: this only works when the event loop was started using asyncio.run() or
1179
+ anyio.run().
1180
+
1181
+ """
1182
+ process: abc.Process
1183
+ try:
1184
+ await sleep(math.inf)
1185
+ except asyncio.CancelledError:
1186
+ for process in workers:
1187
+ if process.returncode is None:
1188
+ process.kill()
1189
+
1190
+ for process in workers:
1191
+ await process.aclose()
1192
+
1193
+
1194
+ #
1195
+ # Sockets and networking
1196
+ #
1197
+
1198
+
1199
+ class StreamProtocol(asyncio.Protocol):
1200
+ read_queue: deque[bytes]
1201
+ read_event: asyncio.Event
1202
+ write_event: asyncio.Event
1203
+ exception: Exception | None = None
1204
+ is_at_eof: bool = False
1205
+
1206
+ def connection_made(self, transport: asyncio.BaseTransport) -> None:
1207
+ self.read_queue = deque()
1208
+ self.read_event = asyncio.Event()
1209
+ self.write_event = asyncio.Event()
1210
+ self.write_event.set()
1211
+ cast(asyncio.Transport, transport).set_write_buffer_limits(0)
1212
+
1213
+ def connection_lost(self, exc: Exception | None) -> None:
1214
+ if exc:
1215
+ self.exception = BrokenResourceError()
1216
+ self.exception.__cause__ = exc
1217
+
1218
+ self.read_event.set()
1219
+ self.write_event.set()
1220
+
1221
+ def data_received(self, data: bytes) -> None:
1222
+ # ProactorEventloop sometimes sends bytearray instead of bytes
1223
+ self.read_queue.append(bytes(data))
1224
+ self.read_event.set()
1225
+
1226
+ def eof_received(self) -> bool | None:
1227
+ self.is_at_eof = True
1228
+ self.read_event.set()
1229
+ return True
1230
+
1231
+ def pause_writing(self) -> None:
1232
+ self.write_event = asyncio.Event()
1233
+
1234
+ def resume_writing(self) -> None:
1235
+ self.write_event.set()
1236
+
1237
+
1238
+ class DatagramProtocol(asyncio.DatagramProtocol):
1239
+ read_queue: deque[tuple[bytes, IPSockAddrType]]
1240
+ read_event: asyncio.Event
1241
+ write_event: asyncio.Event
1242
+ exception: Exception | None = None
1243
+
1244
+ def connection_made(self, transport: asyncio.BaseTransport) -> None:
1245
+ self.read_queue = deque(maxlen=100) # arbitrary value
1246
+ self.read_event = asyncio.Event()
1247
+ self.write_event = asyncio.Event()
1248
+ self.write_event.set()
1249
+
1250
+ def connection_lost(self, exc: Exception | None) -> None:
1251
+ self.read_event.set()
1252
+ self.write_event.set()
1253
+
1254
+ def datagram_received(self, data: bytes, addr: IPSockAddrType) -> None:
1255
+ addr = convert_ipv6_sockaddr(addr)
1256
+ self.read_queue.append((data, addr))
1257
+ self.read_event.set()
1258
+
1259
+ def error_received(self, exc: Exception) -> None:
1260
+ self.exception = exc
1261
+
1262
+ def pause_writing(self) -> None:
1263
+ self.write_event.clear()
1264
+
1265
+ def resume_writing(self) -> None:
1266
+ self.write_event.set()
1267
+
1268
+
1269
+ class SocketStream(abc.SocketStream):
1270
+ def __init__(self, transport: asyncio.Transport, protocol: StreamProtocol):
1271
+ self._transport = transport
1272
+ self._protocol = protocol
1273
+ self._receive_guard = ResourceGuard("reading from")
1274
+ self._send_guard = ResourceGuard("writing to")
1275
+ self._closed = False
1276
+
1277
+ @property
1278
+ def _raw_socket(self) -> socket.socket:
1279
+ return self._transport.get_extra_info("socket")
1280
+
1281
+ async def receive(self, max_bytes: int = 65536) -> bytes:
1282
+ with self._receive_guard:
1283
+ if (
1284
+ not self._protocol.read_event.is_set()
1285
+ and not self._transport.is_closing()
1286
+ and not self._protocol.is_at_eof
1287
+ ):
1288
+ self._transport.resume_reading()
1289
+ await self._protocol.read_event.wait()
1290
+ self._transport.pause_reading()
1291
+ else:
1292
+ await AsyncIOBackend.checkpoint()
1293
+
1294
+ try:
1295
+ chunk = self._protocol.read_queue.popleft()
1296
+ except IndexError:
1297
+ if self._closed:
1298
+ raise ClosedResourceError from None
1299
+ elif self._protocol.exception:
1300
+ raise self._protocol.exception from None
1301
+ else:
1302
+ raise EndOfStream from None
1303
+
1304
+ if len(chunk) > max_bytes:
1305
+ # Split the oversized chunk
1306
+ chunk, leftover = chunk[:max_bytes], chunk[max_bytes:]
1307
+ self._protocol.read_queue.appendleft(leftover)
1308
+
1309
+ # If the read queue is empty, clear the flag so that the next call will
1310
+ # block until data is available
1311
+ if not self._protocol.read_queue:
1312
+ self._protocol.read_event.clear()
1313
+
1314
+ return chunk
1315
+
1316
+ async def send(self, item: bytes) -> None:
1317
+ with self._send_guard:
1318
+ await AsyncIOBackend.checkpoint()
1319
+
1320
+ if self._closed:
1321
+ raise ClosedResourceError
1322
+ elif self._protocol.exception is not None:
1323
+ raise self._protocol.exception
1324
+
1325
+ try:
1326
+ self._transport.write(item)
1327
+ except RuntimeError as exc:
1328
+ if self._transport.is_closing():
1329
+ raise BrokenResourceError from exc
1330
+ else:
1331
+ raise
1332
+
1333
+ await self._protocol.write_event.wait()
1334
+
1335
+ async def send_eof(self) -> None:
1336
+ try:
1337
+ self._transport.write_eof()
1338
+ except OSError:
1339
+ pass
1340
+
1341
+ async def aclose(self) -> None:
1342
+ if not self._transport.is_closing():
1343
+ self._closed = True
1344
+ try:
1345
+ self._transport.write_eof()
1346
+ except OSError:
1347
+ pass
1348
+
1349
+ self._transport.close()
1350
+ await sleep(0)
1351
+ self._transport.abort()
1352
+
1353
+
1354
+ class _RawSocketMixin:
1355
+ _receive_future: asyncio.Future | None = None
1356
+ _send_future: asyncio.Future | None = None
1357
+ _closing = False
1358
+
1359
+ def __init__(self, raw_socket: socket.socket):
1360
+ self.__raw_socket = raw_socket
1361
+ self._receive_guard = ResourceGuard("reading from")
1362
+ self._send_guard = ResourceGuard("writing to")
1363
+
1364
+ @property
1365
+ def _raw_socket(self) -> socket.socket:
1366
+ return self.__raw_socket
1367
+
1368
+ def _wait_until_readable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future:
1369
+ def callback(f: object) -> None:
1370
+ del self._receive_future
1371
+ loop.remove_reader(self.__raw_socket)
1372
+
1373
+ f = self._receive_future = asyncio.Future()
1374
+ loop.add_reader(self.__raw_socket, f.set_result, None)
1375
+ f.add_done_callback(callback)
1376
+ return f
1377
+
1378
+ def _wait_until_writable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future:
1379
+ def callback(f: object) -> None:
1380
+ del self._send_future
1381
+ loop.remove_writer(self.__raw_socket)
1382
+
1383
+ f = self._send_future = asyncio.Future()
1384
+ loop.add_writer(self.__raw_socket, f.set_result, None)
1385
+ f.add_done_callback(callback)
1386
+ return f
1387
+
1388
+ async def aclose(self) -> None:
1389
+ if not self._closing:
1390
+ self._closing = True
1391
+ if self.__raw_socket.fileno() != -1:
1392
+ self.__raw_socket.close()
1393
+
1394
+ if self._receive_future:
1395
+ self._receive_future.set_result(None)
1396
+ if self._send_future:
1397
+ self._send_future.set_result(None)
1398
+
1399
+
1400
+ class UNIXSocketStream(_RawSocketMixin, abc.UNIXSocketStream):
1401
+ async def send_eof(self) -> None:
1402
+ with self._send_guard:
1403
+ self._raw_socket.shutdown(socket.SHUT_WR)
1404
+
1405
+ async def receive(self, max_bytes: int = 65536) -> bytes:
1406
+ loop = get_running_loop()
1407
+ await AsyncIOBackend.checkpoint()
1408
+ with self._receive_guard:
1409
+ while True:
1410
+ try:
1411
+ data = self._raw_socket.recv(max_bytes)
1412
+ except BlockingIOError:
1413
+ await self._wait_until_readable(loop)
1414
+ except OSError as exc:
1415
+ if self._closing:
1416
+ raise ClosedResourceError from None
1417
+ else:
1418
+ raise BrokenResourceError from exc
1419
+ else:
1420
+ if not data:
1421
+ raise EndOfStream
1422
+
1423
+ return data
1424
+
1425
+ async def send(self, item: bytes) -> None:
1426
+ loop = get_running_loop()
1427
+ await AsyncIOBackend.checkpoint()
1428
+ with self._send_guard:
1429
+ view = memoryview(item)
1430
+ while view:
1431
+ try:
1432
+ bytes_sent = self._raw_socket.send(view)
1433
+ except BlockingIOError:
1434
+ await self._wait_until_writable(loop)
1435
+ except OSError as exc:
1436
+ if self._closing:
1437
+ raise ClosedResourceError from None
1438
+ else:
1439
+ raise BrokenResourceError from exc
1440
+ else:
1441
+ view = view[bytes_sent:]
1442
+
1443
+ async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]:
1444
+ if not isinstance(msglen, int) or msglen < 0:
1445
+ raise ValueError("msglen must be a non-negative integer")
1446
+ if not isinstance(maxfds, int) or maxfds < 1:
1447
+ raise ValueError("maxfds must be a positive integer")
1448
+
1449
+ loop = get_running_loop()
1450
+ fds = array.array("i")
1451
+ await AsyncIOBackend.checkpoint()
1452
+ with self._receive_guard:
1453
+ while True:
1454
+ try:
1455
+ message, ancdata, flags, addr = self._raw_socket.recvmsg(
1456
+ msglen, socket.CMSG_LEN(maxfds * fds.itemsize)
1457
+ )
1458
+ except BlockingIOError:
1459
+ await self._wait_until_readable(loop)
1460
+ except OSError as exc:
1461
+ if self._closing:
1462
+ raise ClosedResourceError from None
1463
+ else:
1464
+ raise BrokenResourceError from exc
1465
+ else:
1466
+ if not message and not ancdata:
1467
+ raise EndOfStream
1468
+
1469
+ break
1470
+
1471
+ for cmsg_level, cmsg_type, cmsg_data in ancdata:
1472
+ if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS:
1473
+ raise RuntimeError(
1474
+ f"Received unexpected ancillary data; message = {message!r}, "
1475
+ f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}"
1476
+ )
1477
+
1478
+ fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
1479
+
1480
+ return message, list(fds)
1481
+
1482
+ async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None:
1483
+ if not message:
1484
+ raise ValueError("message must not be empty")
1485
+ if not fds:
1486
+ raise ValueError("fds must not be empty")
1487
+
1488
+ loop = get_running_loop()
1489
+ filenos: list[int] = []
1490
+ for fd in fds:
1491
+ if isinstance(fd, int):
1492
+ filenos.append(fd)
1493
+ elif isinstance(fd, IOBase):
1494
+ filenos.append(fd.fileno())
1495
+
1496
+ fdarray = array.array("i", filenos)
1497
+ await AsyncIOBackend.checkpoint()
1498
+ with self._send_guard:
1499
+ while True:
1500
+ try:
1501
+ # The ignore can be removed after mypy picks up
1502
+ # https://github.com/python/typeshed/pull/5545
1503
+ self._raw_socket.sendmsg(
1504
+ [message], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fdarray)]
1505
+ )
1506
+ break
1507
+ except BlockingIOError:
1508
+ await self._wait_until_writable(loop)
1509
+ except OSError as exc:
1510
+ if self._closing:
1511
+ raise ClosedResourceError from None
1512
+ else:
1513
+ raise BrokenResourceError from exc
1514
+
1515
+
1516
+ class TCPSocketListener(abc.SocketListener):
1517
+ _accept_scope: CancelScope | None = None
1518
+ _closed = False
1519
+
1520
+ def __init__(self, raw_socket: socket.socket):
1521
+ self.__raw_socket = raw_socket
1522
+ self._loop = cast(asyncio.BaseEventLoop, get_running_loop())
1523
+ self._accept_guard = ResourceGuard("accepting connections from")
1524
+
1525
+ @property
1526
+ def _raw_socket(self) -> socket.socket:
1527
+ return self.__raw_socket
1528
+
1529
+ async def accept(self) -> abc.SocketStream:
1530
+ if self._closed:
1531
+ raise ClosedResourceError
1532
+
1533
+ with self._accept_guard:
1534
+ await AsyncIOBackend.checkpoint()
1535
+ with CancelScope() as self._accept_scope:
1536
+ try:
1537
+ client_sock, _addr = await self._loop.sock_accept(self._raw_socket)
1538
+ except asyncio.CancelledError:
1539
+ # Workaround for https://bugs.python.org/issue41317
1540
+ try:
1541
+ self._loop.remove_reader(self._raw_socket)
1542
+ except (ValueError, NotImplementedError):
1543
+ pass
1544
+
1545
+ if self._closed:
1546
+ raise ClosedResourceError from None
1547
+
1548
+ raise
1549
+ finally:
1550
+ self._accept_scope = None
1551
+
1552
+ client_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
1553
+ transport, protocol = await self._loop.connect_accepted_socket(
1554
+ StreamProtocol, client_sock
1555
+ )
1556
+ return SocketStream(transport, protocol)
1557
+
1558
+ async def aclose(self) -> None:
1559
+ if self._closed:
1560
+ return
1561
+
1562
+ self._closed = True
1563
+ if self._accept_scope:
1564
+ # Workaround for https://bugs.python.org/issue41317
1565
+ try:
1566
+ self._loop.remove_reader(self._raw_socket)
1567
+ except (ValueError, NotImplementedError):
1568
+ pass
1569
+
1570
+ self._accept_scope.cancel()
1571
+ await sleep(0)
1572
+
1573
+ self._raw_socket.close()
1574
+
1575
+
1576
+ class UNIXSocketListener(abc.SocketListener):
1577
+ def __init__(self, raw_socket: socket.socket):
1578
+ self.__raw_socket = raw_socket
1579
+ self._loop = get_running_loop()
1580
+ self._accept_guard = ResourceGuard("accepting connections from")
1581
+ self._closed = False
1582
+
1583
+ async def accept(self) -> abc.SocketStream:
1584
+ await AsyncIOBackend.checkpoint()
1585
+ with self._accept_guard:
1586
+ while True:
1587
+ try:
1588
+ client_sock, _ = self.__raw_socket.accept()
1589
+ client_sock.setblocking(False)
1590
+ return UNIXSocketStream(client_sock)
1591
+ except BlockingIOError:
1592
+ f: asyncio.Future = asyncio.Future()
1593
+ self._loop.add_reader(self.__raw_socket, f.set_result, None)
1594
+ f.add_done_callback(
1595
+ lambda _: self._loop.remove_reader(self.__raw_socket)
1596
+ )
1597
+ await f
1598
+ except OSError as exc:
1599
+ if self._closed:
1600
+ raise ClosedResourceError from None
1601
+ else:
1602
+ raise BrokenResourceError from exc
1603
+
1604
+ async def aclose(self) -> None:
1605
+ self._closed = True
1606
+ self.__raw_socket.close()
1607
+
1608
+ @property
1609
+ def _raw_socket(self) -> socket.socket:
1610
+ return self.__raw_socket
1611
+
1612
+
1613
+ class UDPSocket(abc.UDPSocket):
1614
+ def __init__(
1615
+ self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol
1616
+ ):
1617
+ self._transport = transport
1618
+ self._protocol = protocol
1619
+ self._receive_guard = ResourceGuard("reading from")
1620
+ self._send_guard = ResourceGuard("writing to")
1621
+ self._closed = False
1622
+
1623
+ @property
1624
+ def _raw_socket(self) -> socket.socket:
1625
+ return self._transport.get_extra_info("socket")
1626
+
1627
+ async def aclose(self) -> None:
1628
+ if not self._transport.is_closing():
1629
+ self._closed = True
1630
+ self._transport.close()
1631
+
1632
+ async def receive(self) -> tuple[bytes, IPSockAddrType]:
1633
+ with self._receive_guard:
1634
+ await AsyncIOBackend.checkpoint()
1635
+
1636
+ # If the buffer is empty, ask for more data
1637
+ if not self._protocol.read_queue and not self._transport.is_closing():
1638
+ self._protocol.read_event.clear()
1639
+ await self._protocol.read_event.wait()
1640
+
1641
+ try:
1642
+ return self._protocol.read_queue.popleft()
1643
+ except IndexError:
1644
+ if self._closed:
1645
+ raise ClosedResourceError from None
1646
+ else:
1647
+ raise BrokenResourceError from None
1648
+
1649
+ async def send(self, item: UDPPacketType) -> None:
1650
+ with self._send_guard:
1651
+ await AsyncIOBackend.checkpoint()
1652
+ await self._protocol.write_event.wait()
1653
+ if self._closed:
1654
+ raise ClosedResourceError
1655
+ elif self._transport.is_closing():
1656
+ raise BrokenResourceError
1657
+ else:
1658
+ self._transport.sendto(*item)
1659
+
1660
+
1661
+ class ConnectedUDPSocket(abc.ConnectedUDPSocket):
1662
+ def __init__(
1663
+ self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol
1664
+ ):
1665
+ self._transport = transport
1666
+ self._protocol = protocol
1667
+ self._receive_guard = ResourceGuard("reading from")
1668
+ self._send_guard = ResourceGuard("writing to")
1669
+ self._closed = False
1670
+
1671
+ @property
1672
+ def _raw_socket(self) -> socket.socket:
1673
+ return self._transport.get_extra_info("socket")
1674
+
1675
+ async def aclose(self) -> None:
1676
+ if not self._transport.is_closing():
1677
+ self._closed = True
1678
+ self._transport.close()
1679
+
1680
+ async def receive(self) -> bytes:
1681
+ with self._receive_guard:
1682
+ await AsyncIOBackend.checkpoint()
1683
+
1684
+ # If the buffer is empty, ask for more data
1685
+ if not self._protocol.read_queue and not self._transport.is_closing():
1686
+ self._protocol.read_event.clear()
1687
+ await self._protocol.read_event.wait()
1688
+
1689
+ try:
1690
+ packet = self._protocol.read_queue.popleft()
1691
+ except IndexError:
1692
+ if self._closed:
1693
+ raise ClosedResourceError from None
1694
+ else:
1695
+ raise BrokenResourceError from None
1696
+
1697
+ return packet[0]
1698
+
1699
+ async def send(self, item: bytes) -> None:
1700
+ with self._send_guard:
1701
+ await AsyncIOBackend.checkpoint()
1702
+ await self._protocol.write_event.wait()
1703
+ if self._closed:
1704
+ raise ClosedResourceError
1705
+ elif self._transport.is_closing():
1706
+ raise BrokenResourceError
1707
+ else:
1708
+ self._transport.sendto(item)
1709
+
1710
+
1711
+ class UNIXDatagramSocket(_RawSocketMixin, abc.UNIXDatagramSocket):
1712
+ async def receive(self) -> UNIXDatagramPacketType:
1713
+ loop = get_running_loop()
1714
+ await AsyncIOBackend.checkpoint()
1715
+ with self._receive_guard:
1716
+ while True:
1717
+ try:
1718
+ data = self._raw_socket.recvfrom(65536)
1719
+ except BlockingIOError:
1720
+ await self._wait_until_readable(loop)
1721
+ except OSError as exc:
1722
+ if self._closing:
1723
+ raise ClosedResourceError from None
1724
+ else:
1725
+ raise BrokenResourceError from exc
1726
+ else:
1727
+ return data
1728
+
1729
+ async def send(self, item: UNIXDatagramPacketType) -> None:
1730
+ loop = get_running_loop()
1731
+ await AsyncIOBackend.checkpoint()
1732
+ with self._send_guard:
1733
+ while True:
1734
+ try:
1735
+ self._raw_socket.sendto(*item)
1736
+ except BlockingIOError:
1737
+ await self._wait_until_writable(loop)
1738
+ except OSError as exc:
1739
+ if self._closing:
1740
+ raise ClosedResourceError from None
1741
+ else:
1742
+ raise BrokenResourceError from exc
1743
+ else:
1744
+ return
1745
+
1746
+
1747
+ class ConnectedUNIXDatagramSocket(_RawSocketMixin, abc.ConnectedUNIXDatagramSocket):
1748
+ async def receive(self) -> bytes:
1749
+ loop = get_running_loop()
1750
+ await AsyncIOBackend.checkpoint()
1751
+ with self._receive_guard:
1752
+ while True:
1753
+ try:
1754
+ data = self._raw_socket.recv(65536)
1755
+ except BlockingIOError:
1756
+ await self._wait_until_readable(loop)
1757
+ except OSError as exc:
1758
+ if self._closing:
1759
+ raise ClosedResourceError from None
1760
+ else:
1761
+ raise BrokenResourceError from exc
1762
+ else:
1763
+ return data
1764
+
1765
+ async def send(self, item: bytes) -> None:
1766
+ loop = get_running_loop()
1767
+ await AsyncIOBackend.checkpoint()
1768
+ with self._send_guard:
1769
+ while True:
1770
+ try:
1771
+ self._raw_socket.send(item)
1772
+ except BlockingIOError:
1773
+ await self._wait_until_writable(loop)
1774
+ except OSError as exc:
1775
+ if self._closing:
1776
+ raise ClosedResourceError from None
1777
+ else:
1778
+ raise BrokenResourceError from exc
1779
+ else:
1780
+ return
1781
+
1782
+
1783
+ _read_events: RunVar[dict[int, asyncio.Event]] = RunVar("read_events")
1784
+ _write_events: RunVar[dict[int, asyncio.Event]] = RunVar("write_events")
1785
+
1786
+
1787
+ #
1788
+ # Synchronization
1789
+ #
1790
+
1791
+
1792
+ class Event(BaseEvent):
1793
+ def __new__(cls) -> Event:
1794
+ return object.__new__(cls)
1795
+
1796
+ def __init__(self) -> None:
1797
+ self._event = asyncio.Event()
1798
+
1799
+ def set(self) -> None:
1800
+ self._event.set()
1801
+
1802
+ def is_set(self) -> bool:
1803
+ return self._event.is_set()
1804
+
1805
+ async def wait(self) -> None:
1806
+ if self.is_set():
1807
+ await AsyncIOBackend.checkpoint()
1808
+ else:
1809
+ await self._event.wait()
1810
+
1811
+ def statistics(self) -> EventStatistics:
1812
+ return EventStatistics(len(self._event._waiters))
1813
+
1814
+
1815
+ class Lock(BaseLock):
1816
+ def __new__(cls, *, fast_acquire: bool = False) -> Lock:
1817
+ return object.__new__(cls)
1818
+
1819
+ def __init__(self, *, fast_acquire: bool = False) -> None:
1820
+ self._fast_acquire = fast_acquire
1821
+ self._owner_task: asyncio.Task | None = None
1822
+ self._waiters: deque[tuple[asyncio.Task, asyncio.Future]] = deque()
1823
+
1824
+ async def acquire(self) -> None:
1825
+ task = cast(asyncio.Task, current_task())
1826
+ if self._owner_task is None and not self._waiters:
1827
+ await AsyncIOBackend.checkpoint_if_cancelled()
1828
+ self._owner_task = task
1829
+
1830
+ # Unless on the "fast path", yield control of the event loop so that other
1831
+ # tasks can run too
1832
+ if not self._fast_acquire:
1833
+ try:
1834
+ await AsyncIOBackend.cancel_shielded_checkpoint()
1835
+ except CancelledError:
1836
+ self.release()
1837
+ raise
1838
+
1839
+ return
1840
+
1841
+ if self._owner_task == task:
1842
+ raise RuntimeError("Attempted to acquire an already held Lock")
1843
+
1844
+ fut: asyncio.Future[None] = asyncio.Future()
1845
+ item = task, fut
1846
+ self._waiters.append(item)
1847
+ try:
1848
+ await fut
1849
+ except CancelledError:
1850
+ self._waiters.remove(item)
1851
+ if self._owner_task is task:
1852
+ self.release()
1853
+
1854
+ raise
1855
+
1856
+ self._waiters.remove(item)
1857
+
1858
+ def acquire_nowait(self) -> None:
1859
+ task = cast(asyncio.Task, current_task())
1860
+ if self._owner_task is None and not self._waiters:
1861
+ self._owner_task = task
1862
+ return
1863
+
1864
+ if self._owner_task is task:
1865
+ raise RuntimeError("Attempted to acquire an already held Lock")
1866
+
1867
+ raise WouldBlock
1868
+
1869
+ def locked(self) -> bool:
1870
+ return self._owner_task is not None
1871
+
1872
+ def release(self) -> None:
1873
+ if self._owner_task != current_task():
1874
+ raise RuntimeError("The current task is not holding this lock")
1875
+
1876
+ for task, fut in self._waiters:
1877
+ if not fut.cancelled():
1878
+ self._owner_task = task
1879
+ fut.set_result(None)
1880
+ return
1881
+
1882
+ self._owner_task = None
1883
+
1884
+ def statistics(self) -> LockStatistics:
1885
+ task_info = AsyncIOTaskInfo(self._owner_task) if self._owner_task else None
1886
+ return LockStatistics(self.locked(), task_info, len(self._waiters))
1887
+
1888
+
1889
+ class Semaphore(BaseSemaphore):
1890
+ def __new__(
1891
+ cls,
1892
+ initial_value: int,
1893
+ *,
1894
+ max_value: int | None = None,
1895
+ fast_acquire: bool = False,
1896
+ ) -> Semaphore:
1897
+ return object.__new__(cls)
1898
+
1899
+ def __init__(
1900
+ self,
1901
+ initial_value: int,
1902
+ *,
1903
+ max_value: int | None = None,
1904
+ fast_acquire: bool = False,
1905
+ ):
1906
+ super().__init__(initial_value, max_value=max_value)
1907
+ self._value = initial_value
1908
+ self._max_value = max_value
1909
+ self._fast_acquire = fast_acquire
1910
+ self._waiters: deque[asyncio.Future[None]] = deque()
1911
+
1912
+ async def acquire(self) -> None:
1913
+ if self._value > 0 and not self._waiters:
1914
+ await AsyncIOBackend.checkpoint_if_cancelled()
1915
+ self._value -= 1
1916
+
1917
+ # Unless on the "fast path", yield control of the event loop so that other
1918
+ # tasks can run too
1919
+ if not self._fast_acquire:
1920
+ try:
1921
+ await AsyncIOBackend.cancel_shielded_checkpoint()
1922
+ except CancelledError:
1923
+ self.release()
1924
+ raise
1925
+
1926
+ return
1927
+
1928
+ fut: asyncio.Future[None] = asyncio.Future()
1929
+ self._waiters.append(fut)
1930
+ try:
1931
+ await fut
1932
+ except CancelledError:
1933
+ try:
1934
+ self._waiters.remove(fut)
1935
+ except ValueError:
1936
+ self.release()
1937
+
1938
+ raise
1939
+
1940
+ def acquire_nowait(self) -> None:
1941
+ if self._value == 0:
1942
+ raise WouldBlock
1943
+
1944
+ self._value -= 1
1945
+
1946
+ def release(self) -> None:
1947
+ if self._max_value is not None and self._value == self._max_value:
1948
+ raise ValueError("semaphore released too many times")
1949
+
1950
+ for fut in self._waiters:
1951
+ if not fut.cancelled():
1952
+ fut.set_result(None)
1953
+ self._waiters.remove(fut)
1954
+ return
1955
+
1956
+ self._value += 1
1957
+
1958
+ @property
1959
+ def value(self) -> int:
1960
+ return self._value
1961
+
1962
+ @property
1963
+ def max_value(self) -> int | None:
1964
+ return self._max_value
1965
+
1966
+ def statistics(self) -> SemaphoreStatistics:
1967
+ return SemaphoreStatistics(len(self._waiters))
1968
+
1969
+
1970
+ class CapacityLimiter(BaseCapacityLimiter):
1971
+ _total_tokens: float = 0
1972
+
1973
+ def __new__(cls, total_tokens: float) -> CapacityLimiter:
1974
+ return object.__new__(cls)
1975
+
1976
+ def __init__(self, total_tokens: float):
1977
+ self._borrowers: set[Any] = set()
1978
+ self._wait_queue: OrderedDict[Any, asyncio.Event] = OrderedDict()
1979
+ self.total_tokens = total_tokens
1980
+
1981
+ async def __aenter__(self) -> None:
1982
+ await self.acquire()
1983
+
1984
+ async def __aexit__(
1985
+ self,
1986
+ exc_type: type[BaseException] | None,
1987
+ exc_val: BaseException | None,
1988
+ exc_tb: TracebackType | None,
1989
+ ) -> None:
1990
+ self.release()
1991
+
1992
+ @property
1993
+ def total_tokens(self) -> float:
1994
+ return self._total_tokens
1995
+
1996
+ @total_tokens.setter
1997
+ def total_tokens(self, value: float) -> None:
1998
+ if not isinstance(value, int) and not math.isinf(value):
1999
+ raise TypeError("total_tokens must be an int or math.inf")
2000
+ if value < 1:
2001
+ raise ValueError("total_tokens must be >= 1")
2002
+
2003
+ waiters_to_notify = max(value - self._total_tokens, 0)
2004
+ self._total_tokens = value
2005
+
2006
+ # Notify waiting tasks that they have acquired the limiter
2007
+ while self._wait_queue and waiters_to_notify:
2008
+ event = self._wait_queue.popitem(last=False)[1]
2009
+ event.set()
2010
+ waiters_to_notify -= 1
2011
+
2012
+ @property
2013
+ def borrowed_tokens(self) -> int:
2014
+ return len(self._borrowers)
2015
+
2016
+ @property
2017
+ def available_tokens(self) -> float:
2018
+ return self._total_tokens - len(self._borrowers)
2019
+
2020
+ def acquire_nowait(self) -> None:
2021
+ self.acquire_on_behalf_of_nowait(current_task())
2022
+
2023
+ def acquire_on_behalf_of_nowait(self, borrower: object) -> None:
2024
+ if borrower in self._borrowers:
2025
+ raise RuntimeError(
2026
+ "this borrower is already holding one of this CapacityLimiter's "
2027
+ "tokens"
2028
+ )
2029
+
2030
+ if self._wait_queue or len(self._borrowers) >= self._total_tokens:
2031
+ raise WouldBlock
2032
+
2033
+ self._borrowers.add(borrower)
2034
+
2035
+ async def acquire(self) -> None:
2036
+ return await self.acquire_on_behalf_of(current_task())
2037
+
2038
+ async def acquire_on_behalf_of(self, borrower: object) -> None:
2039
+ await AsyncIOBackend.checkpoint_if_cancelled()
2040
+ try:
2041
+ self.acquire_on_behalf_of_nowait(borrower)
2042
+ except WouldBlock:
2043
+ event = asyncio.Event()
2044
+ self._wait_queue[borrower] = event
2045
+ try:
2046
+ await event.wait()
2047
+ except BaseException:
2048
+ self._wait_queue.pop(borrower, None)
2049
+ raise
2050
+
2051
+ self._borrowers.add(borrower)
2052
+ else:
2053
+ try:
2054
+ await AsyncIOBackend.cancel_shielded_checkpoint()
2055
+ except BaseException:
2056
+ self.release()
2057
+ raise
2058
+
2059
+ def release(self) -> None:
2060
+ self.release_on_behalf_of(current_task())
2061
+
2062
+ def release_on_behalf_of(self, borrower: object) -> None:
2063
+ try:
2064
+ self._borrowers.remove(borrower)
2065
+ except KeyError:
2066
+ raise RuntimeError(
2067
+ "this borrower isn't holding any of this CapacityLimiter's tokens"
2068
+ ) from None
2069
+
2070
+ # Notify the next task in line if this limiter has free capacity now
2071
+ if self._wait_queue and len(self._borrowers) < self._total_tokens:
2072
+ event = self._wait_queue.popitem(last=False)[1]
2073
+ event.set()
2074
+
2075
+ def statistics(self) -> CapacityLimiterStatistics:
2076
+ return CapacityLimiterStatistics(
2077
+ self.borrowed_tokens,
2078
+ self.total_tokens,
2079
+ tuple(self._borrowers),
2080
+ len(self._wait_queue),
2081
+ )
2082
+
2083
+
2084
+ _default_thread_limiter: RunVar[CapacityLimiter] = RunVar("_default_thread_limiter")
2085
+
2086
+
2087
+ #
2088
+ # Operating system signals
2089
+ #
2090
+
2091
+
2092
+ class _SignalReceiver:
2093
+ def __init__(self, signals: tuple[Signals, ...]):
2094
+ self._signals = signals
2095
+ self._loop = get_running_loop()
2096
+ self._signal_queue: deque[Signals] = deque()
2097
+ self._future: asyncio.Future = asyncio.Future()
2098
+ self._handled_signals: set[Signals] = set()
2099
+
2100
+ def _deliver(self, signum: Signals) -> None:
2101
+ self._signal_queue.append(signum)
2102
+ if not self._future.done():
2103
+ self._future.set_result(None)
2104
+
2105
+ def __enter__(self) -> _SignalReceiver:
2106
+ for sig in set(self._signals):
2107
+ self._loop.add_signal_handler(sig, self._deliver, sig)
2108
+ self._handled_signals.add(sig)
2109
+
2110
+ return self
2111
+
2112
+ def __exit__(
2113
+ self,
2114
+ exc_type: type[BaseException] | None,
2115
+ exc_val: BaseException | None,
2116
+ exc_tb: TracebackType | None,
2117
+ ) -> bool | None:
2118
+ for sig in self._handled_signals:
2119
+ self._loop.remove_signal_handler(sig)
2120
+ return None
2121
+
2122
+ def __aiter__(self) -> _SignalReceiver:
2123
+ return self
2124
+
2125
+ async def __anext__(self) -> Signals:
2126
+ await AsyncIOBackend.checkpoint()
2127
+ if not self._signal_queue:
2128
+ self._future = asyncio.Future()
2129
+ await self._future
2130
+
2131
+ return self._signal_queue.popleft()
2132
+
2133
+
2134
+ #
2135
+ # Testing and debugging
2136
+ #
2137
+
2138
+
2139
+ class AsyncIOTaskInfo(TaskInfo):
2140
+ def __init__(self, task: asyncio.Task):
2141
+ task_state = _task_states.get(task)
2142
+ if task_state is None:
2143
+ parent_id = None
2144
+ else:
2145
+ parent_id = task_state.parent_id
2146
+
2147
+ coro = task.get_coro()
2148
+ assert coro is not None, "created TaskInfo from a completed Task"
2149
+ super().__init__(id(task), parent_id, task.get_name(), coro)
2150
+ self._task = weakref.ref(task)
2151
+
2152
+ def has_pending_cancellation(self) -> bool:
2153
+ if not (task := self._task()):
2154
+ # If the task isn't around anymore, it won't have a pending cancellation
2155
+ return False
2156
+
2157
+ if task._must_cancel: # type: ignore[attr-defined]
2158
+ return True
2159
+ elif (
2160
+ isinstance(task._fut_waiter, asyncio.Future) # type: ignore[attr-defined]
2161
+ and task._fut_waiter.cancelled() # type: ignore[attr-defined]
2162
+ ):
2163
+ return True
2164
+
2165
+ if task_state := _task_states.get(task):
2166
+ if cancel_scope := task_state.cancel_scope:
2167
+ return cancel_scope._effectively_cancelled
2168
+
2169
+ return False
2170
+
2171
+
2172
+ class TestRunner(abc.TestRunner):
2173
+ _send_stream: MemoryObjectSendStream[tuple[Awaitable[Any], asyncio.Future[Any]]]
2174
+
2175
+ def __init__(
2176
+ self,
2177
+ *,
2178
+ debug: bool | None = None,
2179
+ use_uvloop: bool = False,
2180
+ loop_factory: Callable[[], AbstractEventLoop] | None = None,
2181
+ ) -> None:
2182
+ if use_uvloop and loop_factory is None:
2183
+ import uvloop
2184
+
2185
+ loop_factory = uvloop.new_event_loop
2186
+
2187
+ self._runner = Runner(debug=debug, loop_factory=loop_factory)
2188
+ self._exceptions: list[BaseException] = []
2189
+ self._runner_task: asyncio.Task | None = None
2190
+
2191
+ def __enter__(self) -> TestRunner:
2192
+ self._runner.__enter__()
2193
+ self.get_loop().set_exception_handler(self._exception_handler)
2194
+ return self
2195
+
2196
+ def __exit__(
2197
+ self,
2198
+ exc_type: type[BaseException] | None,
2199
+ exc_val: BaseException | None,
2200
+ exc_tb: TracebackType | None,
2201
+ ) -> None:
2202
+ self._runner.__exit__(exc_type, exc_val, exc_tb)
2203
+
2204
+ def get_loop(self) -> AbstractEventLoop:
2205
+ return self._runner.get_loop()
2206
+
2207
+ def _exception_handler(
2208
+ self, loop: asyncio.AbstractEventLoop, context: dict[str, Any]
2209
+ ) -> None:
2210
+ if isinstance(context.get("exception"), Exception):
2211
+ self._exceptions.append(context["exception"])
2212
+ else:
2213
+ loop.default_exception_handler(context)
2214
+
2215
+ def _raise_async_exceptions(self) -> None:
2216
+ # Re-raise any exceptions raised in asynchronous callbacks
2217
+ if self._exceptions:
2218
+ exceptions, self._exceptions = self._exceptions, []
2219
+ if len(exceptions) == 1:
2220
+ raise exceptions[0]
2221
+ elif exceptions:
2222
+ raise BaseExceptionGroup(
2223
+ "Multiple exceptions occurred in asynchronous callbacks", exceptions
2224
+ )
2225
+
2226
+ async def _run_tests_and_fixtures(
2227
+ self,
2228
+ receive_stream: MemoryObjectReceiveStream[
2229
+ tuple[Awaitable[T_Retval], asyncio.Future[T_Retval]]
2230
+ ],
2231
+ ) -> None:
2232
+ from _pytest.outcomes import OutcomeException
2233
+
2234
+ with receive_stream, self._send_stream:
2235
+ async for coro, future in receive_stream:
2236
+ try:
2237
+ retval = await coro
2238
+ except CancelledError as exc:
2239
+ if not future.cancelled():
2240
+ future.cancel(*exc.args)
2241
+
2242
+ raise
2243
+ except BaseException as exc:
2244
+ if not future.cancelled():
2245
+ future.set_exception(exc)
2246
+
2247
+ if not isinstance(exc, (Exception, OutcomeException)):
2248
+ raise
2249
+ else:
2250
+ if not future.cancelled():
2251
+ future.set_result(retval)
2252
+
2253
+ async def _call_in_runner_task(
2254
+ self,
2255
+ func: Callable[P, Awaitable[T_Retval]],
2256
+ *args: P.args,
2257
+ **kwargs: P.kwargs,
2258
+ ) -> T_Retval:
2259
+ if not self._runner_task:
2260
+ self._send_stream, receive_stream = create_memory_object_stream[
2261
+ tuple[Awaitable[Any], asyncio.Future]
2262
+ ](1)
2263
+ self._runner_task = self.get_loop().create_task(
2264
+ self._run_tests_and_fixtures(receive_stream)
2265
+ )
2266
+
2267
+ coro = func(*args, **kwargs)
2268
+ future: asyncio.Future[T_Retval] = self.get_loop().create_future()
2269
+ self._send_stream.send_nowait((coro, future))
2270
+ return await future
2271
+
2272
+ def run_asyncgen_fixture(
2273
+ self,
2274
+ fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]],
2275
+ kwargs: dict[str, Any],
2276
+ ) -> Iterable[T_Retval]:
2277
+ asyncgen = fixture_func(**kwargs)
2278
+ fixturevalue: T_Retval = self.get_loop().run_until_complete(
2279
+ self._call_in_runner_task(asyncgen.asend, None)
2280
+ )
2281
+ self._raise_async_exceptions()
2282
+
2283
+ yield fixturevalue
2284
+
2285
+ try:
2286
+ self.get_loop().run_until_complete(
2287
+ self._call_in_runner_task(asyncgen.asend, None)
2288
+ )
2289
+ except StopAsyncIteration:
2290
+ self._raise_async_exceptions()
2291
+ else:
2292
+ self.get_loop().run_until_complete(asyncgen.aclose())
2293
+ raise RuntimeError("Async generator fixture did not stop")
2294
+
2295
+ def run_fixture(
2296
+ self,
2297
+ fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]],
2298
+ kwargs: dict[str, Any],
2299
+ ) -> T_Retval:
2300
+ retval = self.get_loop().run_until_complete(
2301
+ self._call_in_runner_task(fixture_func, **kwargs)
2302
+ )
2303
+ self._raise_async_exceptions()
2304
+ return retval
2305
+
2306
+ def run_test(
2307
+ self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any]
2308
+ ) -> None:
2309
+ try:
2310
+ self.get_loop().run_until_complete(
2311
+ self._call_in_runner_task(test_func, **kwargs)
2312
+ )
2313
+ except Exception as exc:
2314
+ self._exceptions.append(exc)
2315
+
2316
+ self._raise_async_exceptions()
2317
+
2318
+
2319
+ class AsyncIOBackend(AsyncBackend):
2320
+ @classmethod
2321
+ def run(
2322
+ cls,
2323
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
2324
+ args: tuple[Unpack[PosArgsT]],
2325
+ kwargs: dict[str, Any],
2326
+ options: dict[str, Any],
2327
+ ) -> T_Retval:
2328
+ @wraps(func)
2329
+ async def wrapper() -> T_Retval:
2330
+ task = cast(asyncio.Task, current_task())
2331
+ task.set_name(get_callable_name(func))
2332
+ _task_states[task] = TaskState(None, None)
2333
+
2334
+ try:
2335
+ return await func(*args)
2336
+ finally:
2337
+ del _task_states[task]
2338
+
2339
+ debug = options.get("debug", None)
2340
+ loop_factory = options.get("loop_factory", None)
2341
+ if loop_factory is None and options.get("use_uvloop", False):
2342
+ import uvloop
2343
+
2344
+ loop_factory = uvloop.new_event_loop
2345
+
2346
+ with Runner(debug=debug, loop_factory=loop_factory) as runner:
2347
+ return runner.run(wrapper())
2348
+
2349
+ @classmethod
2350
+ def current_token(cls) -> object:
2351
+ return get_running_loop()
2352
+
2353
+ @classmethod
2354
+ def current_time(cls) -> float:
2355
+ return get_running_loop().time()
2356
+
2357
+ @classmethod
2358
+ def cancelled_exception_class(cls) -> type[BaseException]:
2359
+ return CancelledError
2360
+
2361
+ @classmethod
2362
+ async def checkpoint(cls) -> None:
2363
+ await sleep(0)
2364
+
2365
+ @classmethod
2366
+ async def checkpoint_if_cancelled(cls) -> None:
2367
+ task = current_task()
2368
+ if task is None:
2369
+ return
2370
+
2371
+ try:
2372
+ cancel_scope = _task_states[task].cancel_scope
2373
+ except KeyError:
2374
+ return
2375
+
2376
+ while cancel_scope:
2377
+ if cancel_scope.cancel_called:
2378
+ await sleep(0)
2379
+ elif cancel_scope.shield:
2380
+ break
2381
+ else:
2382
+ cancel_scope = cancel_scope._parent_scope
2383
+
2384
+ @classmethod
2385
+ async def cancel_shielded_checkpoint(cls) -> None:
2386
+ with CancelScope(shield=True):
2387
+ await sleep(0)
2388
+
2389
+ @classmethod
2390
+ async def sleep(cls, delay: float) -> None:
2391
+ await sleep(delay)
2392
+
2393
+ @classmethod
2394
+ def create_cancel_scope(
2395
+ cls, *, deadline: float = math.inf, shield: bool = False
2396
+ ) -> CancelScope:
2397
+ return CancelScope(deadline=deadline, shield=shield)
2398
+
2399
+ @classmethod
2400
+ def current_effective_deadline(cls) -> float:
2401
+ if (task := current_task()) is None:
2402
+ return math.inf
2403
+
2404
+ try:
2405
+ cancel_scope = _task_states[task].cancel_scope
2406
+ except KeyError:
2407
+ return math.inf
2408
+
2409
+ deadline = math.inf
2410
+ while cancel_scope:
2411
+ deadline = min(deadline, cancel_scope.deadline)
2412
+ if cancel_scope._cancel_called:
2413
+ deadline = -math.inf
2414
+ break
2415
+ elif cancel_scope.shield:
2416
+ break
2417
+ else:
2418
+ cancel_scope = cancel_scope._parent_scope
2419
+
2420
+ return deadline
2421
+
2422
+ @classmethod
2423
+ def create_task_group(cls) -> abc.TaskGroup:
2424
+ return TaskGroup()
2425
+
2426
+ @classmethod
2427
+ def create_event(cls) -> abc.Event:
2428
+ return Event()
2429
+
2430
+ @classmethod
2431
+ def create_lock(cls, *, fast_acquire: bool) -> abc.Lock:
2432
+ return Lock(fast_acquire=fast_acquire)
2433
+
2434
+ @classmethod
2435
+ def create_semaphore(
2436
+ cls,
2437
+ initial_value: int,
2438
+ *,
2439
+ max_value: int | None = None,
2440
+ fast_acquire: bool = False,
2441
+ ) -> abc.Semaphore:
2442
+ return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire)
2443
+
2444
+ @classmethod
2445
+ def create_capacity_limiter(cls, total_tokens: float) -> abc.CapacityLimiter:
2446
+ return CapacityLimiter(total_tokens)
2447
+
2448
+ @classmethod
2449
+ async def run_sync_in_worker_thread(
2450
+ cls,
2451
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
2452
+ args: tuple[Unpack[PosArgsT]],
2453
+ abandon_on_cancel: bool = False,
2454
+ limiter: abc.CapacityLimiter | None = None,
2455
+ ) -> T_Retval:
2456
+ await cls.checkpoint()
2457
+
2458
+ # If this is the first run in this event loop thread, set up the necessary
2459
+ # variables
2460
+ try:
2461
+ idle_workers = _threadpool_idle_workers.get()
2462
+ workers = _threadpool_workers.get()
2463
+ except LookupError:
2464
+ idle_workers = deque()
2465
+ workers = set()
2466
+ _threadpool_idle_workers.set(idle_workers)
2467
+ _threadpool_workers.set(workers)
2468
+
2469
+ async with limiter or cls.current_default_thread_limiter():
2470
+ with CancelScope(shield=not abandon_on_cancel) as scope:
2471
+ future: asyncio.Future = asyncio.Future()
2472
+ root_task = find_root_task()
2473
+ if not idle_workers:
2474
+ worker = WorkerThread(root_task, workers, idle_workers)
2475
+ worker.start()
2476
+ workers.add(worker)
2477
+ root_task.add_done_callback(worker.stop)
2478
+ else:
2479
+ worker = idle_workers.pop()
2480
+
2481
+ # Prune any other workers that have been idle for MAX_IDLE_TIME
2482
+ # seconds or longer
2483
+ now = cls.current_time()
2484
+ while idle_workers:
2485
+ if (
2486
+ now - idle_workers[0].idle_since
2487
+ < WorkerThread.MAX_IDLE_TIME
2488
+ ):
2489
+ break
2490
+
2491
+ expired_worker = idle_workers.popleft()
2492
+ expired_worker.root_task.remove_done_callback(
2493
+ expired_worker.stop
2494
+ )
2495
+ expired_worker.stop()
2496
+
2497
+ context = copy_context()
2498
+ context.run(sniffio.current_async_library_cvar.set, None)
2499
+ if abandon_on_cancel or scope._parent_scope is None:
2500
+ worker_scope = scope
2501
+ else:
2502
+ worker_scope = scope._parent_scope
2503
+
2504
+ worker.queue.put_nowait((context, func, args, future, worker_scope))
2505
+ return await future
2506
+
2507
+ @classmethod
2508
+ def check_cancelled(cls) -> None:
2509
+ scope: CancelScope | None = threadlocals.current_cancel_scope
2510
+ while scope is not None:
2511
+ if scope.cancel_called:
2512
+ raise CancelledError(f"Cancelled by cancel scope {id(scope):x}")
2513
+
2514
+ if scope.shield:
2515
+ return
2516
+
2517
+ scope = scope._parent_scope
2518
+
2519
+ @classmethod
2520
+ def run_async_from_thread(
2521
+ cls,
2522
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
2523
+ args: tuple[Unpack[PosArgsT]],
2524
+ token: object,
2525
+ ) -> T_Retval:
2526
+ async def task_wrapper(scope: CancelScope) -> T_Retval:
2527
+ __tracebackhide__ = True
2528
+ task = cast(asyncio.Task, current_task())
2529
+ _task_states[task] = TaskState(None, scope)
2530
+ scope._tasks.add(task)
2531
+ try:
2532
+ return await func(*args)
2533
+ except CancelledError as exc:
2534
+ raise concurrent.futures.CancelledError(str(exc)) from None
2535
+ finally:
2536
+ scope._tasks.discard(task)
2537
+
2538
+ loop = cast(AbstractEventLoop, token)
2539
+ context = copy_context()
2540
+ context.run(sniffio.current_async_library_cvar.set, "asyncio")
2541
+ wrapper = task_wrapper(threadlocals.current_cancel_scope)
2542
+ f: concurrent.futures.Future[T_Retval] = context.run(
2543
+ asyncio.run_coroutine_threadsafe, wrapper, loop
2544
+ )
2545
+ return f.result()
2546
+
2547
+ @classmethod
2548
+ def run_sync_from_thread(
2549
+ cls,
2550
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
2551
+ args: tuple[Unpack[PosArgsT]],
2552
+ token: object,
2553
+ ) -> T_Retval:
2554
+ @wraps(func)
2555
+ def wrapper() -> None:
2556
+ try:
2557
+ sniffio.current_async_library_cvar.set("asyncio")
2558
+ f.set_result(func(*args))
2559
+ except BaseException as exc:
2560
+ f.set_exception(exc)
2561
+ if not isinstance(exc, Exception):
2562
+ raise
2563
+
2564
+ f: concurrent.futures.Future[T_Retval] = Future()
2565
+ loop = cast(AbstractEventLoop, token)
2566
+ loop.call_soon_threadsafe(wrapper)
2567
+ return f.result()
2568
+
2569
+ @classmethod
2570
+ def create_blocking_portal(cls) -> abc.BlockingPortal:
2571
+ return BlockingPortal()
2572
+
2573
+ @classmethod
2574
+ async def open_process(
2575
+ cls,
2576
+ command: StrOrBytesPath | Sequence[StrOrBytesPath],
2577
+ *,
2578
+ stdin: int | IO[Any] | None,
2579
+ stdout: int | IO[Any] | None,
2580
+ stderr: int | IO[Any] | None,
2581
+ **kwargs: Any,
2582
+ ) -> Process:
2583
+ await cls.checkpoint()
2584
+ if isinstance(command, PathLike):
2585
+ command = os.fspath(command)
2586
+
2587
+ if isinstance(command, (str, bytes)):
2588
+ process = await asyncio.create_subprocess_shell(
2589
+ command,
2590
+ stdin=stdin,
2591
+ stdout=stdout,
2592
+ stderr=stderr,
2593
+ **kwargs,
2594
+ )
2595
+ else:
2596
+ process = await asyncio.create_subprocess_exec(
2597
+ *command,
2598
+ stdin=stdin,
2599
+ stdout=stdout,
2600
+ stderr=stderr,
2601
+ **kwargs,
2602
+ )
2603
+
2604
+ stdin_stream = StreamWriterWrapper(process.stdin) if process.stdin else None
2605
+ stdout_stream = StreamReaderWrapper(process.stdout) if process.stdout else None
2606
+ stderr_stream = StreamReaderWrapper(process.stderr) if process.stderr else None
2607
+ return Process(process, stdin_stream, stdout_stream, stderr_stream)
2608
+
2609
+ @classmethod
2610
+ def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None:
2611
+ create_task(
2612
+ _shutdown_process_pool_on_exit(workers),
2613
+ name="AnyIO process pool shutdown task",
2614
+ )
2615
+ find_root_task().add_done_callback(
2616
+ partial(_forcibly_shutdown_process_pool_on_exit, workers) # type:ignore[arg-type]
2617
+ )
2618
+
2619
+ @classmethod
2620
+ async def connect_tcp(
2621
+ cls, host: str, port: int, local_address: IPSockAddrType | None = None
2622
+ ) -> abc.SocketStream:
2623
+ transport, protocol = cast(
2624
+ tuple[asyncio.Transport, StreamProtocol],
2625
+ await get_running_loop().create_connection(
2626
+ StreamProtocol, host, port, local_addr=local_address
2627
+ ),
2628
+ )
2629
+ transport.pause_reading()
2630
+ return SocketStream(transport, protocol)
2631
+
2632
+ @classmethod
2633
+ async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream:
2634
+ await cls.checkpoint()
2635
+ loop = get_running_loop()
2636
+ raw_socket = socket.socket(socket.AF_UNIX)
2637
+ raw_socket.setblocking(False)
2638
+ while True:
2639
+ try:
2640
+ raw_socket.connect(path)
2641
+ except BlockingIOError:
2642
+ f: asyncio.Future = asyncio.Future()
2643
+ loop.add_writer(raw_socket, f.set_result, None)
2644
+ f.add_done_callback(lambda _: loop.remove_writer(raw_socket))
2645
+ await f
2646
+ except BaseException:
2647
+ raw_socket.close()
2648
+ raise
2649
+ else:
2650
+ return UNIXSocketStream(raw_socket)
2651
+
2652
+ @classmethod
2653
+ def create_tcp_listener(cls, sock: socket.socket) -> SocketListener:
2654
+ return TCPSocketListener(sock)
2655
+
2656
+ @classmethod
2657
+ def create_unix_listener(cls, sock: socket.socket) -> SocketListener:
2658
+ return UNIXSocketListener(sock)
2659
+
2660
+ @classmethod
2661
+ async def create_udp_socket(
2662
+ cls,
2663
+ family: AddressFamily,
2664
+ local_address: IPSockAddrType | None,
2665
+ remote_address: IPSockAddrType | None,
2666
+ reuse_port: bool,
2667
+ ) -> UDPSocket | ConnectedUDPSocket:
2668
+ transport, protocol = await get_running_loop().create_datagram_endpoint(
2669
+ DatagramProtocol,
2670
+ local_addr=local_address,
2671
+ remote_addr=remote_address,
2672
+ family=family,
2673
+ reuse_port=reuse_port,
2674
+ )
2675
+ if protocol.exception:
2676
+ transport.close()
2677
+ raise protocol.exception
2678
+
2679
+ if not remote_address:
2680
+ return UDPSocket(transport, protocol)
2681
+ else:
2682
+ return ConnectedUDPSocket(transport, protocol)
2683
+
2684
+ @classmethod
2685
+ async def create_unix_datagram_socket( # type: ignore[override]
2686
+ cls, raw_socket: socket.socket, remote_path: str | bytes | None
2687
+ ) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket:
2688
+ await cls.checkpoint()
2689
+ loop = get_running_loop()
2690
+
2691
+ if remote_path:
2692
+ while True:
2693
+ try:
2694
+ raw_socket.connect(remote_path)
2695
+ except BlockingIOError:
2696
+ f: asyncio.Future = asyncio.Future()
2697
+ loop.add_writer(raw_socket, f.set_result, None)
2698
+ f.add_done_callback(lambda _: loop.remove_writer(raw_socket))
2699
+ await f
2700
+ except BaseException:
2701
+ raw_socket.close()
2702
+ raise
2703
+ else:
2704
+ return ConnectedUNIXDatagramSocket(raw_socket)
2705
+ else:
2706
+ return UNIXDatagramSocket(raw_socket)
2707
+
2708
+ @classmethod
2709
+ async def getaddrinfo(
2710
+ cls,
2711
+ host: bytes | str | None,
2712
+ port: str | int | None,
2713
+ *,
2714
+ family: int | AddressFamily = 0,
2715
+ type: int | SocketKind = 0,
2716
+ proto: int = 0,
2717
+ flags: int = 0,
2718
+ ) -> list[
2719
+ tuple[
2720
+ AddressFamily,
2721
+ SocketKind,
2722
+ int,
2723
+ str,
2724
+ tuple[str, int] | tuple[str, int, int, int],
2725
+ ]
2726
+ ]:
2727
+ return await get_running_loop().getaddrinfo(
2728
+ host, port, family=family, type=type, proto=proto, flags=flags
2729
+ )
2730
+
2731
+ @classmethod
2732
+ async def getnameinfo(
2733
+ cls, sockaddr: IPSockAddrType, flags: int = 0
2734
+ ) -> tuple[str, str]:
2735
+ return await get_running_loop().getnameinfo(sockaddr, flags)
2736
+
2737
+ @classmethod
2738
+ async def wait_readable(cls, obj: FileDescriptorLike) -> None:
2739
+ await cls.checkpoint()
2740
+ try:
2741
+ read_events = _read_events.get()
2742
+ except LookupError:
2743
+ read_events = {}
2744
+ _read_events.set(read_events)
2745
+
2746
+ if not isinstance(obj, int):
2747
+ obj = obj.fileno()
2748
+
2749
+ if read_events.get(obj):
2750
+ raise BusyResourceError("reading from")
2751
+
2752
+ loop = get_running_loop()
2753
+ event = asyncio.Event()
2754
+ try:
2755
+ loop.add_reader(obj, event.set)
2756
+ except NotImplementedError:
2757
+ from anyio._core._asyncio_selector_thread import get_selector
2758
+
2759
+ selector = get_selector()
2760
+ selector.add_reader(obj, event.set)
2761
+ remove_reader = selector.remove_reader
2762
+ else:
2763
+ remove_reader = loop.remove_reader
2764
+
2765
+ read_events[obj] = event
2766
+ try:
2767
+ await event.wait()
2768
+ finally:
2769
+ remove_reader(obj)
2770
+ del read_events[obj]
2771
+
2772
+ @classmethod
2773
+ async def wait_writable(cls, obj: FileDescriptorLike) -> None:
2774
+ await cls.checkpoint()
2775
+ try:
2776
+ write_events = _write_events.get()
2777
+ except LookupError:
2778
+ write_events = {}
2779
+ _write_events.set(write_events)
2780
+
2781
+ if not isinstance(obj, int):
2782
+ obj = obj.fileno()
2783
+
2784
+ if write_events.get(obj):
2785
+ raise BusyResourceError("writing to")
2786
+
2787
+ loop = get_running_loop()
2788
+ event = asyncio.Event()
2789
+ try:
2790
+ loop.add_writer(obj, event.set)
2791
+ except NotImplementedError:
2792
+ from anyio._core._asyncio_selector_thread import get_selector
2793
+
2794
+ selector = get_selector()
2795
+ selector.add_writer(obj, event.set)
2796
+ remove_writer = selector.remove_writer
2797
+ else:
2798
+ remove_writer = loop.remove_writer
2799
+
2800
+ write_events[obj] = event
2801
+ try:
2802
+ await event.wait()
2803
+ finally:
2804
+ del write_events[obj]
2805
+ remove_writer(obj)
2806
+
2807
+ @classmethod
2808
+ def current_default_thread_limiter(cls) -> CapacityLimiter:
2809
+ try:
2810
+ return _default_thread_limiter.get()
2811
+ except LookupError:
2812
+ limiter = CapacityLimiter(40)
2813
+ _default_thread_limiter.set(limiter)
2814
+ return limiter
2815
+
2816
+ @classmethod
2817
+ def open_signal_receiver(
2818
+ cls, *signals: Signals
2819
+ ) -> AbstractContextManager[AsyncIterator[Signals]]:
2820
+ return _SignalReceiver(signals)
2821
+
2822
+ @classmethod
2823
+ def get_current_task(cls) -> TaskInfo:
2824
+ return AsyncIOTaskInfo(current_task()) # type: ignore[arg-type]
2825
+
2826
+ @classmethod
2827
+ def get_running_tasks(cls) -> Sequence[TaskInfo]:
2828
+ return [AsyncIOTaskInfo(task) for task in all_tasks() if not task.done()]
2829
+
2830
+ @classmethod
2831
+ async def wait_all_tasks_blocked(cls) -> None:
2832
+ await cls.checkpoint()
2833
+ this_task = current_task()
2834
+ while True:
2835
+ for task in all_tasks():
2836
+ if task is this_task:
2837
+ continue
2838
+
2839
+ waiter = task._fut_waiter # type: ignore[attr-defined]
2840
+ if waiter is None or waiter.done():
2841
+ await sleep(0.1)
2842
+ break
2843
+ else:
2844
+ return
2845
+
2846
+ @classmethod
2847
+ def create_test_runner(cls, options: dict[str, Any]) -> TestRunner:
2848
+ return TestRunner(**options)
2849
+
2850
+
2851
+ backend_class = AsyncIOBackend
vllm/lib/python3.10/site-packages/anyio/_backends/_trio.py ADDED
@@ -0,0 +1,1334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import array
4
+ import math
5
+ import os
6
+ import socket
7
+ import sys
8
+ import types
9
+ import weakref
10
+ from collections.abc import (
11
+ AsyncGenerator,
12
+ AsyncIterator,
13
+ Awaitable,
14
+ Callable,
15
+ Collection,
16
+ Coroutine,
17
+ Iterable,
18
+ Sequence,
19
+ )
20
+ from concurrent.futures import Future
21
+ from contextlib import AbstractContextManager
22
+ from dataclasses import dataclass
23
+ from functools import partial
24
+ from io import IOBase
25
+ from os import PathLike
26
+ from signal import Signals
27
+ from socket import AddressFamily, SocketKind
28
+ from types import TracebackType
29
+ from typing import (
30
+ IO,
31
+ TYPE_CHECKING,
32
+ Any,
33
+ Generic,
34
+ NoReturn,
35
+ TypeVar,
36
+ cast,
37
+ overload,
38
+ )
39
+
40
+ import trio.from_thread
41
+ import trio.lowlevel
42
+ from outcome import Error, Outcome, Value
43
+ from trio.lowlevel import (
44
+ current_root_task,
45
+ current_task,
46
+ wait_readable,
47
+ wait_writable,
48
+ )
49
+ from trio.socket import SocketType as TrioSocketType
50
+ from trio.to_thread import run_sync
51
+
52
+ from .. import (
53
+ CapacityLimiterStatistics,
54
+ EventStatistics,
55
+ LockStatistics,
56
+ TaskInfo,
57
+ WouldBlock,
58
+ abc,
59
+ )
60
+ from .._core._eventloop import claim_worker_thread
61
+ from .._core._exceptions import (
62
+ BrokenResourceError,
63
+ BusyResourceError,
64
+ ClosedResourceError,
65
+ EndOfStream,
66
+ )
67
+ from .._core._sockets import convert_ipv6_sockaddr
68
+ from .._core._streams import create_memory_object_stream
69
+ from .._core._synchronization import (
70
+ CapacityLimiter as BaseCapacityLimiter,
71
+ )
72
+ from .._core._synchronization import Event as BaseEvent
73
+ from .._core._synchronization import Lock as BaseLock
74
+ from .._core._synchronization import (
75
+ ResourceGuard,
76
+ SemaphoreStatistics,
77
+ )
78
+ from .._core._synchronization import Semaphore as BaseSemaphore
79
+ from .._core._tasks import CancelScope as BaseCancelScope
80
+ from ..abc import IPSockAddrType, UDPPacketType, UNIXDatagramPacketType
81
+ from ..abc._eventloop import AsyncBackend, StrOrBytesPath
82
+ from ..streams.memory import MemoryObjectSendStream
83
+
84
+ if TYPE_CHECKING:
85
+ from _typeshed import HasFileno
86
+
87
+ if sys.version_info >= (3, 10):
88
+ from typing import ParamSpec
89
+ else:
90
+ from typing_extensions import ParamSpec
91
+
92
+ if sys.version_info >= (3, 11):
93
+ from typing import TypeVarTuple, Unpack
94
+ else:
95
+ from exceptiongroup import BaseExceptionGroup
96
+ from typing_extensions import TypeVarTuple, Unpack
97
+
98
+ T = TypeVar("T")
99
+ T_Retval = TypeVar("T_Retval")
100
+ T_SockAddr = TypeVar("T_SockAddr", str, IPSockAddrType)
101
+ PosArgsT = TypeVarTuple("PosArgsT")
102
+ P = ParamSpec("P")
103
+
104
+
105
+ #
106
+ # Event loop
107
+ #
108
+
109
+ RunVar = trio.lowlevel.RunVar
110
+
111
+
112
+ #
113
+ # Timeouts and cancellation
114
+ #
115
+
116
+
117
+ class CancelScope(BaseCancelScope):
118
+ def __new__(
119
+ cls, original: trio.CancelScope | None = None, **kwargs: object
120
+ ) -> CancelScope:
121
+ return object.__new__(cls)
122
+
123
+ def __init__(self, original: trio.CancelScope | None = None, **kwargs: Any) -> None:
124
+ self.__original = original or trio.CancelScope(**kwargs)
125
+
126
+ def __enter__(self) -> CancelScope:
127
+ self.__original.__enter__()
128
+ return self
129
+
130
+ def __exit__(
131
+ self,
132
+ exc_type: type[BaseException] | None,
133
+ exc_val: BaseException | None,
134
+ exc_tb: TracebackType | None,
135
+ ) -> bool | None:
136
+ # https://github.com/python-trio/trio-typing/pull/79
137
+ return self.__original.__exit__(exc_type, exc_val, exc_tb)
138
+
139
+ def cancel(self) -> None:
140
+ self.__original.cancel()
141
+
142
+ @property
143
+ def deadline(self) -> float:
144
+ return self.__original.deadline
145
+
146
+ @deadline.setter
147
+ def deadline(self, value: float) -> None:
148
+ self.__original.deadline = value
149
+
150
+ @property
151
+ def cancel_called(self) -> bool:
152
+ return self.__original.cancel_called
153
+
154
+ @property
155
+ def cancelled_caught(self) -> bool:
156
+ return self.__original.cancelled_caught
157
+
158
+ @property
159
+ def shield(self) -> bool:
160
+ return self.__original.shield
161
+
162
+ @shield.setter
163
+ def shield(self, value: bool) -> None:
164
+ self.__original.shield = value
165
+
166
+
167
+ #
168
+ # Task groups
169
+ #
170
+
171
+
172
+ class TaskGroup(abc.TaskGroup):
173
+ def __init__(self) -> None:
174
+ self._active = False
175
+ self._nursery_manager = trio.open_nursery(strict_exception_groups=True)
176
+ self.cancel_scope = None # type: ignore[assignment]
177
+
178
+ async def __aenter__(self) -> TaskGroup:
179
+ self._active = True
180
+ self._nursery = await self._nursery_manager.__aenter__()
181
+ self.cancel_scope = CancelScope(self._nursery.cancel_scope)
182
+ return self
183
+
184
+ async def __aexit__(
185
+ self,
186
+ exc_type: type[BaseException] | None,
187
+ exc_val: BaseException | None,
188
+ exc_tb: TracebackType | None,
189
+ ) -> bool | None:
190
+ try:
191
+ return await self._nursery_manager.__aexit__(exc_type, exc_val, exc_tb)
192
+ except BaseExceptionGroup as exc:
193
+ if not exc.split(trio.Cancelled)[1]:
194
+ raise trio.Cancelled._create() from exc
195
+
196
+ raise
197
+ finally:
198
+ del exc_val, exc_tb
199
+ self._active = False
200
+
201
+ def start_soon(
202
+ self,
203
+ func: Callable[[Unpack[PosArgsT]], Awaitable[Any]],
204
+ *args: Unpack[PosArgsT],
205
+ name: object = None,
206
+ ) -> None:
207
+ if not self._active:
208
+ raise RuntimeError(
209
+ "This task group is not active; no new tasks can be started."
210
+ )
211
+
212
+ self._nursery.start_soon(func, *args, name=name)
213
+
214
+ async def start(
215
+ self, func: Callable[..., Awaitable[Any]], *args: object, name: object = None
216
+ ) -> Any:
217
+ if not self._active:
218
+ raise RuntimeError(
219
+ "This task group is not active; no new tasks can be started."
220
+ )
221
+
222
+ return await self._nursery.start(func, *args, name=name)
223
+
224
+
225
+ #
226
+ # Threads
227
+ #
228
+
229
+
230
+ class BlockingPortal(abc.BlockingPortal):
231
+ def __new__(cls) -> BlockingPortal:
232
+ return object.__new__(cls)
233
+
234
+ def __init__(self) -> None:
235
+ super().__init__()
236
+ self._token = trio.lowlevel.current_trio_token()
237
+
238
+ def _spawn_task_from_thread(
239
+ self,
240
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval],
241
+ args: tuple[Unpack[PosArgsT]],
242
+ kwargs: dict[str, Any],
243
+ name: object,
244
+ future: Future[T_Retval],
245
+ ) -> None:
246
+ trio.from_thread.run_sync(
247
+ partial(self._task_group.start_soon, name=name),
248
+ self._call_func,
249
+ func,
250
+ args,
251
+ kwargs,
252
+ future,
253
+ trio_token=self._token,
254
+ )
255
+
256
+
257
+ #
258
+ # Subprocesses
259
+ #
260
+
261
+
262
+ @dataclass(eq=False)
263
+ class ReceiveStreamWrapper(abc.ByteReceiveStream):
264
+ _stream: trio.abc.ReceiveStream
265
+
266
+ async def receive(self, max_bytes: int | None = None) -> bytes:
267
+ try:
268
+ data = await self._stream.receive_some(max_bytes)
269
+ except trio.ClosedResourceError as exc:
270
+ raise ClosedResourceError from exc.__cause__
271
+ except trio.BrokenResourceError as exc:
272
+ raise BrokenResourceError from exc.__cause__
273
+
274
+ if data:
275
+ return data
276
+ else:
277
+ raise EndOfStream
278
+
279
+ async def aclose(self) -> None:
280
+ await self._stream.aclose()
281
+
282
+
283
+ @dataclass(eq=False)
284
+ class SendStreamWrapper(abc.ByteSendStream):
285
+ _stream: trio.abc.SendStream
286
+
287
+ async def send(self, item: bytes) -> None:
288
+ try:
289
+ await self._stream.send_all(item)
290
+ except trio.ClosedResourceError as exc:
291
+ raise ClosedResourceError from exc.__cause__
292
+ except trio.BrokenResourceError as exc:
293
+ raise BrokenResourceError from exc.__cause__
294
+
295
+ async def aclose(self) -> None:
296
+ await self._stream.aclose()
297
+
298
+
299
+ @dataclass(eq=False)
300
+ class Process(abc.Process):
301
+ _process: trio.Process
302
+ _stdin: abc.ByteSendStream | None
303
+ _stdout: abc.ByteReceiveStream | None
304
+ _stderr: abc.ByteReceiveStream | None
305
+
306
+ async def aclose(self) -> None:
307
+ with CancelScope(shield=True):
308
+ if self._stdin:
309
+ await self._stdin.aclose()
310
+ if self._stdout:
311
+ await self._stdout.aclose()
312
+ if self._stderr:
313
+ await self._stderr.aclose()
314
+
315
+ try:
316
+ await self.wait()
317
+ except BaseException:
318
+ self.kill()
319
+ with CancelScope(shield=True):
320
+ await self.wait()
321
+ raise
322
+
323
+ async def wait(self) -> int:
324
+ return await self._process.wait()
325
+
326
+ def terminate(self) -> None:
327
+ self._process.terminate()
328
+
329
+ def kill(self) -> None:
330
+ self._process.kill()
331
+
332
+ def send_signal(self, signal: Signals) -> None:
333
+ self._process.send_signal(signal)
334
+
335
+ @property
336
+ def pid(self) -> int:
337
+ return self._process.pid
338
+
339
+ @property
340
+ def returncode(self) -> int | None:
341
+ return self._process.returncode
342
+
343
+ @property
344
+ def stdin(self) -> abc.ByteSendStream | None:
345
+ return self._stdin
346
+
347
+ @property
348
+ def stdout(self) -> abc.ByteReceiveStream | None:
349
+ return self._stdout
350
+
351
+ @property
352
+ def stderr(self) -> abc.ByteReceiveStream | None:
353
+ return self._stderr
354
+
355
+
356
+ class _ProcessPoolShutdownInstrument(trio.abc.Instrument):
357
+ def after_run(self) -> None:
358
+ super().after_run()
359
+
360
+
361
+ current_default_worker_process_limiter: trio.lowlevel.RunVar = RunVar(
362
+ "current_default_worker_process_limiter"
363
+ )
364
+
365
+
366
+ async def _shutdown_process_pool(workers: set[abc.Process]) -> None:
367
+ try:
368
+ await trio.sleep(math.inf)
369
+ except trio.Cancelled:
370
+ for process in workers:
371
+ if process.returncode is None:
372
+ process.kill()
373
+
374
+ with CancelScope(shield=True):
375
+ for process in workers:
376
+ await process.aclose()
377
+
378
+
379
+ #
380
+ # Sockets and networking
381
+ #
382
+
383
+
384
+ class _TrioSocketMixin(Generic[T_SockAddr]):
385
+ def __init__(self, trio_socket: TrioSocketType) -> None:
386
+ self._trio_socket = trio_socket
387
+ self._closed = False
388
+
389
+ def _check_closed(self) -> None:
390
+ if self._closed:
391
+ raise ClosedResourceError
392
+ if self._trio_socket.fileno() < 0:
393
+ raise BrokenResourceError
394
+
395
+ @property
396
+ def _raw_socket(self) -> socket.socket:
397
+ return self._trio_socket._sock # type: ignore[attr-defined]
398
+
399
+ async def aclose(self) -> None:
400
+ if self._trio_socket.fileno() >= 0:
401
+ self._closed = True
402
+ self._trio_socket.close()
403
+
404
+ def _convert_socket_error(self, exc: BaseException) -> NoReturn:
405
+ if isinstance(exc, trio.ClosedResourceError):
406
+ raise ClosedResourceError from exc
407
+ elif self._trio_socket.fileno() < 0 and self._closed:
408
+ raise ClosedResourceError from None
409
+ elif isinstance(exc, OSError):
410
+ raise BrokenResourceError from exc
411
+ else:
412
+ raise exc
413
+
414
+
415
+ class SocketStream(_TrioSocketMixin, abc.SocketStream):
416
+ def __init__(self, trio_socket: TrioSocketType) -> None:
417
+ super().__init__(trio_socket)
418
+ self._receive_guard = ResourceGuard("reading from")
419
+ self._send_guard = ResourceGuard("writing to")
420
+
421
+ async def receive(self, max_bytes: int = 65536) -> bytes:
422
+ with self._receive_guard:
423
+ try:
424
+ data = await self._trio_socket.recv(max_bytes)
425
+ except BaseException as exc:
426
+ self._convert_socket_error(exc)
427
+
428
+ if data:
429
+ return data
430
+ else:
431
+ raise EndOfStream
432
+
433
+ async def send(self, item: bytes) -> None:
434
+ with self._send_guard:
435
+ view = memoryview(item)
436
+ while view:
437
+ try:
438
+ bytes_sent = await self._trio_socket.send(view)
439
+ except BaseException as exc:
440
+ self._convert_socket_error(exc)
441
+
442
+ view = view[bytes_sent:]
443
+
444
+ async def send_eof(self) -> None:
445
+ self._trio_socket.shutdown(socket.SHUT_WR)
446
+
447
+
448
+ class UNIXSocketStream(SocketStream, abc.UNIXSocketStream):
449
+ async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]:
450
+ if not isinstance(msglen, int) or msglen < 0:
451
+ raise ValueError("msglen must be a non-negative integer")
452
+ if not isinstance(maxfds, int) or maxfds < 1:
453
+ raise ValueError("maxfds must be a positive integer")
454
+
455
+ fds = array.array("i")
456
+ await trio.lowlevel.checkpoint()
457
+ with self._receive_guard:
458
+ while True:
459
+ try:
460
+ message, ancdata, flags, addr = await self._trio_socket.recvmsg(
461
+ msglen, socket.CMSG_LEN(maxfds * fds.itemsize)
462
+ )
463
+ except BaseException as exc:
464
+ self._convert_socket_error(exc)
465
+ else:
466
+ if not message and not ancdata:
467
+ raise EndOfStream
468
+
469
+ break
470
+
471
+ for cmsg_level, cmsg_type, cmsg_data in ancdata:
472
+ if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS:
473
+ raise RuntimeError(
474
+ f"Received unexpected ancillary data; message = {message!r}, "
475
+ f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}"
476
+ )
477
+
478
+ fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
479
+
480
+ return message, list(fds)
481
+
482
+ async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None:
483
+ if not message:
484
+ raise ValueError("message must not be empty")
485
+ if not fds:
486
+ raise ValueError("fds must not be empty")
487
+
488
+ filenos: list[int] = []
489
+ for fd in fds:
490
+ if isinstance(fd, int):
491
+ filenos.append(fd)
492
+ elif isinstance(fd, IOBase):
493
+ filenos.append(fd.fileno())
494
+
495
+ fdarray = array.array("i", filenos)
496
+ await trio.lowlevel.checkpoint()
497
+ with self._send_guard:
498
+ while True:
499
+ try:
500
+ await self._trio_socket.sendmsg(
501
+ [message],
502
+ [
503
+ (
504
+ socket.SOL_SOCKET,
505
+ socket.SCM_RIGHTS,
506
+ fdarray,
507
+ )
508
+ ],
509
+ )
510
+ break
511
+ except BaseException as exc:
512
+ self._convert_socket_error(exc)
513
+
514
+
515
+ class TCPSocketListener(_TrioSocketMixin, abc.SocketListener):
516
+ def __init__(self, raw_socket: socket.socket):
517
+ super().__init__(trio.socket.from_stdlib_socket(raw_socket))
518
+ self._accept_guard = ResourceGuard("accepting connections from")
519
+
520
+ async def accept(self) -> SocketStream:
521
+ with self._accept_guard:
522
+ try:
523
+ trio_socket, _addr = await self._trio_socket.accept()
524
+ except BaseException as exc:
525
+ self._convert_socket_error(exc)
526
+
527
+ trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
528
+ return SocketStream(trio_socket)
529
+
530
+
531
+ class UNIXSocketListener(_TrioSocketMixin, abc.SocketListener):
532
+ def __init__(self, raw_socket: socket.socket):
533
+ super().__init__(trio.socket.from_stdlib_socket(raw_socket))
534
+ self._accept_guard = ResourceGuard("accepting connections from")
535
+
536
+ async def accept(self) -> UNIXSocketStream:
537
+ with self._accept_guard:
538
+ try:
539
+ trio_socket, _addr = await self._trio_socket.accept()
540
+ except BaseException as exc:
541
+ self._convert_socket_error(exc)
542
+
543
+ return UNIXSocketStream(trio_socket)
544
+
545
+
546
+ class UDPSocket(_TrioSocketMixin[IPSockAddrType], abc.UDPSocket):
547
+ def __init__(self, trio_socket: TrioSocketType) -> None:
548
+ super().__init__(trio_socket)
549
+ self._receive_guard = ResourceGuard("reading from")
550
+ self._send_guard = ResourceGuard("writing to")
551
+
552
+ async def receive(self) -> tuple[bytes, IPSockAddrType]:
553
+ with self._receive_guard:
554
+ try:
555
+ data, addr = await self._trio_socket.recvfrom(65536)
556
+ return data, convert_ipv6_sockaddr(addr)
557
+ except BaseException as exc:
558
+ self._convert_socket_error(exc)
559
+
560
+ async def send(self, item: UDPPacketType) -> None:
561
+ with self._send_guard:
562
+ try:
563
+ await self._trio_socket.sendto(*item)
564
+ except BaseException as exc:
565
+ self._convert_socket_error(exc)
566
+
567
+
568
+ class ConnectedUDPSocket(_TrioSocketMixin[IPSockAddrType], abc.ConnectedUDPSocket):
569
+ def __init__(self, trio_socket: TrioSocketType) -> None:
570
+ super().__init__(trio_socket)
571
+ self._receive_guard = ResourceGuard("reading from")
572
+ self._send_guard = ResourceGuard("writing to")
573
+
574
+ async def receive(self) -> bytes:
575
+ with self._receive_guard:
576
+ try:
577
+ return await self._trio_socket.recv(65536)
578
+ except BaseException as exc:
579
+ self._convert_socket_error(exc)
580
+
581
+ async def send(self, item: bytes) -> None:
582
+ with self._send_guard:
583
+ try:
584
+ await self._trio_socket.send(item)
585
+ except BaseException as exc:
586
+ self._convert_socket_error(exc)
587
+
588
+
589
+ class UNIXDatagramSocket(_TrioSocketMixin[str], abc.UNIXDatagramSocket):
590
+ def __init__(self, trio_socket: TrioSocketType) -> None:
591
+ super().__init__(trio_socket)
592
+ self._receive_guard = ResourceGuard("reading from")
593
+ self._send_guard = ResourceGuard("writing to")
594
+
595
+ async def receive(self) -> UNIXDatagramPacketType:
596
+ with self._receive_guard:
597
+ try:
598
+ data, addr = await self._trio_socket.recvfrom(65536)
599
+ return data, addr
600
+ except BaseException as exc:
601
+ self._convert_socket_error(exc)
602
+
603
+ async def send(self, item: UNIXDatagramPacketType) -> None:
604
+ with self._send_guard:
605
+ try:
606
+ await self._trio_socket.sendto(*item)
607
+ except BaseException as exc:
608
+ self._convert_socket_error(exc)
609
+
610
+
611
+ class ConnectedUNIXDatagramSocket(
612
+ _TrioSocketMixin[str], abc.ConnectedUNIXDatagramSocket
613
+ ):
614
+ def __init__(self, trio_socket: TrioSocketType) -> None:
615
+ super().__init__(trio_socket)
616
+ self._receive_guard = ResourceGuard("reading from")
617
+ self._send_guard = ResourceGuard("writing to")
618
+
619
+ async def receive(self) -> bytes:
620
+ with self._receive_guard:
621
+ try:
622
+ return await self._trio_socket.recv(65536)
623
+ except BaseException as exc:
624
+ self._convert_socket_error(exc)
625
+
626
+ async def send(self, item: bytes) -> None:
627
+ with self._send_guard:
628
+ try:
629
+ await self._trio_socket.send(item)
630
+ except BaseException as exc:
631
+ self._convert_socket_error(exc)
632
+
633
+
634
+ #
635
+ # Synchronization
636
+ #
637
+
638
+
639
+ class Event(BaseEvent):
640
+ def __new__(cls) -> Event:
641
+ return object.__new__(cls)
642
+
643
+ def __init__(self) -> None:
644
+ self.__original = trio.Event()
645
+
646
+ def is_set(self) -> bool:
647
+ return self.__original.is_set()
648
+
649
+ async def wait(self) -> None:
650
+ return await self.__original.wait()
651
+
652
+ def statistics(self) -> EventStatistics:
653
+ orig_statistics = self.__original.statistics()
654
+ return EventStatistics(tasks_waiting=orig_statistics.tasks_waiting)
655
+
656
+ def set(self) -> None:
657
+ self.__original.set()
658
+
659
+
660
+ class Lock(BaseLock):
661
+ def __new__(cls, *, fast_acquire: bool = False) -> Lock:
662
+ return object.__new__(cls)
663
+
664
+ def __init__(self, *, fast_acquire: bool = False) -> None:
665
+ self._fast_acquire = fast_acquire
666
+ self.__original = trio.Lock()
667
+
668
+ @staticmethod
669
+ def _convert_runtime_error_msg(exc: RuntimeError) -> None:
670
+ if exc.args == ("attempt to re-acquire an already held Lock",):
671
+ exc.args = ("Attempted to acquire an already held Lock",)
672
+
673
+ async def acquire(self) -> None:
674
+ if not self._fast_acquire:
675
+ try:
676
+ await self.__original.acquire()
677
+ except RuntimeError as exc:
678
+ self._convert_runtime_error_msg(exc)
679
+ raise
680
+
681
+ return
682
+
683
+ # This is the "fast path" where we don't let other tasks run
684
+ await trio.lowlevel.checkpoint_if_cancelled()
685
+ try:
686
+ self.__original.acquire_nowait()
687
+ except trio.WouldBlock:
688
+ await self.__original._lot.park()
689
+ except RuntimeError as exc:
690
+ self._convert_runtime_error_msg(exc)
691
+ raise
692
+
693
+ def acquire_nowait(self) -> None:
694
+ try:
695
+ self.__original.acquire_nowait()
696
+ except trio.WouldBlock:
697
+ raise WouldBlock from None
698
+ except RuntimeError as exc:
699
+ self._convert_runtime_error_msg(exc)
700
+ raise
701
+
702
+ def locked(self) -> bool:
703
+ return self.__original.locked()
704
+
705
+ def release(self) -> None:
706
+ self.__original.release()
707
+
708
+ def statistics(self) -> LockStatistics:
709
+ orig_statistics = self.__original.statistics()
710
+ owner = TrioTaskInfo(orig_statistics.owner) if orig_statistics.owner else None
711
+ return LockStatistics(
712
+ orig_statistics.locked, owner, orig_statistics.tasks_waiting
713
+ )
714
+
715
+
716
+ class Semaphore(BaseSemaphore):
717
+ def __new__(
718
+ cls,
719
+ initial_value: int,
720
+ *,
721
+ max_value: int | None = None,
722
+ fast_acquire: bool = False,
723
+ ) -> Semaphore:
724
+ return object.__new__(cls)
725
+
726
+ def __init__(
727
+ self,
728
+ initial_value: int,
729
+ *,
730
+ max_value: int | None = None,
731
+ fast_acquire: bool = False,
732
+ ) -> None:
733
+ super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire)
734
+ self.__original = trio.Semaphore(initial_value, max_value=max_value)
735
+
736
+ async def acquire(self) -> None:
737
+ if not self._fast_acquire:
738
+ await self.__original.acquire()
739
+ return
740
+
741
+ # This is the "fast path" where we don't let other tasks run
742
+ await trio.lowlevel.checkpoint_if_cancelled()
743
+ try:
744
+ self.__original.acquire_nowait()
745
+ except trio.WouldBlock:
746
+ await self.__original._lot.park()
747
+
748
+ def acquire_nowait(self) -> None:
749
+ try:
750
+ self.__original.acquire_nowait()
751
+ except trio.WouldBlock:
752
+ raise WouldBlock from None
753
+
754
+ @property
755
+ def max_value(self) -> int | None:
756
+ return self.__original.max_value
757
+
758
+ @property
759
+ def value(self) -> int:
760
+ return self.__original.value
761
+
762
+ def release(self) -> None:
763
+ self.__original.release()
764
+
765
+ def statistics(self) -> SemaphoreStatistics:
766
+ orig_statistics = self.__original.statistics()
767
+ return SemaphoreStatistics(orig_statistics.tasks_waiting)
768
+
769
+
770
+ class CapacityLimiter(BaseCapacityLimiter):
771
+ def __new__(
772
+ cls,
773
+ total_tokens: float | None = None,
774
+ *,
775
+ original: trio.CapacityLimiter | None = None,
776
+ ) -> CapacityLimiter:
777
+ return object.__new__(cls)
778
+
779
+ def __init__(
780
+ self,
781
+ total_tokens: float | None = None,
782
+ *,
783
+ original: trio.CapacityLimiter | None = None,
784
+ ) -> None:
785
+ if original is not None:
786
+ self.__original = original
787
+ else:
788
+ assert total_tokens is not None
789
+ self.__original = trio.CapacityLimiter(total_tokens)
790
+
791
+ async def __aenter__(self) -> None:
792
+ return await self.__original.__aenter__()
793
+
794
+ async def __aexit__(
795
+ self,
796
+ exc_type: type[BaseException] | None,
797
+ exc_val: BaseException | None,
798
+ exc_tb: TracebackType | None,
799
+ ) -> None:
800
+ await self.__original.__aexit__(exc_type, exc_val, exc_tb)
801
+
802
+ @property
803
+ def total_tokens(self) -> float:
804
+ return self.__original.total_tokens
805
+
806
+ @total_tokens.setter
807
+ def total_tokens(self, value: float) -> None:
808
+ self.__original.total_tokens = value
809
+
810
+ @property
811
+ def borrowed_tokens(self) -> int:
812
+ return self.__original.borrowed_tokens
813
+
814
+ @property
815
+ def available_tokens(self) -> float:
816
+ return self.__original.available_tokens
817
+
818
+ def acquire_nowait(self) -> None:
819
+ self.__original.acquire_nowait()
820
+
821
+ def acquire_on_behalf_of_nowait(self, borrower: object) -> None:
822
+ self.__original.acquire_on_behalf_of_nowait(borrower)
823
+
824
+ async def acquire(self) -> None:
825
+ await self.__original.acquire()
826
+
827
+ async def acquire_on_behalf_of(self, borrower: object) -> None:
828
+ await self.__original.acquire_on_behalf_of(borrower)
829
+
830
+ def release(self) -> None:
831
+ return self.__original.release()
832
+
833
+ def release_on_behalf_of(self, borrower: object) -> None:
834
+ return self.__original.release_on_behalf_of(borrower)
835
+
836
+ def statistics(self) -> CapacityLimiterStatistics:
837
+ orig = self.__original.statistics()
838
+ return CapacityLimiterStatistics(
839
+ borrowed_tokens=orig.borrowed_tokens,
840
+ total_tokens=orig.total_tokens,
841
+ borrowers=tuple(orig.borrowers),
842
+ tasks_waiting=orig.tasks_waiting,
843
+ )
844
+
845
+
846
+ _capacity_limiter_wrapper: trio.lowlevel.RunVar = RunVar("_capacity_limiter_wrapper")
847
+
848
+
849
+ #
850
+ # Signal handling
851
+ #
852
+
853
+
854
+ class _SignalReceiver:
855
+ _iterator: AsyncIterator[int]
856
+
857
+ def __init__(self, signals: tuple[Signals, ...]):
858
+ self._signals = signals
859
+
860
+ def __enter__(self) -> _SignalReceiver:
861
+ self._cm = trio.open_signal_receiver(*self._signals)
862
+ self._iterator = self._cm.__enter__()
863
+ return self
864
+
865
+ def __exit__(
866
+ self,
867
+ exc_type: type[BaseException] | None,
868
+ exc_val: BaseException | None,
869
+ exc_tb: TracebackType | None,
870
+ ) -> bool | None:
871
+ return self._cm.__exit__(exc_type, exc_val, exc_tb)
872
+
873
+ def __aiter__(self) -> _SignalReceiver:
874
+ return self
875
+
876
+ async def __anext__(self) -> Signals:
877
+ signum = await self._iterator.__anext__()
878
+ return Signals(signum)
879
+
880
+
881
+ #
882
+ # Testing and debugging
883
+ #
884
+
885
+
886
+ class TestRunner(abc.TestRunner):
887
+ def __init__(self, **options: Any) -> None:
888
+ from queue import Queue
889
+
890
+ self._call_queue: Queue[Callable[[], object]] = Queue()
891
+ self._send_stream: MemoryObjectSendStream | None = None
892
+ self._options = options
893
+
894
+ def __exit__(
895
+ self,
896
+ exc_type: type[BaseException] | None,
897
+ exc_val: BaseException | None,
898
+ exc_tb: types.TracebackType | None,
899
+ ) -> None:
900
+ if self._send_stream:
901
+ self._send_stream.close()
902
+ while self._send_stream is not None:
903
+ self._call_queue.get()()
904
+
905
+ async def _run_tests_and_fixtures(self) -> None:
906
+ self._send_stream, receive_stream = create_memory_object_stream(1)
907
+ with receive_stream:
908
+ async for coro, outcome_holder in receive_stream:
909
+ try:
910
+ retval = await coro
911
+ except BaseException as exc:
912
+ outcome_holder.append(Error(exc))
913
+ else:
914
+ outcome_holder.append(Value(retval))
915
+
916
+ def _main_task_finished(self, outcome: object) -> None:
917
+ self._send_stream = None
918
+
919
+ def _call_in_runner_task(
920
+ self,
921
+ func: Callable[P, Awaitable[T_Retval]],
922
+ *args: P.args,
923
+ **kwargs: P.kwargs,
924
+ ) -> T_Retval:
925
+ if self._send_stream is None:
926
+ trio.lowlevel.start_guest_run(
927
+ self._run_tests_and_fixtures,
928
+ run_sync_soon_threadsafe=self._call_queue.put,
929
+ done_callback=self._main_task_finished,
930
+ **self._options,
931
+ )
932
+ while self._send_stream is None:
933
+ self._call_queue.get()()
934
+
935
+ outcome_holder: list[Outcome] = []
936
+ self._send_stream.send_nowait((func(*args, **kwargs), outcome_holder))
937
+ while not outcome_holder:
938
+ self._call_queue.get()()
939
+
940
+ return outcome_holder[0].unwrap()
941
+
942
+ def run_asyncgen_fixture(
943
+ self,
944
+ fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]],
945
+ kwargs: dict[str, Any],
946
+ ) -> Iterable[T_Retval]:
947
+ asyncgen = fixture_func(**kwargs)
948
+ fixturevalue: T_Retval = self._call_in_runner_task(asyncgen.asend, None)
949
+
950
+ yield fixturevalue
951
+
952
+ try:
953
+ self._call_in_runner_task(asyncgen.asend, None)
954
+ except StopAsyncIteration:
955
+ pass
956
+ else:
957
+ self._call_in_runner_task(asyncgen.aclose)
958
+ raise RuntimeError("Async generator fixture did not stop")
959
+
960
+ def run_fixture(
961
+ self,
962
+ fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]],
963
+ kwargs: dict[str, Any],
964
+ ) -> T_Retval:
965
+ return self._call_in_runner_task(fixture_func, **kwargs)
966
+
967
+ def run_test(
968
+ self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any]
969
+ ) -> None:
970
+ self._call_in_runner_task(test_func, **kwargs)
971
+
972
+
973
+ class TrioTaskInfo(TaskInfo):
974
+ def __init__(self, task: trio.lowlevel.Task):
975
+ parent_id = None
976
+ if task.parent_nursery and task.parent_nursery.parent_task:
977
+ parent_id = id(task.parent_nursery.parent_task)
978
+
979
+ super().__init__(id(task), parent_id, task.name, task.coro)
980
+ self._task = weakref.proxy(task)
981
+
982
+ def has_pending_cancellation(self) -> bool:
983
+ try:
984
+ return self._task._cancel_status.effectively_cancelled
985
+ except ReferenceError:
986
+ # If the task is no longer around, it surely doesn't have a cancellation
987
+ # pending
988
+ return False
989
+
990
+
991
+ class TrioBackend(AsyncBackend):
992
+ @classmethod
993
+ def run(
994
+ cls,
995
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
996
+ args: tuple[Unpack[PosArgsT]],
997
+ kwargs: dict[str, Any],
998
+ options: dict[str, Any],
999
+ ) -> T_Retval:
1000
+ return trio.run(func, *args)
1001
+
1002
+ @classmethod
1003
+ def current_token(cls) -> object:
1004
+ return trio.lowlevel.current_trio_token()
1005
+
1006
+ @classmethod
1007
+ def current_time(cls) -> float:
1008
+ return trio.current_time()
1009
+
1010
+ @classmethod
1011
+ def cancelled_exception_class(cls) -> type[BaseException]:
1012
+ return trio.Cancelled
1013
+
1014
+ @classmethod
1015
+ async def checkpoint(cls) -> None:
1016
+ await trio.lowlevel.checkpoint()
1017
+
1018
+ @classmethod
1019
+ async def checkpoint_if_cancelled(cls) -> None:
1020
+ await trio.lowlevel.checkpoint_if_cancelled()
1021
+
1022
+ @classmethod
1023
+ async def cancel_shielded_checkpoint(cls) -> None:
1024
+ await trio.lowlevel.cancel_shielded_checkpoint()
1025
+
1026
+ @classmethod
1027
+ async def sleep(cls, delay: float) -> None:
1028
+ await trio.sleep(delay)
1029
+
1030
+ @classmethod
1031
+ def create_cancel_scope(
1032
+ cls, *, deadline: float = math.inf, shield: bool = False
1033
+ ) -> abc.CancelScope:
1034
+ return CancelScope(deadline=deadline, shield=shield)
1035
+
1036
+ @classmethod
1037
+ def current_effective_deadline(cls) -> float:
1038
+ return trio.current_effective_deadline()
1039
+
1040
+ @classmethod
1041
+ def create_task_group(cls) -> abc.TaskGroup:
1042
+ return TaskGroup()
1043
+
1044
+ @classmethod
1045
+ def create_event(cls) -> abc.Event:
1046
+ return Event()
1047
+
1048
+ @classmethod
1049
+ def create_lock(cls, *, fast_acquire: bool) -> Lock:
1050
+ return Lock(fast_acquire=fast_acquire)
1051
+
1052
+ @classmethod
1053
+ def create_semaphore(
1054
+ cls,
1055
+ initial_value: int,
1056
+ *,
1057
+ max_value: int | None = None,
1058
+ fast_acquire: bool = False,
1059
+ ) -> abc.Semaphore:
1060
+ return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire)
1061
+
1062
+ @classmethod
1063
+ def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter:
1064
+ return CapacityLimiter(total_tokens)
1065
+
1066
+ @classmethod
1067
+ async def run_sync_in_worker_thread(
1068
+ cls,
1069
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
1070
+ args: tuple[Unpack[PosArgsT]],
1071
+ abandon_on_cancel: bool = False,
1072
+ limiter: abc.CapacityLimiter | None = None,
1073
+ ) -> T_Retval:
1074
+ def wrapper() -> T_Retval:
1075
+ with claim_worker_thread(TrioBackend, token):
1076
+ return func(*args)
1077
+
1078
+ token = TrioBackend.current_token()
1079
+ return await run_sync(
1080
+ wrapper,
1081
+ abandon_on_cancel=abandon_on_cancel,
1082
+ limiter=cast(trio.CapacityLimiter, limiter),
1083
+ )
1084
+
1085
+ @classmethod
1086
+ def check_cancelled(cls) -> None:
1087
+ trio.from_thread.check_cancelled()
1088
+
1089
+ @classmethod
1090
+ def run_async_from_thread(
1091
+ cls,
1092
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
1093
+ args: tuple[Unpack[PosArgsT]],
1094
+ token: object,
1095
+ ) -> T_Retval:
1096
+ return trio.from_thread.run(func, *args)
1097
+
1098
+ @classmethod
1099
+ def run_sync_from_thread(
1100
+ cls,
1101
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
1102
+ args: tuple[Unpack[PosArgsT]],
1103
+ token: object,
1104
+ ) -> T_Retval:
1105
+ return trio.from_thread.run_sync(func, *args)
1106
+
1107
+ @classmethod
1108
+ def create_blocking_portal(cls) -> abc.BlockingPortal:
1109
+ return BlockingPortal()
1110
+
1111
+ @classmethod
1112
+ async def open_process(
1113
+ cls,
1114
+ command: StrOrBytesPath | Sequence[StrOrBytesPath],
1115
+ *,
1116
+ stdin: int | IO[Any] | None,
1117
+ stdout: int | IO[Any] | None,
1118
+ stderr: int | IO[Any] | None,
1119
+ **kwargs: Any,
1120
+ ) -> Process:
1121
+ def convert_item(item: StrOrBytesPath) -> str:
1122
+ str_or_bytes = os.fspath(item)
1123
+ if isinstance(str_or_bytes, str):
1124
+ return str_or_bytes
1125
+ else:
1126
+ return os.fsdecode(str_or_bytes)
1127
+
1128
+ if isinstance(command, (str, bytes, PathLike)):
1129
+ process = await trio.lowlevel.open_process(
1130
+ convert_item(command),
1131
+ stdin=stdin,
1132
+ stdout=stdout,
1133
+ stderr=stderr,
1134
+ shell=True,
1135
+ **kwargs,
1136
+ )
1137
+ else:
1138
+ process = await trio.lowlevel.open_process(
1139
+ [convert_item(item) for item in command],
1140
+ stdin=stdin,
1141
+ stdout=stdout,
1142
+ stderr=stderr,
1143
+ shell=False,
1144
+ **kwargs,
1145
+ )
1146
+
1147
+ stdin_stream = SendStreamWrapper(process.stdin) if process.stdin else None
1148
+ stdout_stream = ReceiveStreamWrapper(process.stdout) if process.stdout else None
1149
+ stderr_stream = ReceiveStreamWrapper(process.stderr) if process.stderr else None
1150
+ return Process(process, stdin_stream, stdout_stream, stderr_stream)
1151
+
1152
+ @classmethod
1153
+ def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None:
1154
+ trio.lowlevel.spawn_system_task(_shutdown_process_pool, workers)
1155
+
1156
+ @classmethod
1157
+ async def connect_tcp(
1158
+ cls, host: str, port: int, local_address: IPSockAddrType | None = None
1159
+ ) -> SocketStream:
1160
+ family = socket.AF_INET6 if ":" in host else socket.AF_INET
1161
+ trio_socket = trio.socket.socket(family)
1162
+ trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
1163
+ if local_address:
1164
+ await trio_socket.bind(local_address)
1165
+
1166
+ try:
1167
+ await trio_socket.connect((host, port))
1168
+ except BaseException:
1169
+ trio_socket.close()
1170
+ raise
1171
+
1172
+ return SocketStream(trio_socket)
1173
+
1174
+ @classmethod
1175
+ async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream:
1176
+ trio_socket = trio.socket.socket(socket.AF_UNIX)
1177
+ try:
1178
+ await trio_socket.connect(path)
1179
+ except BaseException:
1180
+ trio_socket.close()
1181
+ raise
1182
+
1183
+ return UNIXSocketStream(trio_socket)
1184
+
1185
+ @classmethod
1186
+ def create_tcp_listener(cls, sock: socket.socket) -> abc.SocketListener:
1187
+ return TCPSocketListener(sock)
1188
+
1189
+ @classmethod
1190
+ def create_unix_listener(cls, sock: socket.socket) -> abc.SocketListener:
1191
+ return UNIXSocketListener(sock)
1192
+
1193
+ @classmethod
1194
+ async def create_udp_socket(
1195
+ cls,
1196
+ family: socket.AddressFamily,
1197
+ local_address: IPSockAddrType | None,
1198
+ remote_address: IPSockAddrType | None,
1199
+ reuse_port: bool,
1200
+ ) -> UDPSocket | ConnectedUDPSocket:
1201
+ trio_socket = trio.socket.socket(family=family, type=socket.SOCK_DGRAM)
1202
+
1203
+ if reuse_port:
1204
+ trio_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
1205
+
1206
+ if local_address:
1207
+ await trio_socket.bind(local_address)
1208
+
1209
+ if remote_address:
1210
+ await trio_socket.connect(remote_address)
1211
+ return ConnectedUDPSocket(trio_socket)
1212
+ else:
1213
+ return UDPSocket(trio_socket)
1214
+
1215
+ @classmethod
1216
+ @overload
1217
+ async def create_unix_datagram_socket(
1218
+ cls, raw_socket: socket.socket, remote_path: None
1219
+ ) -> abc.UNIXDatagramSocket: ...
1220
+
1221
+ @classmethod
1222
+ @overload
1223
+ async def create_unix_datagram_socket(
1224
+ cls, raw_socket: socket.socket, remote_path: str | bytes
1225
+ ) -> abc.ConnectedUNIXDatagramSocket: ...
1226
+
1227
+ @classmethod
1228
+ async def create_unix_datagram_socket(
1229
+ cls, raw_socket: socket.socket, remote_path: str | bytes | None
1230
+ ) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket:
1231
+ trio_socket = trio.socket.from_stdlib_socket(raw_socket)
1232
+
1233
+ if remote_path:
1234
+ await trio_socket.connect(remote_path)
1235
+ return ConnectedUNIXDatagramSocket(trio_socket)
1236
+ else:
1237
+ return UNIXDatagramSocket(trio_socket)
1238
+
1239
+ @classmethod
1240
+ async def getaddrinfo(
1241
+ cls,
1242
+ host: bytes | str | None,
1243
+ port: str | int | None,
1244
+ *,
1245
+ family: int | AddressFamily = 0,
1246
+ type: int | SocketKind = 0,
1247
+ proto: int = 0,
1248
+ flags: int = 0,
1249
+ ) -> list[
1250
+ tuple[
1251
+ AddressFamily,
1252
+ SocketKind,
1253
+ int,
1254
+ str,
1255
+ tuple[str, int] | tuple[str, int, int, int],
1256
+ ]
1257
+ ]:
1258
+ return await trio.socket.getaddrinfo(host, port, family, type, proto, flags)
1259
+
1260
+ @classmethod
1261
+ async def getnameinfo(
1262
+ cls, sockaddr: IPSockAddrType, flags: int = 0
1263
+ ) -> tuple[str, str]:
1264
+ return await trio.socket.getnameinfo(sockaddr, flags)
1265
+
1266
+ @classmethod
1267
+ async def wait_readable(cls, obj: HasFileno | int) -> None:
1268
+ try:
1269
+ await wait_readable(obj)
1270
+ except trio.ClosedResourceError as exc:
1271
+ raise ClosedResourceError().with_traceback(exc.__traceback__) from None
1272
+ except trio.BusyResourceError:
1273
+ raise BusyResourceError("reading from") from None
1274
+
1275
+ @classmethod
1276
+ async def wait_writable(cls, obj: HasFileno | int) -> None:
1277
+ try:
1278
+ await wait_writable(obj)
1279
+ except trio.ClosedResourceError as exc:
1280
+ raise ClosedResourceError().with_traceback(exc.__traceback__) from None
1281
+ except trio.BusyResourceError:
1282
+ raise BusyResourceError("writing to") from None
1283
+
1284
+ @classmethod
1285
+ def current_default_thread_limiter(cls) -> CapacityLimiter:
1286
+ try:
1287
+ return _capacity_limiter_wrapper.get()
1288
+ except LookupError:
1289
+ limiter = CapacityLimiter(
1290
+ original=trio.to_thread.current_default_thread_limiter()
1291
+ )
1292
+ _capacity_limiter_wrapper.set(limiter)
1293
+ return limiter
1294
+
1295
+ @classmethod
1296
+ def open_signal_receiver(
1297
+ cls, *signals: Signals
1298
+ ) -> AbstractContextManager[AsyncIterator[Signals]]:
1299
+ return _SignalReceiver(signals)
1300
+
1301
+ @classmethod
1302
+ def get_current_task(cls) -> TaskInfo:
1303
+ task = current_task()
1304
+ return TrioTaskInfo(task)
1305
+
1306
+ @classmethod
1307
+ def get_running_tasks(cls) -> Sequence[TaskInfo]:
1308
+ root_task = current_root_task()
1309
+ assert root_task
1310
+ task_infos = [TrioTaskInfo(root_task)]
1311
+ nurseries = root_task.child_nurseries
1312
+ while nurseries:
1313
+ new_nurseries: list[trio.Nursery] = []
1314
+ for nursery in nurseries:
1315
+ for task in nursery.child_tasks:
1316
+ task_infos.append(TrioTaskInfo(task))
1317
+ new_nurseries.extend(task.child_nurseries)
1318
+
1319
+ nurseries = new_nurseries
1320
+
1321
+ return task_infos
1322
+
1323
+ @classmethod
1324
+ async def wait_all_tasks_blocked(cls) -> None:
1325
+ from trio.testing import wait_all_tasks_blocked
1326
+
1327
+ await wait_all_tasks_blocked()
1328
+
1329
+ @classmethod
1330
+ def create_test_runner(cls, options: dict[str, Any]) -> TestRunner:
1331
+ return TestRunner(**options)
1332
+
1333
+
1334
+ backend_class = TrioBackend
vllm/lib/python3.10/site-packages/anyio/_core/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/anyio/_core/__pycache__/_asyncio_selector_thread.cpython-310.pyc ADDED
Binary file (3.91 kB). View file